Linux – using python Paramiko for ssh: sudo: no tty present and no askpass program specified


I want to use paramiko to ssh into a bunch a remote nodes and run some command line with root priviledge

I have ssh key in my home directory and so i don't need to input password when I ssh into those remote nodes

but when running the following script:

    def connect(hostname):
                    ssh = paramiko.SSHClient()
                    ssh.connect(hostname, username='niky', pkey=paramiko.RSAKey.from_private_key(open('id_rsa'), 'passwd'), timeout = 240.0)                return ssh          

    def run(hostname):
            ssh = connect(hostname)
            (stdin, stdout, stderr) = ssh.exec_command("sudo ls")
            res = stderr.readlines()
            print hostname+': '+''.join(str(elem) for elem in res)+'\n'


I got the following error: sudo: no tty present and no askpass program specified

if I don't add sudo before ls
everything works fine
what are potential reasons ?

Best Answer

In the stock sudoers configuration, the following line is usually present:

Defaults requiretty

This is both secure and what you need in the majority of the use cases.

In your case, you need to override this default for a specific user, so you would write below:

Defaults:niky !requiretty

Also, you need to define a line allowing niky to call sudo without password:

niky = (root)NOPASSWD: /bin/ls

This line means that the user niky is allowed to execute /bin/ls as root in without requiring a password.

Further reference can be found in here.