Executing remote command with paramiko

Piet van Oostrum piet at cs.uu.nl
Tue Aug 4 01:26:58 CEST 2009

>>>>> Hussein B <hubaghdadi at gmail.com> (HB) wrote:

>HB> Hey,
>HB> I'm trying to run a sudo guarded command over SSH using paramiko
>HB> +++++++++++++++++++
>HB> s = paramiko.SSHClient()
>HB> s.load_system_host_keys()
>HB> s.connect(hostname, port, username, passwd)
>HB> stdin, stdout, stderr = s.exec_command('sudo -s')
>HB> stdin.write('password\n')
>HB> stdin.flush()
>HB> print 'Flushing'
>HB> stdin, stdout, stderr = s.exec_command('harvester')
>HB> print stdout.read()
>HB> s.close()
>HB> +++++++++++++++++++
>HB> It seems to me that the sudo -s isn't getting executed at all.
>HB> I commented the sudo -s code lines and no error is shown.
>HB> Thanks for help and time.

Your command 'harvester' is not run in the sudo shell, but separately in
a new session. so it will run under 'username', not under 'root'.

You could use 
    stdin, stdout, stderr = s.exec_command('sudo harvester')

Or use the lower-level constructs:

s = paramiko.SSHClient()
s.connect(hostname, port, username, password)
t = s.get_transport()
chan = t.open_session()
chan.exec_command('sudo -s')

print 'writing password'
chan.send(password + '\n')

print 'write command'
print "try to read"
print chan.recv(9999)

For more control you can use chan.recv_ready() to see if output is available.
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org

More information about the Python-list mailing list