-1

this is not a problem related to shell script , this a problem on how to restart or use pm2 commands from spawn process in nodejs from a remote server. running the pm2 commands solo or in a shell script directly on the server , it works fine , but when i use spawn i get the error below.

how to restart pm2, using spawn process , using ssh root@ip

i've tried this

ssh root@ip 'pm2 restart all'

but when i try this on my local pc directly from my terminal it works , but when i try to run it in exces or spawn process , i get this error bash: pm2: command not found failed with code 127

i also tried , putting my commands in script.sh and send it with this command from spawn

scp /root/script.sh root@${ip}:/root&&ssh root@${ip} bash script.sh

i get the same error. but if i run alone in terminal it works , is the error in environment variable , it's not loaded correctly when i run it in spawn prcess.

sasha romanov
  • 485
  • 1
  • 10
  • 26
  • 1
    Possible duplicate of [How to use SSH to run a shell script on a remote machine?](https://stackoverflow.com/questions/305035/how-to-use-ssh-to-run-a-shell-script-on-a-remote-machine) – O. Jones Jun 02 '19 at 12:12
  • @O.Jones this is not a problem in running sell script on another machine , please read the question very carefully , i asked that the problem in spawn process , not in sell script , because i already run it using script.sh and terminal directly , but when i run it with spawn process , the problem occurs – sasha romanov Jun 02 '19 at 12:20
  • What happens if you use `ssh root@ip` to get a shell on the remote machine, and then issue the command `pm2 restart all` ? I bet it doesn't work. I bet `pm2` can't be found in the `PATH` available to the root user on the remote machine. I *know* running `pm2` from root is a bad choice for security reasons. – O. Jones Jun 02 '19 at 12:26
  • @O.Jones i don't want to make a user with root privileges , my question was a problem in spawn process , do i need to load en variables when i run the spawn ? or where is the problem exactly , this is vps server and when i log in i use pm2 command and it works , so why it didn't work when i used only spawn all other commands works just fine, so please tell me exactly what's the error . or how to solve ? – sasha romanov Jun 02 '19 at 13:09

1 Answers1

1
ssh -t root@ip "export PATH='path/to/pm2'; pm2 restart all"

You should include the pathname to pm2 even if it is the current directory (eg ./pm2 or /path/to/pm2) to ensure it is found, or else export PATH=.... before the call to pm2.

Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55