使用子进程连接到远程计算机

时间:2016-02-10 20:35:25

标签: python ssh

我想连接到远程计算机,并且还希望在那里执行某些命令。

详细信息:

远程计算机:它是一台Linux计算机。

本地机:它是Windows 7机器。

我的Python代码在Windows机器上。

import subprocess
import sys

HOST="eseki.rnd.sozi.se"
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="uname -a"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()

if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result

但是,当我执行此代码时,收到以下错误消息:

Traceback (most recent call last):
  File "C:\Users\ABC\workspace\HelloWorldPython\src\SSHTestModule.py", line 16, in <module>
    stderr=subprocess.PIPE)
  File "C:\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

如何使用Python连接到远程计算机?

1 个答案:

答案 0 :(得分:0)

您要么没有在本地计算机上安装ssh客户端,要么它不在PATH变量中。

无论哪种方式,我建议您查看专为ssh设计的库,而不是使用子进程(例如http://www.paramiko.org/