Execute command on remote machine as different user via SSH

Execute command on remote machine as different user via SSH

To execute command on remote machine as different user via SSH, you may need to run the below command

ssh -t user@host sudo -u<other_user_name> sh -c /path/to/script.sh

In our example, we are executing the script.sh as root after login to the server as testuser

ssh -t testuser@162.23.45.67 sudo -uroot sh -c /home/testuser/script.sh

If you are trying to execute a command to action a file on remote machine as a different user, you need to run the below command,

ssh -t user@host sudo -u<other_user_name> sh -c 'command /path/to/file'

In our example, we are executing the script.sh as root after login to the server as testuser

ssh -t user@host sudo -u<other_user_name> sh -c 'cat /path/to/file'

If you wish to reboot a remote server as a different user, please execute,

ssh -t testuser@162.23.45.67 sudo -uroot sh -c 'reboot'

To execute multiple commands via SSH, please execute,

ssh user@host << EOF
command1
command2
command3
EOF

Example script below,

ssh testuser@162.23.45.67 << EOF
uname -a
cat /proc/cpuinfo
free -m
EOF

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.