虽然subprocess.Popen
可能适用于包装ssh
访问,但这不是这样做的首选方式。
我建议使用paramiko。
import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(server, username=user,password=password)
...
ssh_client.close()
如果你想模拟一个终端,就好像用户正在输入:
chan=self.ssh_client.invoke_shell()
def exec_cmd(cmd):
"""Gets ssh command(s), execute them, and returns the output"""
prompt='bash $' # the command line prompt in the ssh terminal
buff=''
chan.send(str(cmd)+'\n')
while not chan.recv_ready():
time.sleep(1)
while not buff.endswith(prompt):
buff+=self.chan.recv(1024)
return buff[:len(prompt)]
示例用法:exec_cmd('pwd')
如果你事先不知道提示,你可以这样设置:
chan.send('PS1="python-ssh:"\n')