使用带有 Pywinauto python 脚本的 Putty 进行多服务器登录

Multiple server login using Putty with Pywinauto python script

如何使用pywinauto应用程序登录到多个服务器?我正在使用下面的程序来访问 putty 和 运行 命令,当我定义如下时,这适用于单个服务器 app = Application().Start(cmd_line='C:\Program Files\PuTTY\putty.exe -ssh user@10.55.167.4') 但是,当我通过 for 循环为另一台服务器执行相同的任务时,它不起作用。

from pywinauto.application import Application
import time

server = [ "10.55.167.4", "10.56.127.23" ]
for inser in server:
    print(inser)
    app = Application ().Start (cmd_line = 'C:\Program Files\PuTTY\putty.exe -ssh user@inser')
    putty = app.PuTTY
    putty.Wait ('ready')
    time.sleep (1)
    putty.TypeKeys ("aq@wer")
    putty.TypeKeys ("{ENTER}")
    putty.TypeKeys ("ls")
    putty.TypeKeys ("{ENTER}")

pywinauto 是一个 Python 模块,用于自动化图形用户界面 (GUI) 操作,例如模拟鼠标点击以及人类过去在 GUI 上与计算机交互时所做的一切。 SSH 是一种主要为命令行设计的远程访问协议,在 Python 中具有出色的编程支持。 Putty 是一个用于管理 SSH 和 Telnet 连接的小型 GUI 工具。尽管基于快速检查,我认为可以通过 pywinauto 读取控制台输出(您的意思是 cmd.com?),但我认为您的方法不必要地复杂:您不需要使用一个 GUI 工具,专为人机交互而设计,用于访问具有出色命令行和程序库支持的协议。我建议您使用 paramiko,它提供了一个非常简单方便的 SSH 接口:

import paramiko

def ssh_connect(server, **kwargs):

    client = paramiko.client.SSHClient()
    client.load_system_host_keys()
    # note: here you can give other paremeters
    # like user, port, password, key file, etc.
    # also you can wrap the call below into
    # try/except, you can expect many kinds of
    # errors here, if the address is unreachable,
    # times out, authentication fails, etc.
    client.connect(server, **kwargs)
    return client

servers = ['10.55.167.4', '10.56.127.23']

# connect to all servers
clients = dict((server, ssh_connect(server)) for server in servers)

# execute commands on the servers by the clients, 2 examples:

stdin, stdout, stderr = clients['10.55.167.4'].exec_command('pwd')
print(stdout.read())
# b'/home/denes\n'

stdin, stdout, stderr = clients['10.56.127.23'].exec_command('rm foobar')
print(stderr.read())
# b"rm: cannot remove 'foobar': No such file or directory\n"

# once you finished close the connections
_ = [cl.close() for cl in clients.values()]