Python 如何解决-连接到192.168.X.X已关闭?

Python 如何解决-连接到192.168.X.X已关闭?,python,ssh,Python,Ssh,我的代码如下所示: def op(): cmd = "ssh -t user@ip top -bn 1 >data.txt" os.system(cmd) #does some other operations and then returns some variables, say a,b,c return (a,b,c) k=1 while k<5: print(op()) k+=1 我所有的变量也是空的。如何解决这个问题 我

我的代码如下所示:

def op():
    cmd = "ssh -t user@ip top -bn 1 >data.txt"
    os.system(cmd)
    #does some other operations and then returns some variables, say a,b,c
    return (a,b,c)


k=1
while k<5:
    print(op())
    k+=1
我所有的变量也是空的。如何解决这个问题


我假设这与“关闭”SSH连接有关,然后在每次迭代开始时重新启动它,但我不知道如何做到这一点。

这个答案可能不是解决问题的直接方法。但是,最好使用python ssh接口,而不是直接执行shell命令

Paramiko就是这样一个pythonsshv2实现

当前文件:

示例代码:

您无法从
os.system()
获取值。您必须使用模块
子流程
-ie
supprocess.run
,然后您可以从
stdout
获取文本。您可能需要查看以下内容:
Connection to 192.168.xxx.xxx closed.

    import paramiko 
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect('localhost', username=username, password=password)
    except paramiko.SSHException:
        print "Connection Failed"
        quit()

stdin,stdout,stderr = ssh.exec_command("top -bn")

for line in stdout.readlines():
        print line.strip()
ssh.close()