打开putty窗口并运行ssh命令-Python
我是python新手。我需要每天登录服务器(桌面->1.32->0.20->3.26)。为此,我需要打开putty并使用ssh连接登录。为了完成所有这些,我想使用python编写一个脚本 通过使用google,我认为subprocess.Popen可以做到这一点。但它的工作不好 第一条线索:打开putty窗口并运行ssh命令-Python,python,python-2.7,ssh,Python,Python 2.7,Ssh,我是python新手。我需要每天登录服务器(桌面->1.32->0.20->3.26)。为此,我需要打开putty并使用ssh连接登录。为了完成所有这些,我想使用python编写一个脚本 通过使用google,我认为subprocess.Popen可以做到这一点。但它的工作不好 第一条线索: import subprocess pid = subprocess.Popen("putty.exe user@xxx.xx.x.32 -pw password").pid 工作正常(打开窗口登录到.3
import subprocess
pid = subprocess.Popen("putty.exe user@xxx.xx.x.32 -pw password").pid
工作正常(打开窗口登录到.32)。但我不能提供意见。我开始知道,为了给同一个过程提供输入,我们需要使用管道
第二条线索:
from subprocess import Popen, PIPE, STDOUT
p = Popen("putty.exe user@xxx.xx.x.32 -pw password", stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'ssh xx.xx.x.20\n')[0]
print(grep_stdout.decode())
通过使用这个我不能登录到第一个服务器也。登录到所有服务器后,我需要终端处于活动状态。怎么做
编辑
我需要在一个新的腻子窗里做这个。登录后不要关闭窗口。我有一些手工工作要做。有一个针对python的SSHv2协议实现:。您可以使用pip轻松安装它:
pip install paramiko
然后,您可以创建ssh客户端,连接到主机并执行命令:
import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect('hostname', username='login', password='pwd')
stdin, stdout, stderr = ssh_client.exec_command('command')
使用paramiko库python 使用以下命令建立SSH连接-
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,username, password)
使用检查连接是否处于活动状态-
status = ssh.get_transport().is_active()
#returns True if connection is alive/active
exec_command()基本上是一个会话。使用exec_命令(command1;command2)在一个会话中执行多个命令
此外,您可以使用它在单个会话中执行多个命令
channel = ssh.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
Command 1
Command 2
''')
print stdout.read()
使用powershell调用putty以打开新窗口
from subprocess import Popen
Popen("powershell putty.exe user@host -pw mypassword")
我在windows上创建了一个bat文件,它引用了putty和putty会话的特定信息。此bat文件可以在windows上自行运行。为了从python调用,我使用了subprocess.run()--python 3.5+ 名为putty.bat的bat文件示例:
start c:\app\PuTTy\PuTTy.exe-load 192.168.1.230-node1-logs-l-pw
分解bat文件:
import subprocess
...
...
try:
process = subprocess.run(["putty.bat"], check=True, stdout=subprocess.PIPE, universal_newlines=True)
print(process.stdout)
except Exception as e:
print("subprocess call error in open putty command")
print(str(e))
我希望这对您有所帮助我需要打开一个新窗口(putty)并登录。登录到所有服务器(桌面->1.32->0.20->3.26)后,不要关闭putty窗口(我有一些手动工作要检查)。