zoukankan      html  css  js  c++  java
  • python paramiko操作linux

    paramiko简述

    paramiko是基于Python实现的SSH2远程安全连接,支持认证及密钥方式。可以实现远程命令执行、文件传输、中间SSH代理等功能,相对于Pexpect,封装的层次更高,更贴近SSH协议的功能

    目前需要实现如下需求

    1、python远程连接linux主机执行命令获取返回结果

    2、上传文件至linux服务器

    3、从linux服务器下载文件

    实现代码如下:

    # -*- coding: utf-8 -*-
    # @Author   : cli
    import paramiko
    from common import log
    
    '''开启paramiko日志'''
    paramiko.util.log_to_file('../log/paramiko.log')
    class Linux(object):
        # 通过IP, 用户名,密码,超时时间初始化一个远程Linux主机
        def __init__(self, ip, port,username, password, timeout=30):
            self.ip = ip
            self.port = port
            self.username = username
            self.password = password
            self.timeout = timeout
            # 链接失败的重试次数
            self.try_times = 3
            # 记录日志
            self.log = log.MyLog()
    
        # 调用该方法连接远程主机
        def connect(self):
            while True:
                # 连接过程中可能会抛出异常,比如网络不通、链接超时
                try:
                    self.ssh=paramiko.SSHClient()
                    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                    self.ssh.connect(hostname=self.ip,port=self.port,username=self.username,password=self.password,timeout=self.timeout)
                    # 如果没有抛出异常说明连接成功,直接返回
                    print('连接%s成功' % self.ip)
                    self.log.info('连接%s成功' % self.ip)
                    return
                # 这里不对可能的异常如socket.error, socket.timeout细化,直接一网打尽
                except Exception as e1:
                    if self.try_times != 0:
                        print('连接%s失败,进行重试' % self.ip)
                        self.log.error('连接%s失败,进行重试' % self.ip)
                        self.try_times -= 1
                    else:
                        print('重试3次失败,结束程序')
                        self.log.error('重试3次失败,结束程序')
                        exit(1)
    
        # 发送要执行的命令
        def command(self, cmd):
            self.connect()
            stdin,stdout,stderr=self.ssh.exec_command(cmd)
            result=stdout.read().decode('utf-8')
            error = stdout.read().decode('utf-8')
            if not error:
                print(result)
                self.log.info(result)
                return result
            else:
                print(error)
                self.log.error(error)
                return error
    
        '''
        发送文件
        @:param upload_files上传文件路径 例如:/tmp/test.py
        @:param upload_path 上传到目标路径 例如:/tmp/test_new.py
        '''
        def upload_file(self, upload_files, upload_path):
            try:
                tran = paramiko.Transport(self.ip, self.port)
                tran.connect(username=self.username, password=self.password)
                sftp = paramiko.SFTPClient.from_transport(tran)
                result = sftp.put(upload_files, upload_path)
                return True if result else False
            except Exception as ex:
                print(ex)
                tran.close()
            finally:
                tran.close()
    
        '''
           下载文件
           @:param remote_path下载文件路径 例如:/tmp/test.py
           @:param local_path 文件本地保存路径 例如:/tmp/test_new.py
           '''
        def dowland_file(self,remote_path, local_path):
            try:
                tran = paramiko.Transport(self.ip, self.port)
                tran.connect(username=self.username, password=self.password)
                sftp = paramiko.SFTPClient.from_transport(tran)
                # 使用paramiko下载文件到本机
                result=sftp.get(remote_path, local_path)
                return True if result else False
            except Exception as ex:
                print(ex)
                tran.close()
            finally:
                tran.close()

    测试:

    正常连接

    a=Linux('192.168.101.9',22,'root','123',3)
    a.command('whoami')

     异常连接:

    a=Linux('192.168.101.9',23,'root','123',3)
    a.command('whoami')

     文件上传下载

    a=Linux('192.168.101.9',22,'root','123',3)
    a.upload_file(r'../log/paramiko.log','/root/paramiko_upload.log')
    a.dowland_file('/root/paramiko_upload.log',r'../log/paramiko_dowland.log')

    the end..



  • 相关阅读:
    总结oninput、onchange与onpropertychange事件的用法和区别,onchange
    即时反应的input和propertychange方法
    响应式网页
    angularJS问题集结
    网页边框样式与style样式部分总结
    软件工程问题及回答
    第13章到第17章问题
    《构建之法》第10、11、12章
    《构建之法》第8,9,10章
    [css]等高列的简单实现
  • 原文地址:https://www.cnblogs.com/mingfan/p/13682098.html
Copyright © 2011-2022 走看看