我想编写一个程序(在Windows7上的Python3.x中),通过ssh在远程shell上执行多个命令。在查看paramikos'exec_command()
函数之后,我意识到它不适合我的用例(因为在执行命令之后通道会关闭),因为命令依赖于环境变量(由先前的命令设置),并且不能连接到一个exec_command()
调用中,因为它们将在程序中的不同时间执行。
因此,我想在同一个通道中执行命令。我研究的下一个选项是使用paramikos'invoke_shell()
函数实现交互式shell:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=psw, port=22)
channel = ssh.invoke_shell()
out = channel.recv(9999)
channel.send('cd mivne_final\n')
channel.send('ls\n')
while not channel.recv_ready():
time.sleep(3)
out = channel.recv(9999)
print(out.decode("ascii"))
channel.send('cd ..\n')
channel.send('cd or_fail\n')
channel.send('ls\n')
while not channel.recv_ready():
time.sleep(3)
out = channel.recv(9999)
print(out.decode("ascii"))
channel.send('cd ..\n')
channel.send('cd simulator\n')
channel.send('ls\n')
while not channel.recv_ready():
time.sleep(3)
out = channel.recv(9999)
print(out.decode("ascii"))
ssh.close()
此代码有一些问题:
print
并不总是打印ls
输出(有时它只打印在第二个print
)。cd
和ls
命令始终出现在输出中(作为输出的一部分,我通过recv
命令获取它们),而下面的cd
和ls
命令有时会打印,有时不会打印cd
和ls
命令(打印时)总是出现在第一个ls
输出之前。我对这种“非决定论”感到困惑,非常感谢你的帮助。
相关问题 更多 >
编程相关推荐