开发者

C# running batch file on remote machine after PsExec has been started

Basically, I'm trying to run the batch file that was copied on the remote machine, by the way, this is my first attempt at coding, so please be nice but critique it if you want, I'm still learning the language and had to spend 3 hours to get this far, thank god for Google, LOL.

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Form开发者_StackOverflows;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void cleanerBtn_Click(object sender, EventArgs e)
        {
            //Copying Batch File to Remote Host
            string fileToCopy = "C:\\Clean.bat";
            string newLocation = hostName.Text;
            string newFile = (newLocation + "\\clean.bat");

            System.IO.File.Copy(fileToCopy, newLocation);

            //Run PsExec
            string psExec = "psexec -s "+newLocation+" cmd";
            System.Diagnostics.Process.Start("CMD.exe", psExec);

            //Run Batch File using PsExec


            //Removing Batch File from Remote Host
            System.IO.File.Delete(newFile);

        }

    }
}

Thanks in advance.


From PSExec help:

-c Copy the specified program to the remote system for execution. If you omit this option the application must be in the system path on the remote system.

Use that flag to make PSExec copy the batch file that you want executed to the remote system and run it. You don't have to write extra code to do that.

Basically you want to do:

psexec \\server cmd.exe /c file_you_want_to_run.bat


Try running CMD.exe with /C. From cmd.exe help:

/C Carries out the command specified by string and then terminates

The /C needs to be appended to the content of the psExec:

System.Diagnostics.Process.Start("CMD.exe", "/C " + psExec);

I believe you'll get the expected results then. If not, you might want to make sure psexec.exe is in a directory that is in the PATH environment variable.

Also, you might be interested to look into ProcessStartInfo to specify different other parameters that can be set for the execution of a process.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜