47

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
wonea
  • 1,877
Boldewyn
  • 4,468

3 Answers3

55

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'
Boldewyn
  • 4,468
0

This method will run a single script using sudo after ssh:

Let's assume we have a "remote" user with sudo capabilities and we have a script we want it to execute as root.

1) Set a script in /etc/passwd to be used on login:

remote:x:1100:1100:Some Remote User,,,:/home/remote:/home/remote/login.sh

2) Inside "login.sh", we execute the script we want to run as "sudo":

#!/bin/bash
if [ "$(id -u)" != "0" ]; then
    #Not running as root, so we execute "sudo"
    sudo /usr/local/bin/script.sh
else
    #We are already rooted, so "sudo" is not required.
    /usr/local/bin/script.sh
fi
exit;

Normally it will ask the password twice: ssh login + sudo. If you want to input it only once, try sudo without password (not recommended). <-- please read Boldewyn comment.

The main advantage is that "ssh" does not require any other parameter (as -t), and sudo is forced on server side. Also, once the script exits, the user is logged out as well.

It may not be that elegant, but its simple and works.

lepe
  • 798
  • 9
  • 17
-1

You can run following command get root access without interactivity:

ssh server " sudo command" < sudopassword.txt
SilentGuy
  • 101
  • 1