通过PuTTY进行SSH的Python脚本 [英] Python script for SSH through PuTTY

查看:561
本文介绍了通过PuTTY进行SSH的Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够在命令行中给出以下命令

I am able to give the following command in the command-line

C:\>cd "C:\Program Files\ExtraPuTTY\Bin"

C:\Program Files\ExtraPuTTY\Bin>putty.exe -ssh root@172.20.0.102 22

这可以帮助我通过PuTTY打开SSH会话.

This helps me open the SSH session through PuTTY.

我无法在Python脚本中复制它们.

Whereas I am not able to reproduce them in the Python script.

cwd="C://Program Files//ExtraPuTTY//Bin"
COMMAND="ls"
ssh = Popen(['putty.exe -ssh','%s'%HOST, COMMAND,cwd],shell=True,stdout=f,stderr=f)

我看到的错误是

"putty.exe -ssh"'无法识别为内部或外部命令,可运行程序或批处理文件

"putty.exe -ssh"' is not recognized as an internal or external command,operable program or batch file

推荐答案

In the putty download page, download and install plink, and make sure its in the windows path ($PATH variable)

然后,此python代码段应该可以工作:

Then, this python snippet should work:

import subprocess
cmd='plink -ssh {}@{} -pw {}'.format(user,server,password)
sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
sp.stdin.write(stdin)
sp.stdin.close()
stdout= sp.stdout.read()
stderr=sp.stderr.read()
sp.wait()

stdin是用户在终端中键入的命令,stdoutstderr是服务器输出.

stdin is the commands typed by the user in the terminal, stdout and stderr are the server output.

user="root"server="172.20.0.102 22"以及也许password的ssh连接中填写您的凭据

Fill in your credentials in the user="root", server="172.20.0.102 22" and maybe password for the ssh connection

这篇关于通过PuTTY进行SSH的Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆