使用 Plink (PuTTy) 通过 Python 进行 SSH [英] Using Plink (PuTTy) to SSH through Python

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

问题描述

我正在尝试编写一个 python 脚本,该脚本将通过 SSH 连接到服务器并执行命令.我在 Windows 上使用 Python 2.6,并安装了 plink 和 paegent(用于 ssh 密钥)并将它们全部添加到我的路径中.

I am trying to write a python script that will SSH to a server and execute a command. I am using Python 2.6 on Windows, and have installed plink and paegent (for ssh keys) and added them all to my path.

如果我转到命令提示符并键入:

If I go to the command prompt and type:

plink username@host -i key.ppk
open vnc://www.example.com/

我看到了所需的行为 - 在我的 Mac(服务器)上打开了一个 VNC 查看器.

I see the desired behavior-- a VNC viewer opens on my Mac (server).

但是,如果我尝试了两种方法通过 Python 以编程方式执行此操作,但都不起作用:

However, if I have tried two approaches to do this programmatically through Python and neither is working:

方法 1(操作系统):

Approach 1 (os):

import os
ff=os.popen("plink user@host -i key.ppk",'w')
print >>ff, r"open vnc://www.example.com"
ff.flush() 

方法 2(子流程):

import subprocess
ff=subprocess.Popen("plink user@host -i key.ppk",shell=False,stdin=subprocess.PIPE)
ff.stdin.write(r"open vnc://www.example.com")
ff.stdin.flush()

这两种方法都不会产生错误,但都不会打开 VNC 窗口.但是,我相信他们都成功连接到远程主机.

Neither approach produces an error, but neither opens the VNC window. However, I believe they both successfully connect to the remote host.

我做错了什么?

推荐答案

在第二种方法中,使用

In the second approach, use

ff.communicate("open vnc://www.example.com\n")

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

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