Multi-threaded batch automation operation and maintenance of linux

Automation multi-host, saving time, effort

Ideas:

1. system host list

2. Batch Task List

3. Multi-threaded execution

Premise: a unified system administrator password

import paramiko
import threading

def hostnamelist():
    """
     :return:  hostname list
    """
    try:
        hosts = open("system_nonp.lst", "r", encoding='utf-8')  #reading the hostname list
        hostnames = hosts.readlines()
        return hostnames
    except FileNotFoundError:
        print('cannot open file!')
    except LookupError:
        print('assing wrong code!')
    except UnicodeDecodeError:
        print('reading file with wrong code!')
    finally:
        if hosts:
            hosts.close()

def ssh2(ip, username, passwd, cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, passwd, timeout=100)
        print("-------------------%s------------------------------" % (ip))
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
            #stdin.write("Y")   #input  ‘Y’
            out = stdout.readlines()
            # scren output
            for o in out:
                print(o)
        print('%s\tOK\n' % (ip))
        print("-------------------%s------------------------------\n\n" % (ip))
        ssh.close()
    except:
        print('%s\tError\n' % (ip))

if __name__ == '__main__':
    cmd  = ['date','ps -ef|grep -i splunk','which python','ifconfig']    
    username = "XXXXX"  # 用户名
    passwd = input("Input user %s\'s password:" %(username)) # input user password
threads = [] # 多线程 print("Begin......") for saphost in hostnamelist(): a = threading.Thread(target=ssh2, args=(saphost, username, passwd, cmd)) a.start() a.join() print("End........")

 

Guess you like

Origin www.cnblogs.com/tingxin/p/11949317.html