Python模块学习 - Paramiko


转载自一只小小寄居蟹的博客

https://www.cnblogs.com/xiao-apple36/p/9144092.html

阅读目录

  1. 简介
  2. Paramiko介绍
  3. Paramiko的基本使用
    • SSHClient常用的方法介绍
    • SSHClient常用的方法举例
    • SFTPClient常用方法介绍
    • SFTPClient常用方法举例
  4. Paramiko的综合使用例子
    • 参考资料

回到顶部回到顶部回到顶部回到顶部

Paramiko的综合使用例子

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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

参考资料

武沛齐:http://www.cnblogs.com/wupeiqi/p/5699254.html

Alex堡垒机:http://www.cnblogs.com/alex3714/articles/5286889.html 

http://www.cnblogs.com/dachenzi/articles/7954443.html