0

I have one PowerShell script which I want to run on a remote windows machine using my Node.js code(I have credentials of the machine). any idea how to achieve this?

2
  • Would you please explain more? Commented Jul 14, 2019 at 7:06
  • @El. I want to create a Node.js script that can run a PowerShell script on a remote windows server using admin credentials. so I have my PowerShell script, I have credentials of the remote windows server. what I want to achieve is run this PowerShell script on that remote windows server using Node.Js code. Commented Jul 14, 2019 at 7:18

1 Answer 1

1

You can use nodejs child_process spawn module for spawning a ssh process and then execute the batch or bash file, if you are in windows machine this code makes it for you:

const { spawn } = require("child_process");

const ssh = spawn(
    "powershell",
    ["ssh", "user@remoteserverip", "powershell path/to/batch/file"]
    );

ssh.stdout.on("data", data => {
    // Do whatever you want with stream of data from server
    console.log(data.toString());
});

ssh.stderr.on("data", err => {
    // Do whatever you want with err from execution of batch script
    console.error(err);
});

ssh.on("exit", code => {
    if(code === 0){
        // Process successfully ended so you can chain anything 
    }
    // Do whatever you want with other codes that process sends
})

If you are in a windows machine you need to spawn Powershell or Command Prompt process. Keep in mind that Powershell must be in path of environment variables and if you want to use Command Prompt you need to spawn process with a /c flag like spawn("cmd", ["/c", "other cammands"])

And if you on an UNIX machine like Linux or Mac just spawn the process directly like below:

const ssh = spawn(
    "ssh",
    ["user@remoteserverip", "powershell path/to/batch/file"]
    );

And the rest is the same.

Sign up to request clarification or add additional context in comments.

2 Comments

child_process is used to execute commands locally on the machine where node.js is running. It doesn't execute commands on remote servers.
@Yogesh.Kathayat you can run Invoke-Command locally to run your script on remote machine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.