Running commands as another user on their machine via ssh?

31,516

Solution 1

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"

Solution 2

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}"
Share:
31,516

Related videos on Youtube

Esker
Author by

Esker

Updated on September 18, 2022

Comments

  • Esker
    Esker over 1 year

    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"
    
    • Fiisch
      Fiisch over 10 years
      Something like ssh myaccount@somehost "su -u <user> -c <command>" wouldn't work?
    • Zoredache
      Zoredache over 10 years
      You could always publish your key into their authorized_keys file. Then you can connect to using that users account directly.
  • Fiisch
    Fiisch over 10 years
    And how exactly does this address the Esker's problem?
  • piksel bitworks
    piksel bitworks over 10 years
    Yeah, I misread. Updated the answer.
  • Esker
    Esker over 10 years
    With a bit of tweaking, that worked, thanks. ssh -t hostname "sudo su user -c runcommand"