在PsExec启动后,在远程机器上运行c#批处理文件

本文关键字:机器 运行 批处理文件 启动 PsExec 程机器 | 更新日期: 2023-09-27 17:49:47

基本上,我正在尝试运行远程机器上复制的批处理文件,顺便说一下,这是我第一次尝试编码,所以请很好,但如果你想批评它,我还在学习语言,不得不花3个小时才能走到这一步,感谢上帝,哈哈。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
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);
        }
    }
}

在PsExec启动后,在远程机器上运行c#批处理文件

From PSExec help:

-c将指定的程序复制到远程系统执行。如果省略此选项,则应用程序

必须在远端系统的系统路径中。

使用该标志使PSExec将您想要执行的批处理文件复制到远程系统并运行它。你不需要写额外的代码。

基本上你要做的是:

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

尝试使用/C运行CMD.exe。从cmd.exe帮助:

/C执行string指定的命令,然后终止

/C需要追加到psExec的内容:

System.Diagnostics.Process.Start("CMD.exe", "/C " + psExec);
我相信你会得到预期的结果。如果没有,您可能希望确保psexec.exe位于PATH环境变量下的目录中。

另外,您可能有兴趣查看ProcessStartInfo,以指定可以为进程执行设置的其他不同参数。