Python无法通过subprocess远程连接服务器并打印预期输出

0 投票
1 回答
823 浏览
提问于 2025-04-20 09:41

我从一个文本文件里读取了一台机器的IP地址,想通过SSH连接到那台服务器,然后运行几个命令来获取想要的结果。

在文本文件 IP_address.txt 中,我提供的IP地址是 182.x.x.x

这是我的代码片段:

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']

我无法解决这个错误,因为我搞不清楚代码哪里出了问题。有没有人能帮帮我?
附注:我想通过子进程来建立SSH连接,而不是使用paramiko或其他类库。
谢谢!

1 个回答

0

试着这样调用你的ssh:

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

当你使用shell=True时,所有的参数都会被传递给命令行,而不是直接传给应用程序的第一个参数。所以在这种情况下,你其实是想把你的ssh和某个ip地址一起传给命令行,而不是先传ssh(这会立即执行),然后再传ip地址。

撰写回答