I am trying to execute a sudo command on a remote machine using python-paramiko, when I execute the command, I bind it with 3 streams, and I use the input stream to pass the
I know this question is kind of old but I was wanting to use sudo and paramiko together, too. It took me a while to figure out this solution. It may not work for everyone but I figured it was worth adding.
def ssh_handler(hostname, username=USER, password=PASS, command=CMD):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,
username=username,
password=password)
stdin, stdout, stderr = ssh.exec_command(prepare_command(command))
# stdin.write(password+'\n')
response = stdout.read()
ssh.close()
print response
def prepare_command(command):
if (not isinstance(command, basestring)):
command = ' ; '.join(command)
command = command.replace('"','\"')
command = 'sudo -s -- " '+command+' " \n'
return command
# kind of a dumb example but you get the point
mycmd = [];
mycmd.append('cd /dir/this/user/doesnt/have/access/to')
mycmd.append('ls -las')
mycmd.append('cat file_in_dir.txt')
ssh_handler(server, command=mycmd)