Home > Mobile >  How to ssh into a machine, switch user (providing the password in the switch command) and run a comm
How to ssh into a machine, switch user (providing the password in the switch command) and run a comm

Time:06-25

I am looking for a way ssh into a machine, switch user and run a command as that user.

In particular, to test the whole journey, I want to

  • ssh into a remote machine
  • echo the machine ip
  • become an existing user (i usually do it with sudo -i -u user_o)
  • echo that user name with $whoami

By reading this thread I have composed this command

ssh user_c@remote_ip "echo $(hostname -I); sudo -i -u user_o echo $(whoami)"

I would expect it enters machine with remote_ip logging in as user_c, then run the equivalent of sudo -i -u user_o and then echoes its own name, so user_o.

Instead, it prints

my_local_machine_ip
current_user_of_local_machine

that is the same that I would have get by running

echo $(hostname -I); echo $(whoami)

I don't get what is wrong.

Update

I did a little steps forward: I changed the command to

ssh user_c@remote_ip 'echo "$(hostname -I)" && sudo -i -u user_o echo "$(whoami)"'

and now I get at least the correct remote machine ip and no error, but the echoed user is user_c, while I want user_o, so I guess it could not become the user_o

CodePudding user response:

SOLVED

By following this thread I got to the solution.

There is no need to separate by && the "switch user" command and the command that one wants to be executed as the target user.

The && instead can be used to separate the commands that we want to execute as different users.

Finally, all the commands that we want to be run via ssh must be enclosed in ' or ".
In this case I am using ' since I am already using " to protect premature expansion of command $(hostname -I).

ssh user_c@remote_ip 'echo "$(hostname -I)" && sudo -i -u user_o whoami'
remote_ip
user_o

In order to run multiple commands as user user_o we can use this syntax:

ssh user_c@remote_ip 'echo "$(hostname -I)" && sudo -i -u user_o <<"EOF"                               
whoami
whoami
whoami
EOF'
remote_ip
user_o   
user_o
user_o 
  • Related