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?
-
Would you please explain more?El.– El.2019-07-14 07:06:40 +00:00Commented 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.Yogesh.Kathayat– Yogesh.Kathayat2019-07-14 07:18:03 +00:00Commented Jul 14, 2019 at 7:18
1 Answer
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.
2 Comments
Invoke-Command locally to run your script on remote machine