执行交互式工具的命令并使用Paramiko读取其输出



我正在准备一个代码,以使用带有Paramiko的ssh访问远程服务器,并运行一些命令并查看stdout的输出。

我已经用 Ubuntu 服务器测试了代码,它运行良好,但是当我使用不同的服务器(即 Windows 服务器和电信机器的接口(测试代码时,标准输出没有被读取, 打印(">远程服务器上成功执行的命令">(,但打印以下内容("读取行"(没有打印 所以我得出结论,代码挂在stdout=stdout.readlines()代码复制在下面,你能帮我弄清楚这次失败背后的原因是什么吗?

我还想补充一点,如果我使用 PuTTY 在该服务器上执行命令,我会得到正确的输出。

import paramiko
import os
user_name = "****"
passwd = "******"
ip = "*.*.*.*"
print ("Please wait creating ssh client ...")
ssh_client = paramiko.SSHClient()     #Create sshclient instance
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print ("Please wait, connecting to remote server")
ssh_client.connect(hostname=ip,username=user_name,password=passwd)
cmd="mml n command2"
print ("Please wait, executing command on remote server")
stdin,stdout,stderr=ssh_client.exec_command(cmd)
print ("Successfully executed command on remote server")
stdout=stdout.readlines()
print ("lines are read")
stdout="".join(stdout)
ssh_client.close()
print ("Connection closed")
print (stdout)
os.system("pause")

您正在执行的命令是交互式的。启动时,它会等待子命令。当您执行它并等待命令完成时(通过调用readlines(。永远不会发生的事情。

您必须将子命令提供给您的命令才能让它执行某些操作。
请参阅使用 Python Paramiko 通过 SSH 将输入/变量传递给命令/脚本。

您还必须使命令退出(通过发送类似exit/quit/bye之类的子命令(。

最新更新