首页 > 解决方案 > Paramiko parallel execution to the remote unix hosts

问题描述

I have a below script which i'm using to execute commands on remote hosts as a cetralized user, but this script is reads the host file and execute the command one by one however it also remains on the session until its not unlinked from the shell, Hence i want to have a parallel execution saying that when running the script it should be able to fork multiple ssh connection and login to the host and exit immeadiaely after command execution.

Please let me know if you guys have any trick or expert inputs. Though i'm using paramiko as these hosta rae legarcy UNIX hosts where i'm unable to use ansible or like utilities due to some restrictions.

import paramiko
with open('/data/CR9432/SunOS.txt', 'r') as f:
    for host in f:
        remote_host = host.rstrip()
        remote_pass = "pass123"
        smart_user = "mtrooper"
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(remote_host, username=smart_user, password=remote_pass)
        transport = ssh.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        #for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
        ############################################
        #session.exec_command("shutdown -y -i5 -g0")
        ############################################
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        #you have to check if you really need to send password here
        stdin.write(remote_pass +'\n')
        stdin.flush()
        print"\n"
        print "------------------------------------------------------------------------------"
        print "Command Execution Output On  Hostname: "
        print "------------------------------------------------------------------------------"
        for line in stdout.read().splitlines():
            print 'host: %s: %s' % (remote_host, line)

标签: python

解决方案


推荐阅读