#coding=utf8 import paramiko import sys import time import os import re class DoError(Exception): pass class DoSsh(object): def __init__(self,host=None, username=None, password=None, port='22',private_key=None,is_windows=False,debug=False): self.ip = host self.user = username.encode('utf8') self.passwd = password.encode('utf8') self.port = int(port) self.slip = " ".encode('utf8') if is_windows else " ".encode('utf8') self.private_key=private_key self.client=None def login(self): try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(self.ip, self.port, username=self.user, password=self.passwd, timeout=4) ssh_shell = client.invoke_shell() ssh_shell.keep_this = client self.client=ssh_shell ssh_shell.recv(1024)#获取连接信息 test_connect = ssh_shell.recv(1024)#获取输入提示符 if test_connect: return True,test_connect except Exception as e: return False, 'connect fail:{}'.format(e) def run(self,cmd): try: self.client.send(cmd+' ') while not self.client.recv_ready(): time.sleep(2) result='' res= self.client.recv(1024) # while res.strip(): # print res # result = result + res # if re.search(r'% Unrecognized|% Invalid|% Unknown| %Incomplete', res): # return False # res=self.client.recv(1024) return result except Exception as e: print e sys.exit(1) def close(self): try: print self.client.recv(1024) self.client.close() print "Close success" except Exception as err: print "Close Error: {}".format(err) sys.exit(1) is_windows = True if os.name == 'nt' else False now = time.strftime('%Y%m%d_%H%M%S') def get_file(host, username, password,ftp_host,ftp_user,ftp_passwd,filename,directory, **kwargs): """支持cisco、 h3c 、huawei交换机的升级""" print host try: terminal = DoSsh(host=host, username=username, password=password, **kwargs) terminal.login() slip = " ".encode('utf8') if is_windows else " ".encode('utf8') out = terminal.run('ftp {}'.format(ftp_host)) outs=out.split(slip) success=False for line in outs: if 'Connected to' in line: success=True break if not success: raise DoError(out) terminal.run('{}'.format(ftp_user)) out = terminal.run('{}'.format(ftp_passwd)) if 'Login successful' not in out: raise DoError('ftp user or password is error') if directory: out=terminal.run('cd {}'.format(directory)) if 'Failed to change directory' in out: raise DoError(out) files = terminal.run('ls').split(slip) file_exists=False for file in files: if file.strip()==filename: file_exists=True if not file_exists: raise DoError( 'file not exists') out = terminal.run('get {}'.format(filename)) if 'Overwrite it? [Y/N]:' in out: out=terminal.run('Y') print out terminal.run('bye') outs = terminal.run('dir /all').split(slip) for file in outs: if file.strip()==filename: #terminal.close() return True #terminal.close() return False except Exception as e: print e sys.exit(1) if __name__ == '__main__': for ip in ips.split(','): if ip.strip(): _tmp = get_file(ip.strip(), username, password, ftp_host,ftp_user,ftp_passwd, filename,directory,is_windows=is_windows, debug=False) print '{}已升级'.format(ip.strip())