python使用paramiko库文件实现ssh上传,下载文件以及执行ssh命令的函数

python的常用函数类,构建一个SSHConnection类,提供上传,下载sftp文件,和执行ssh命令,

分别调用sftp_command,sftp_upload_packet,sftp_download_packet即可;

import paramiko

class SSHConnection(object):                                                
    def __init__(self, host, port, username, password):                     
        self._host = host                                                   
        self._port = port                                                   
        self._username = username                                           
        self._password = password                                           
        self._transport = None                                              
        self._sftp = None                                                   
        self._client = None                                                 
        self._connect()  # 建立连接                                             
                                                                            
    def _connect(self):                                                     
        transport = paramiko.Transport((self._host, self._port))            
        transport.connect(username=self._username, password=self._password) 
        self._transport = transport                                         
                                                                            
    #下载                                                                     
    def download(self, remotepath, localpath):                              
        if self._sftp is None:                                              
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.get(remotepath, localpath)                               
                                                                            
    #上传                                                                     
    def put(self, localpath, remotepath):                                   
        if self._sftp is None:                                              
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.put(localpath, remotepath)                               
                                                                            
    #执行命令                                                                   
    def exec_command(self, command):                                        
        try:                                                                
            if self._client is None:                                        
                self._client = paramiko.SSHClient()                         
                self._client._transport = self._transport                   
            stdin, stdout, stderr = self._client.exec_command(command)      
            data_out = stdout.read()                                        
            #if len(data_out) > 0:                                          
                ##print data_out.strip()   #打印正确结果                          
            data_err = stderr.read()                                        
            #if len(data_err) > 0:                                          
                ##print data_err.strip()    #输出错误结果                         
            #print 'data_type:',type(data_out),type(data_err)               
        except:                                                             
            pdb.set_trace()                                                 
        return data_out,data_err                                            
                                                                            
    def exec_command_timeout(self, command, timeout=None):                  
        try:                                                                
            if self._client is None:                                        
                self._client = paramiko.SSHClient()                         
                self._client._transport = self._transport                   
            stdin, stdout, stderr = self._client.exec_command(command)      
            #pdb.set_trace()                                                
            # 设置文件描述符为非阻塞模式                                                 
            stdout.channel.setblocking(0)                                   
            stderr.channel.setblocking(0)                                   
                                                                            
            data_out = b''                                                  
            data_err = b''                                                  
            end_time = time.time() + timeout if timeout is not None else Non
                                                                            
            while True:                                                     
                # 使用select函数进行监听可读文件描述符                                     
                ready, _, _ = select.select([stdout.channel], [stderr.channe
                                                                            
                if stdout.channel in ready:                                 
                    partial_out = stdout.channel.recv(1024)  # 读取部分输出数据     
                    data_out += partial_out                                 
                    if not partial_out:  # 如果输出数据为空,则表示已读取完毕                
                        break                                               
                                                                            
                if stderr.channel in ready:                                 
                    partial_err = stderr.channel.recv(1024)  # 读取部分错误数据     
                    data_err += partial_err                                 
                    if not partial_err:  # 如果错误数据为空,则表示已读取完毕                
                        break                                               
                                                                            
                if end_time is not None and time.time() > end_time:         
                    break                                                   
                                                                            
        except Exception as e:                                              
            print (command,'exec_command_timeout_error:',str(e))            
            i=0                                                             
            while i<timeout:                                                
                time.sleep(1)                                               
                i=i+1                                                       
            data_out=b'';data_err=b'';                                      
        return data_out, data_err                                           
                                                                            
                                                                            
    def exec_command_timeout1(self, command,timeout):                       
        error_count=30;i=0;                                                 
        while 1:                                                            
            try:                                                            
                #pdb.set_trace()                                            
                if self._client is None:                                    
                    self._client = paramiko.SSHClient()                     
                    self._client._transport = self._transport               
                stdin, stdout, stderr = self._client.exec_command(command)  
                data_out = read_timeout(stdout,timeout)                     
                data_err = read_timeout(stderr,timeout)                     
                return data_out,data_err                                    
            except:                                                         
                #pdb.set_trace()                                            
                time.sleep(5)                                               
                i=i+1                                                       
                if i>error_count:                                           
                    return False,False                                      
                continue                                                    
                                                                            
                                                                            
    def close(self):                                                        
        if self._transport:                                                 
            self._transport.close()                                         
        if self._client:                                                    
            self._client.close()                                            
    def gatherAttrs(self):                                                  
        return ",".join("{}={}".format(k, getattr(self, k)) for k in list(se
    def __str__(self):                                                      
        return "[{}:{}]".format(self.__class__.__name__, self.gatherAttrs())
    def data(self):                                                         
        return "[{}:{}]".format(self.__class__.__name__, self.gatherAttrs())

def sftp_download_packet(server_ip,username,password,port,remote_path,local_path):
    conn = SSHConnection(server_ip, port, username, password)
    #print 'download start'+':'+local_path+':'+remote_path
    conn.download(remote_path, local_path)
    #print 'download end'+':'+local_path+':'+remote_path
    conn.close()

def sftp_upload_packet(server_ip,username,password,port,remote_path,local_path):
    conn = SSHConnection(server_ip, port, username, password)
    #print 'put begin'+':'+local_path+':'+remote_path
    conn.put(local_path, remote_path)
    #print 'put end'+':'+local_path+':'+remote_path
    conn.close()

def sftp_command(server_ip,username,password,port,command):
    conn = SSHConnection(server_ip, port, username, password)
    #print 'ssh cmd begin'+':'+command
    data_out,data_err=conn.exec_command(command)
    #print 'ssh cmd end'+':'+command
    conn.close()
    return data_out,data_err

def sftp_command_timeout(server_ip,username,password,port,command,timeout=4000):
    conn = SSHConnection(server_ip, port, username, password)
    #print 'ssh cmd begin'+':'+command
    data_out,data_err=conn.exec_command_timeout(command,timeout)
    #print 'ssh cmd end'+':'+command
    conn.close()
    return data_out,data_err  

  • 25
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值