Can anyone help me to to solve following issue
i need to ssh to another server by eg ubuntu
user which has permission to run sudo su fore sure then execute pm2 restart command
full command look like this
#!/bin/sh
CMD="sudo su; pm2 restart 0; pm2 restart 1; exit;"
ssh -i somepemfile.pem ubuntu@1.1.1.1 $CMD
for example i can run normally any command with sudo
CMD="sudo /etc/init.d/apache2 restart"
but with sudo su
case it somehow hang and do not response
Unless you have an unusual setup, you can't normally string su
with other preceding commands like that. I would imagine it is running sudo su
, then hanging in the root environment/session, because it's waiting for you to exit before preceding to the pm2
commands. Instead, I would consider something along the lines of this using the -c
option:
CMD="sudo su -c 'pm2 restart 0; pm2 restart 1'"
ssh -i somepemfile.pem ubuntu@1.1.1.1 "$CMD"
As suggested in another answer, it would also probably be useful to encapsulate the $CMD
variable in quotes in the ssh
call.
Use -c
option of su
to specify the command
From man su
In particular, an argument of -c will cause the next argument to be treated as a command by most command interpreters. The command will be executed by the shell specified in /etc/passwd for the target user.
CMD="sudo su -c \"pm2 restart 0; pm2 restart 1;\""
You need to quote the expansion so that the entire string is parsed on the remote end.
ssh -i somepemfile.pem ubuntu@1.1.1.1 "$CMD"
Otherwise, the expansion is subject to word splitting, and the remote shell gets a string which consists of the command sudo
and the arguments su;
, restart
, 0;
, pm2
, restart;
, 1;
, and exit;
. That is, ssh
will escape the semicolons when it builds a single string from the separate arguments you pass.
However, that doesn't solve the problem of running pm2
in the shell started by sudo
. That is addressed by ramki .
su normally puts you in a sub shell which you can see by echoing the current PID (process id)
$ echo $$
94260
$ sudo echo $$
94260
$ sudo su
$ echo $$
94271
But to get around this you can pipe the commands you want to run to su like this
$ echo "whoami" | sudo su
root
And we run multiple commands
$ echo "uptime;whoami" | sudo su
11:29 up 8 days, 19:20, 4 users, load averages: 4.55 2.96 2.65
root
Now to make this work with ssh
$ ssh wderezin@localhost 'echo "uptime;whoami" | sudo su'
sudo: no tty present and no askpass program specified
Darn it, we need allocate a tty for the su command. Add the -t option which allocates a TTY during the remote execution.
$ ssh -t wderezin@localhost 'echo "uptime;whoami" | sudo su'
11:36 up 8 days, 19:26, 5 users, load averages: 2.97 2.97 2.76
root
Your command would look this
ssh -i somepemfile.pem ubuntu@1.1.1.1 'echo "pm2 restart 0; pm2 restart1" | sudo su'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.