【发布时间】:2016-10-26 01:24:59
【问题描述】:
我已经编写了下面的代码以交互方式在远程服务器中运行 3 个命令
但是当我检查第 3 个命令从未执行并且卡在这里的代码是我的代码时
def execute():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ipaddress', username='user', password='pw')
chan = ssh.invoke_shell() # start the shell before sending commands
chan.send('cd /path to folder/test')
chan.send('\n')
time.sleep(3)
chan.send("ls -l")
chan.send('\n')
buff = ''
while not buff.endswith("test >"):
resp = chan.recv(9999)
# code stuck here after 'path to folder/test >' comes in shell prompt
buff += resp
print resp
print "test"
chan.send("ls -lh")
chan.send('\n')
time.sleep(5)
buff = ''
while not buff.endswith("test >"):
resp = chan.recv(9999)
buff += resp
print resp
if __name__ == "__main__":
execute()
当我运行时,我得到了 ls -l 的输出,但 ls -lh 从未执行过我的代码,卡在第一个 while 循环中。请任何人帮助解决我的问题
【问题讨论】:
-
据我所知,您实际上并不需要启动外壳,如果您直接使用外壳就会知道一些安全问题。您在客户端类中尝试过
exec_command吗? -
我没试过我认为在 shell 中执行交互式命令 invoke_shell 是正确的 api
-
不,不是。您应该尝试 exec_command,因为它会将所有 3 个频道返回给您。
-
我使用了 invoke_shell 因为我需要从特定文件夹一个接一个地执行命令序列,这就是为什么如果我使用 execute_command 则通道在执行第一个命令后关闭
-
exec_command也可以。你应该阅读文档。