# -*- coding: utf-8 -*- """ ssh 远程 控制类, 和SCP 文件上传下载 """ import paramiko """ from libs_opsp.ssh_class import * ssh = ShhClass('192.1.1.1', 'root', '1111', sshtype=3) print ssh.Errorinfo #print ssh.getexe('lss /', datatype=2) a = {"Sfile": "/root/Twisted-13.2.0.tar.bz2", "Dfile": "/root/aa", "Type": 1} c = {"Sfile": "/root/aa", "Dfile": "/root/dddll.tar.bz2", "Type": 2} print ssh.batch(1,['ls /etc/', 'pwd']) print ssh.batch(2,[a, c]) """ class ShhClass: def __init__(self,host,user,pwd,port=22,sshtype=1): """ sshtype 链接类型 1 initexe, 2 initscp, 3 initexe and initscp""" self.host = host self.user = user self.pwd = pwd self.port = port self.Error = True self.Errorinfo = None #初始化 链接 if sshtype == 1: self.initexe() elif sshtype == 2: self.initscp() elif sshtype == 3: self.initexe() self.initscp() print self.client.set_log_channel('aa') def initexe(self): # 远程 命令 执行 链接初始化 try: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.load_system_host_keys() self.client.connect(self.host,port=self.port,username=self.user,password=self.pwd) except paramiko.AuthenticationException as a: self.Error = False self.Errorinfo = a except: self.Error = False self.Errorinfo = 'No route to host or port is no.' def initscp(self): #scp 文件传输 链接初始化 try: self.scpclient = paramiko.Transport((self.host, self.port)) self.scpclient.connect(username=self.user, password=self.pwd) self.sftp = paramiko.SFTPClient.from_transport(self.scpclient) except paramiko.AuthenticationException as a: self.Error = False self.Errorinfo = a except: self.Error = False self.Errorinfo = 'No route to host or port is no.' def getexe(self, command, datatype=1): #执行单条 命令 dataexe = {} dataexe['command'] = command if self.Error and type(command) == str: stdin, stdout, stderr = self.client.exec_command(command) isa = stderr.read() if isa: dataexe['stats'] = False dataexe['info'] = isa else: if datatype == 1: data = stdout.read() elif datatype == 2: #按照 行 切分的列表 data = stdout.readlines() dataexe['stats'] = True dataexe['info'] = data return dataexe def getscp(self, file_dict): """ scp 传输 单条 文件 #file_dict_list = [{"Sfile": sfile, "Dfile": Dfile, "Type": 1}] Type 1(上传) 2(下载) """ scpdata = {} try: if file_dict['Type'] == 1: a = self.sftp.put(file_dict['Sfile'], file_dict['Dfile']) elif file_dict['Type'] == 2: a = self.sftp.get(file_dict['Sfile'] , file_dict['Dfile']) scpdata['stats'] = True scpdata['info'] = a except OSError as e: scpdata['stats'] = False scpdata['info'] = str(e) except IOError as e: scpdata['stats'] = False if str(e) == "Failure": scpdata['info'] = "Failure , Dfile path error" else: scpdata['info'] = str(e) return scpdata def batch(self, sshtype, batcharge): """ 批量执行 或者 传输文件 type = 1 执行 命令 type = 2 scp传输文件 """ returnlist = [] if self.Error and type(batcharge) == list: if sshtype == 1: for i in batcharge: returnlist.append(self.getexe(i)) elif sshtype == 2: for i in batcharge: returnlist.append(self.getscp(i)) return returnlist