Python不能ssh到服务器并使用子进程打印预期的输出

时间:2014-09-08 07:23:10

标签: python ssh

我从文本文件中读取了一台机器的IP地址,并希望ssh到该服务器并运行一些shell命令来获得所需的输出。

IP_address.txt文字中,我提供了182.x.x.x

的IP地址

这是我的代码段:

fo = open("ip_address.txt", "r")
    data = fo.readlines()
    for line in data:
        line = line.strip("\n")
        ssh = subprocess.Popen(["ssh", "%s" % line],shell = True,stdin=subprocess.PIPE,stdout= subprocess.PIPE,stderr=subprocess.PIPE)
        ssh.stdin.write(">en\n")
        ssh.stdin.write("_shell\n")
        ssh.stdin.write("ls -ltr\n")
        result = ssh.stdout.readlines()
        if result == []:
            error = ssh.stderr.readlines()
            print >>sys.stderr, "ERROR: %s" % error
        else:
            print result

当我打印结果时,它是[],意思是空的。我尝试运行脚本的服务器与我尝试SSH连接的服务器之间没有无密码连接。

当我从这个服务器执行手动步骤时,我只是尝试执行类似的命令: -

ssh 182.x.x.x
en
_shell
ls -ltr

但这会引发一个错误: -

    ERROR: ['usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n', '           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n', '           [-i identity_file] [-L [bind_address:]port:host:hostport]\n', '           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n', '           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n', '           [-W host:port] [-w local_tun[:remote_tun]]\n', '           [user@]hostname [command]\n']

我无法解决此错误,因为我无法弄清楚此代码有什么问题。有帮助吗? P.S - 我想只使用子进程而不是paramiko或任何其他类库进行ssh连接。 感谢

1 个答案:

答案 0 :(得分:0)

尝试像这样调用你的ssh:

sh = subprocess.Popen("ssh %s" % line,shell = True,stdin=subprocess.PIPE,stdout= subprocess.PIPE,stderr=subprocess.PIPE)

当使用shell = True调用时,列表中的所有参数都会从第一个参数传递给shell而不是传递给应用程序,因此在这种情况下,您只想将ssh some.ip.add.ress传递给shell而不是传递ssh(这会立即执行),然后在

之后传递ip string