Python 连接到putty并键入少量命令
我想连接到putty,并想执行以下几步:Python 连接到putty并键入少量命令,python,putty,Python,Putty,我想连接到putty,并想执行以下几步: 登录到Putty 键入少量命令以关闭服务器 遍历到特定路径 从目录中删除该文件 再次启动服务器 我需要在windows中编写代码。但是我的服务器是linux。 我该怎么办? 提前感谢您可以使用类似以下代码: command=“plink.exe-ssh username@”+hostname+“-pw password-batch\”导出显示=“+hostname+”/unix:0.0”;“ 它将使用用户名和密码打开ssh到所需的主机名 关闭: comm
提前感谢您可以使用类似以下代码:
command=“plink.exe-ssh username@”+hostname+“-pw password-batch\”导出显示=“+hostname+”/unix:0.0”;“
它将使用用户名
和密码
打开ssh到所需的主机名
关闭:
command+=“sudo/sbin/halt\”
重新启动:
command+=“sudo/sbin/reboot\”
使用与上述相同的方法添加其他命令
使用以下命令运行该命令:
pid=subprocess.Popen(命令).pid
正如Tadeck所指出的,这只适用于试图连接到linux机器的windows机器。您需要的是,但对于初学者来说可能有点复杂
对于简单重复的任务,您可以使用我的脚本——它是为了学习一些Python而创建的。它基于其他人对Paramiko()友好的SSH Python接口
使用上述SSH模块连接到服务器并执行命令相当简单:
import ssh
server = ssh.Connection(host='host', username='user', private_key='key_path')
result = server.execute('your command')
基本上,您需要的不是PuTTy,而是Python的SSH模块。此模块应该可以在Windows和Linux上工作。使用我的脚本,您只需要处理要调用的命令,并根据需要调整代码
祝你好运。告诉我是否有用。你可以这样做:
# Use plink to open a connection to the remote shell
command = "plink.exe -ssh %s -batch" % credentials
sp = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Send commands to the shell as if they were read from a shell script
sp.stdin.write("command1\n")
sp.stdin.write("command2\n")
sp.stdin.close()
# read out the answers, if needed
ans = sp.stdout.read()
sp.wait()
对于凭据
,最好输入PuTTY连接配置文件的名称,并准备好用户名集和SSH密钥
from pywinauto.application import Application
import time
app = Application ().Start (cmd_line=u'putty -ssh user_name@10.70.15.175')
putty = app.PuTTY
putty.Wait ('ready')
time.sleep (1)
putty.TypeKeys ("password")
putty.TypeKeys ("{ENTER}")
time.sleep (1)
putty.TypeKeys ("ls")
putty.TypeKeys ("{ENTER}")
我使用的是python 2.7。代码在Windows上运行,并连接到远程Linux。它在我的环境中工作。当然,您的解决方案完全依赖于平台,并且只在连接到Linux/Unix系统的Windows上工作。确实如此,但这正是OP想要的,也是我最近做的。@Tadeck,谢谢,我应该已经完成了正如你所说,这是我的疏忽,为了正确起见,我将添加它。你能建议一种解决方法,让它等到像rsync这样的复杂过程结束,然后执行其他命令,提前谢谢。你能将模块上载到PyPi吗?到Paramiko的链接已失效。你能包含到“”的链接吗…其他人友好的SSH Python界面…”?您可以使用来执行这些步骤。我想您需要登录到SSH服务器,这样您就可以使用了。您不需要PuTTY!