Paramiko and Pseudo-tty Allocation

守給你的承諾、 提交于 2019-11-26 08:23:38

问题


I\'m trying to use Paramiko to connect to a remote host and execute a number of text file substitutions.

i, o, e = client.exec_command(\"perl -p -i -e \'s/\" + initial + \"/\" 
                              + replaced + \"/g\'\" + conf);

Some of these commands need to be run as sudo, which results in:

sudo: sorry, you must have a tty to run sudo

I can force pseudo-tty allocation with the -t switch and ssh.

Is it possible to do the same thing using paramiko?


回答1:


I think you want the invoke_shell method of the SSHClient object (I'd love to give a URL but the paramiko docs at lag.net are frame-heavy and just won't show me a specific URL for a given spot in the docs) -- it gives you a Channel, on which you can do exec_command and the like, but does that through a pseudo-terminal (complete with terminal type and numbers of rows and columns!-) which seems to be what you're asking for.




回答2:


Actually it's quite simple. Just:

stdin, stdout, stderr = client.exec_command(command,  get_pty=True)



回答3:


The following code works for me:

#!/usr/bin/env python
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('localhost',username='root',password='secret')
chan = ssh.get_transport().open_session()
chan.get_pty()
chan.exec_command('tty')
print(chan.recv(1024))

This was just assembled from looking at a few examples online... not sure if its the "right" way.




回答4:


According to the sudo manpage:

The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device. The password must be followed by a newline character.

You can write to the stdin because it is a file object with write():

import paramiko

client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
client.connect(hostname='localhost', port=22, username='user', password='password')
stdin, stdout, stderr = client.exec_command('sudo -S aptitude update')
stdin.write('password\n')
stdin.flush()
# print the results
print stdout.read()
client.close()


来源:https://stackoverflow.com/questions/2909481/paramiko-and-pseudo-tty-allocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!