Search code examples
pythonpython-3.xputtypywinauto

Multiple server login using Putty with Pywinauto python script


How to logged in to multiple server using pywinauto application? I am using below program for access putty and run the command, This is work for single server when i have defined like app = Application ().Start (cmd_line = 'C:\Program Files\PuTTY\putty.exe -ssh user@10.55.167.4') But while i am passing with for loop to do the same task for another server it does not work.

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}")

Solution

  • pywinauto is a Python module to automatize graphical user interface (GUI) operations for example to simulate mouse clicking and everything else humans used to do on GUIs to interact with the computer. SSH is a remote access protocol designed primarily for command line and having excellent programmatic support in Python. Putty is a little GUI tool to manage SSH and Telnet connections. Although, based on quick check, I think it is possible to read the console output (you mean in cmd.com?) by pywinauto, I think your approach is unnecessarily complicated: you don't need to use a GUI tool designed for human interaction to access a protocol with excellent command line and programmatic library support. I suggest you to use paramiko which gives a very simple and convenient interface to 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()]