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(">enn")
        ssh.stdin.write("_shelln")
        ssh.stdin.write("ls -ltrn")
        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连接。感谢

试着这样调用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字符串

最新更新