使用 PuTTY 或 plink 通过 python 子进程连接到远程 linux 机器会抛出错误

Connecting to remote linux machine via python subprocess using PuTTY or plink throws error

我正在尝试从 windows 主机在远程 linux 机器上执行一些脚本。我希望使用 python subprocess +putty/plink 来实现这一点。 当我从 windows cmd 尝试 Putty 或 plink 命令时,它工作正常。但是,如果我使用 python 子进程尝试相同的命令,则会出现很多错误。

C:\Users\username>plink.exe username@machinename -pw password

工作正常。但是当我尝试从 python、

process = subprocess.Popen('plink.exe username@machinename -pw password'.split(),
                           env={'PATH':'C:\Program Files (x86)\PuTTY\'},
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

抛出以下错误。

Unable to open connection:

gethostbyname: unknown error'

process = subprocess.Popen("putty.exe -ssh -2 -l username -pw password -m C:\script.sh machinename",
                           env={'PATH':'C:\Program Files (x86)\PuTTY\'},
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT
                           ,shell=True);

Unable to open connection:

gethostbyname: unknown error'

我也试过 subprocess.check_ouput 但没有成功。

output = subprocess.check_output("putty.exe -ssh -2 -l username -pw password -m C:\script.sh machinename", stderr=subprocess.STDOUT,shell=True)

抛出以下错误

CalledProcessError: Command 'putty.exe -ssh -2 -l username -pw password -m C:\script.sh machinename' returned non-zero exit status 1

这可能是防火墙问题吗?

我强烈建议不要使用 PuTT 或一般的每个外部程序连接到 shh 然后与管道接口。

使用 python 库 paramiko 这可以做得更好。

例如:

# ... connect like one of the examples on github
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print '... ' + line.strip('\n')