通过 PuTTY 进行 SSH 的 Python 脚本

标签 python ssh popen putty

我可以在命令行中给出以下命令

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

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

这可以帮助我通过 PuTTY 打开 SSH session 。

然而我无法在 Python 脚本中重现它们。

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"' is not recognized as an internal or external command,operable program or batch file

最佳答案

putty download page ,下载并安装plink,并确保其位于 windows path 中($PATH 变量)

然后,这个 python 代码片段应该可以工作:

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 是服务器输出。

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

关于通过 PuTTY 进行 SSH 的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32598361/

相关文章:

python - 我什么时候应该使用 subprocess.Popen 而不是 os.popen?

c - C 中的变量 popen 调用

python - 如何在 Python 中应用自适应过滤器

python - 在Python中使用正则表达式提取特定值

macos - 在Mac中使用终端进行文件传输

ubuntu - 锁定root,没有其​​他用户帐户登录ubuntu ssh

bash - 如何使用其他用户的显示器

c++ - 如何确保 popen()ed 进程在退出时运行析构函数?

python - 使用 pandas 对列中的重复值进行分类

python - 使用 python 调试器 (pdb) 时调试 cython 代码 (.pyx) - 最佳实践