Running commands as another user on their machine via ssh?

3

1

As part of my normal workflow I ssh into another user's machine, switch user to them, run a command, then exit out to my own machine again:

ssh hostname
sudo su user
runcommand
exit
exit

Is there a way to cut this down to a single line command? e.g.

ssh --someflags "runcommand"

I have tried this but get prompted for the other user's password which I do not have:

sudo ssh user@hostnme "runcommand"

Esker

Posted 2013-10-04T18:46:45.033

Reputation: 33

Something like ssh myaccount@somehost "su -u <user> -c <command>" wouldn't work? – Fiisch – 2013-10-04T18:56:03.923

You could always publish your key into their authorized_keys file. Then you can connect to using that users account directly. – Zoredache – 2013-10-04T19:28:39.117

Answers

6

Do you have a user on all of the remote computers? I guess this should work, but im not sure i understand your setup correctly.

ssh youruser@hostname "sudo -u remoteuser runcommand"

piksel bitworks

Posted 2013-10-04T18:46:45.033

Reputation: 178

And how exactly does this address the Esker's problem? – Fiisch – 2013-10-04T18:59:09.530

Yeah, I misread. Updated the answer. – piksel bitworks – 2013-10-04T19:00:28.937

2With a bit of tweaking, that worked, thanks. ssh -t hostname "sudo su user -c runcommand" – Esker – 2013-10-04T19:03:10.483

1

It's often the case that a terminal is required as well. The following should work in this case:

commands='cd myfolder;ls -l'

ssh -ttt "youruser@remotehost" "sudo -u remoteuser sh -c ${commands}"

Thomas Bratt

Posted 2013-10-04T18:46:45.033

Reputation: 803