Search code examples
c#batch-fileprocesspowershell-remoting

Execute batch file on remote PC from a webpage on user action


I have a webpage written in MVC C#. I want to run some batch file (on a remote PC) on user action in this page. I have the following function to run batch files on remote PC:

public bool runBatch(string address, string batchFile, string pwd, string username) {
    try {
        string AppPath = address;

        string strFilePath = AppPath + batchFile;
        Process proc = new Process();
        proc.StartInfo.FileName = strFilePath;
        proc.StartInfo.UserName = username;
        proc.StartInfo.Domain = "localdomain";
        System.Security.SecureString secret = new System.Security.SecureString();
        foreach (char c in pwd)
            secret.AppendChar(c);

        proc.StartInfo.Password = secret;
        proc.StartInfo.UseShellExecute = false;

        proc.Start();

        while (!proc.HasExited) {
            proc.Refresh();
            Thread.Sleep(1000);
        }

        proc.Close();

        return true;
    } catch (Exception ex) {
        return false;
        throw ex;
    }
}

and I call this function like this:

var run = runBatch("X.X.X.X:\\\\C:Users\\Admin\\Desktop\\", "ping.bat", "****", "Admin");

My PCs are in same IP domain and I have checked username and passwords multiple times, but I got an error

username and password incorrect

I'm really confused.can any one help me with that?


Solution

  • As some of friends help me with this question I will answer so maybe it can save time for another one. The problem with my code was that i was giving file adrress in a wrong way and. I have to call it like this:

    var run = runBatch(@"\\x.x.x.x\C$\Users\Admin\Desktop\", "ping.bat", "****", "Admin");
    

    Another thing to remember is that process can see shared folders on the path we gave!