python 执行上传,下载,批量执行命令,退出
#!/usr/bin/env python #_*_encoding:utf-8_*_ #上传文件取源文件的MD5值, 查询目标端的MD5 import os,sys,time,hashlib,datetime,paramiko,threading source = sys.argv[1] #源文件 target = sys.argv[2] #目标文件 ttt = 'ls',target ip = "ip_addr.txt" comm = ["hostname","ifconfig eth0 | awk 'NR==2{print $2}' |awk -F':' '{print $2}'"] #comm.append('ls '+target) #目标端文件名 comm.append('md5sum '+target) #目标端文件,MD5 def Read_ip(ip_addr): with open(ip_addr,'rb')as f: f = f.readlines() return f def Put_File(): #上传文件及 取源文件的MD5值 IP = Read_ip(ip) private_key_path = '/root/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(private_key_path) md5file=open(source,'rb') md5=hashlib.md5(md5file.read()).hexdigest() md5file.close() for line in range(len(IP)): I_P = IP[line].strip() t = paramiko.Transport((I_P,22)) t.connect(username='root',pkey = key) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(source, target) t.close() return md5 def Achieve_target_MD5():#获取目标端的MD5值 llist = [] IP = Read_ip(ip) private_key_path = '/root/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(private_key_path) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for line in range(len(IP)): IIP = IP[line].strip() for ii in range(len(comm)): C_Command = comm[ii].strip() ssh.connect(IIP, 22,username='root', pkey = key) stdin, stdout, stderr = ssh.exec_command(C_Command) content = stdout.read() ssh.close() llist.append(content) return llist if __name__ =='__main__': m_sum = Put_File() print m_sum tar_infor = Achieve_target_MD5() for i in range(2,len(tar_infor),3): print tar_infor[i]