自动化操作多主机,省时,省力
思路:
1. 系统主机清单
2. 批处理任务清单
3. 多线程并发执行
前提:有统一的系统管理员密码
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........")