SSH: execute sudo command

71,721

The wondrous ssh has a cure for everything. The point is to add the -t flag to force ssh to allocate a pseudo-tty:

ssh -t remote-server 'sudo ls'
Share:
71,721

Related videos on Youtube

Boldewyn
Author by

Boldewyn

Boldewyn is the name of the donkey in German fables (at least, the ones from Goethe). Despite its bad name, a donkey is an animal with its own head and quite a portion of wit. As someone pointed out once, if you say to a horse to jump down that abyss, it would happily do so, whereas the donkey would give you a kick where you deserve it to. And someone else pointed out, that laziness is a core requirement for a good developer...

Updated on September 17, 2022

Comments

  • Boldewyn
    Boldewyn almost 2 years

    I have an interactive shell script, that at one place needs to ssh to another machine (Ubuntu based) and execute something as root (the user should enter his password, but the remote command should run like noted in the script):

    # ...
    ssh remote-machine 'sudo ls'
    # ...
    

    However, I always get this error message back:

    sudo: no tty present and no askpass program specified
    

    OK, that's quite clear. But how can I circumvent this? Something like this should happen:

    $ ssh remote-machine 'sudo ls /'
    [sudo] password for user1:
    
    /bin
    /etc
    /var
    
  • Tobu
    Tobu about 14 years
    PTYs can mess things up with scripts, however. ls output will contain \r\n endings for example.
  • Gabe
    Gabe about 11 years
    The easy way around that is to force ls into non-terminal mode. ls | cat will do - it'll see that stdout is a pipe. In this specific question, that's not relevant, as it's apparently intended to be run interactively from a terminal - so you probably want the columns and colours and whatnot.
  • Boldewyn
    Boldewyn almost 9 years
    Uh oh. Putting your remote user in the sudoers file on a server like this is a catastrophe waiting to happen. If anyone gains access as your user (e.g. via the web server), he can immediately become root. Thank you, but I was looking for solutions, that do not place my server config at odds. If you had a solution, that somehow magically re-uses the authentication from SSH for the sudo command, I'd be more interested (and perhaps would start to search for replacements for SSH...).
  • lepe
    lepe almost 9 years
    @Boldewyn : yes, setting "sudo without password" has that security risk... its an optional step. I agree with you, if SSH could re-use the authentication, this kind of "solutions" wouldn't be required. Thanks for your comment.
  • Anthony Geoghegan
    Anthony Geoghegan about 8 years
    That won't work because stdin won't be a terminal device (it will be reading from the specified file).