代码之家  ›  专栏  ›  技术社区  ›  krock1516

Paramiko到远程unix主机的并行执行

  •  0
  • krock1516  · 技术社区  · 7 年前

    我有一个下面的脚本,我用它作为一个合法用户在远程主机上执行命令,但是这个脚本是读取主机文件并逐个执行命令,但是它也会保留在会话中,直到它没有与shell解除链接为止,因此,我希望有一个并行执行,说当运行脚本时,它应该能够在命令执行后拨出多个SSH连接并登录到主机并退出IMAMEDAIELY。

    请让我知道,如果你们有任何技巧或专家的意见。尽管我使用paramiko作为这些hosta rae legarcy UNIX主机,但由于一些限制,我无法使用ansible或类似的实用程序。

    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)
    
    0 回复  |  直到 7 年前