• paramiko模块(基于SSH用于连接远程服务器)


    paramiko模块,基于SSH用于连接远程服务器并执行相关操作

    class SSHConnection(object):
        def __init__(self, host_dict):
            self.host = host_dict['host']
            self.port = host_dict['port']
            self.username = host_dict['username']
            self.pwd = host_dict['pwd']
            self.__k = None
     
        def connect(self):
            transport = paramiko.Transport((self.host,self.port))
            transport.connect(username=self.username,password=self.pwd)
            self.__transport = transport
     
        def close(self):
            self.__transport.close()
     
        def run_cmd(self, command):
            """
             执行shell命令,返回字典
             return {'color': 'red','res':error}或
             return {'color': 'green', 'res':res}
            :param command:
            :return:
            """
            ssh = paramiko.SSHClient()
            ssh._transport = self.__transport
            # 执行命令
            stdin, stdout, stderr = ssh.exec_command(command)
            # 获取命令结果
            res = unicode_utils.to_str(stdout.read())
            # 获取错误信息
            error = unicode_utils.to_str(stderr.read())
            # 如果有错误信息,返回error
            # 否则返回res
            if error.strip():
                return {'color':'red','res':error}
            else:
                return {'color': 'green', 'res':res}
     
        def upload(self,local_path, target_path):
            # 连接,上传
            sftp = paramiko.SFTPClient.from_transport(self.__transport)
            # 将location.py 上传至服务器 /tmp/test.py
            sftp.put(local_path, target_path, confirm=True)
            # print(os.stat(local_path).st_mode)
            # 增加权限
            # sftp.chmod(target_path, os.stat(local_path).st_mode)
            sftp.chmod(target_path, 0o755)  # 注意这里的权限是八进制的,八进制需要使用0o作为前缀
     
        def download(self,target_path, local_path):
            # 连接,下载
            sftp = paramiko.SFTPClient.from_transport(self.__transport)
            # 将location.py 下载至服务器 /tmp/test.py
            sftp.get(target_path, local_path)
     
        # 销毁
        def __del__(self):
            self.close()
     
      
    #unicode_utils.py
    def to_str(bytes_or_str):
        """
        把byte类型转换为str
        :param bytes_or_str:
        :return:
        """
        if isinstance(bytes_or_str, bytes):
            value = bytes_or_str.decode('utf-8')
        else:
            value = bytes_or_str
        return value
  • 相关阅读:
    Java开发必会的Linux命令
    为什么跳槽加薪会比内部调薪要高?
    程序员跳槽的最佳时机选择
    推荐!国外程序员整理的Java资源大全
    JavaScript最全编码规范
    window.open子窗口获取父窗口的值
    js获取iframe中的元素
    js数组合并为一个字符串
    js中for循环(原生js)
    js字符串截取为数组
  • 原文地址:https://www.cnblogs.com/snailgirl/p/11805504.html
Copyright © 2020-2023  润新知