Executing remote command with paramiko

H

Hussein B

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

Piet van Oostrum

Hussein B said:
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')
instead.

Or use the lower-level constructs:

s = paramiko.SSHClient()
s.load_system_host_keys()
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'
chan.send('whoami\n')
print "try to read"
print chan.recv(9999)

For more control you can use chan.recv_ready() to see if output is available.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top