设为首页收藏本站
网站公告 | 这是第一条公告
     

 找回密码
 立即注册
缓存时间07 现在时间07 缓存数据 女人不要只算计自己喜欢的任何物品多少钱,要计算自己的青春还剩多少年;要懂得爱自己,舍得爱自己;不为别人,只为那个限量版的自己!

女人不要只算计自己喜欢的任何物品多少钱,要计算自己的青春还剩多少年;要懂得爱自己,舍得爱自己;不为别人,只为那个限量版的自己!

查看: 346|回复: 0

Python中paramiko模块的基础操作与排错问题

[复制链接]

  离线 

TA的专栏

  • 打卡等级:热心大叔
  • 打卡总天数:232
  • 打卡月天数:0
  • 打卡总奖励:3550
  • 最近打卡:2025-04-08 16:28:38
等级头衔

等級:晓枫资讯-上等兵

在线时间
0 小时

积分成就
威望
0
贡献
442
主题
411
精华
0
金钱
4884
积分
913
注册时间
2023-1-4
最后登录
2025-4-8

发表于 2023-2-10 22:45:39 | 显示全部楼层 |阅读模式
关于
  1. python的ssh库操作需要引入一个远程控制的模块——paramiko,可用于对远程服务器进行命令或文件操作。
复制代码
应用
  1. 登陆服务器,问题排查。可用于编写脚本,在服务器上做一些繁琐的重复操作。
复制代码
安装
  1. 打开cmd,输入命令[code]python -m pip install paramiko
复制代码
[/code]
示例


1.秘钥登陆
  1. 配置免密登录,linux上信任了windows的公钥,然后脚本在windows上跑,使用windows的私钥就可以直接不要密码登录linux
复制代码
  1. 注意
复制代码
:提供秘钥的
  1. paramiko.RSAKey.from_private_key_file('文件')
复制代码
,这里面的"文件"是你本机上的秘钥,不是指你被控机上的公钥哦!
  1. import paramiko

  2. key = paramiko.RSAKey.from_private_key_file("C:\\Users\\liyansheng\\.ssh\\id_rsa")
  3. ssh = paramiko.SSHClient()
  4. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  5. print("connecting")
  6. ssh.connect(hostname="192.168.220.128", username="root", pkey=key)
  7. print("connected")
  8. commands = "uname -a"
  9. stdin, stdout, stderr = ssh.exec_command(commands)
  10. stdin.close()
  11. res, err = stdout.read(), stderr.read()
  12. result = res if res else err
  13. print(result)
  14. ssh.close()

  15. if __name__ == '__main__':
  16.     print()
复制代码
2.单个命令执行
  1. 创建一个[code].py
复制代码
文件,引入
  1. paramiko
复制代码
模块[/code]
  1. import paramiko
复制代码
  1. <ol start="2"><li>建立[code]SSHClient
复制代码
对象
[/code]
  1. ssh = paramiko.SSHClient()
复制代码
  1. <ol start="3"><li>设置可信任,将主机加到[code]host_allow
复制代码
列表
[/code]
  1. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
复制代码
  1. <ol start="4"><li>创建连接</li></ol>
复制代码
  1. ssh.connect("150.158.16.123", 22, "wuyanping", "2022")
复制代码
  1. <ol start="5"><li>创建命令,发送并获取响应结果</li></ol>
复制代码
  1. stdin, stdout, stderr = ssh.exec_command("ls /home")
  2.     print(stdout.read().decode("utf-8"))
复制代码
  1. <ol start="6"><li>关闭连接</li></ol>
复制代码
  1. ssh.close()
复制代码
3.执行多个命令
  1. # 执行多条命令,注意传入的参数有个list
  2. def execMultiCmd(host, user, psw, cmds: list, port=22) -> (str, str):
  3.     with paramiko.SSHClient() as ssh_client:
  4.         ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  5.         ssh_client.connect(hostname=host, port=port, username=user, password=psw)
  6.         cmd = ";".join(cmds)
  7.         _, stdout, stderr = ssh_client.exec_command(cmd, get_pty=True)
  8.         result = stdout.read().decode('utf-8')
  9.         err = stderr.read().decode('utf-8')
  10.     return result, err


  11. if __name__ == '__main__':
  12.     cmdList = ["cd /home", "ls"]
  13.     print(execMultiCmd("192.168.220.128", "root", "root", cmdList))
复制代码
4.SFTPClient下载文件

方法封装:
  1. def down_file(host, user, psw, local_file, remote_file, port=22):
  2.     with paramiko.Transport((host, port)) as transport:
  3.         # 连接服务
  4.         transport.connect(username=user, password=psw)
  5.         # 获取SFTP示例
  6.         sftp = paramiko.SFTPClient.from_transport(transport)
  7.         # 下载
  8.         sftp.get(remote_file, local_file)
  9.         transport.close()
复制代码
问题:(错误)
  1. if __name__ == '__main__':
  2.     down_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download", "/home/test.txt")
复制代码
  1. Traceback (most recent call last):
  2.   File "D:\MyCode2\py-1\ssh\download.py", line 17, in <module>
  3.     down_file("192.168.220.128", "root", "root", "D:\\ssh_download", "/home/test.txt")
  4.   File "D:\MyCode2\py-1\ssh\download.py", line 11, in down_file
  5.     sftp.get(remote_file, local_file)
  6.   File "D:\MyCode2\py-1\venv\lib\site-packages\paramiko\sftp_client.py", line 810, in get
  7.     with open(localpath, "wb") as fl:
  8. PermissionError: [Errno 13] Permission denied: 'D:\\ssh_download'
复制代码
正确使用
  1. 要指定下载的文件名,不能只是一个目录
复制代码
  1. if __name__ == '__main__':
  2.     down_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download\\test.txt", "/home/test.txt")
复制代码
5.上传文件
  1. def upload_file(host, user, psw, local_file, remote_file, port=22):
  2.     with paramiko.Transport((host, port)) as transport:
  3.         # 连接服务
  4.         transport.connect(username=user, password=psw)
  5.         # 获取SFTP示例
  6.         sftp = paramiko.SFTPClient.from_transport(transport)
  7.         sftp.put(local_file, remote_file)
  8.         transport.close()
复制代码
测试同下载,
  1. 特别要注意路径问题
复制代码
。如
  1. if __name__ == '__main__':
  2.     upload_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download\\test123.txt", "/home/test/test123.txt")
复制代码
6.ssh工具封装
  1. import os

  2. import paramiko


  3. class SSHTool():
  4.     def __init__(self, ip, port, user, psw):
  5.         """
  6.         初始化
  7.         :param ip:
  8.         :param port:
  9.         :param user:
  10.         :param psw:
  11.         """
  12.         self.ip = ip
  13.         self.port = port
  14.         self.user = user
  15.         self.psw = psw

  16.     def connect_ssh(self):
  17.         """
  18.         创建连接
  19.         :return:
  20.         """
  21.         try:
  22.             self.ssh = paramiko.SSHClient()
  23.             self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  24.             self.ssh.connect(
  25.                 hostname=self.ip,
  26.                 port=self.port,
  27.                 username=self.user,
  28.                 password=self.psw
  29.             )
  30.         except Exception as e:
  31.             print(e)
  32.         return self.ssh

  33.     def close_ssh(self):
  34.         """
  35.         关闭连接
  36.         :return:
  37.         """
  38.         try:
  39.             self.ssh.close()
  40.         except Exception as e:
  41.             print(e)

  42.     def exec_shell(self, shell):
  43.         ssh = self.connect_ssh()
  44.         try:
  45.             stdin, stdout, stderr = ssh.exec_command(shell)
  46.             return stdin, stdout, stderr
  47.         except Exception as e:
  48.             print(e)

  49.     def sftp_put_file(self, file, local_dir, remote_dir):
  50.         try:
  51.             t = paramiko.Transport((self.ip, self.port))
  52.             t.connect(username=self.user, password=self.psw)
  53.             sftp = paramiko.SFTPClient.from_transport(t)
  54.             sftp.put(os.path.join(local_dir, file), remote_dir)
  55.             t.close()
  56.         except Exception:
  57.             print("connect error!")

  58.     def sftp_get_file(self, file, local_dir, remote_dir):
  59.         try:
  60.             t = paramiko.Transport((self.ip, self.port))
  61.             t.connect(username=self.user, password=self.psw)
  62.             sftp = paramiko.SFTPClient.from_transport(t)
  63.             sftp.get(remote_dir, os.path.join(local_dir, file))
  64.             t.close()
  65.         except Exception:
  66.             print("connect error!")
复制代码
补充

获取当前文件路径:os.getcwd()
  1. import os

  2. if __name__ == '__main__':
  3.     print(os.getcwd())  # D:\MyCode2\py-1\ssh
复制代码
python函数返回多个参数
  1. def get_strs() -> (str, str):
  2.     return "hello", "word"
  3. if __name__ == '__main__':
  4.     # 返回值为元祖的形式
  5.     print(get_strs())  # ('hello', 'word')
  6.     # 获取元祖的个数
  7.     print(len(get_strs()))  # 2
  8.     # 通过下标获取元祖的某一个值
  9.     print(get_strs().__getitem__(1))  # word
  10.     # 通过元祖的某个元素定位对应的下标
  11.     print(get_strs().index("hello"))  # 0
复制代码
with … as …使用
  1. 为了更好地避免此类问题,不同的编程语言都引入了不同的机制。在 Python 中,对应的解决方式是使用 with as 语句操作上下文管理器(context manager),它能够帮助我们自动分配并且释放资源。简单的理解,同时包含 <strong>enter</strong>() 和 <strong>exit</strong>() 方法的对象就是上下文管理器。
复制代码
格式:
  1. with 表达式 [as target]:
  2.     代码块
复制代码
学习参考


  • Python]远程SSH库Paramiko简介_alwaysrun的博客-CSDN博客_python ssh库
  • Python with as用法详解 (biancheng.net)
  • Python中的with-as用法 - 简书 (jianshu.com)
到此这篇关于Python学习之paramiko模块的基础操作与排错的文章就介绍到这了,更多相关Python paramiko模块内容请搜索晓枫资讯以前的文章或继续浏览下面的相关文章希望大家以后多多支持晓枫资讯!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
晓枫资讯-科技资讯社区-免责声明
免责声明:以上内容为本网站转自其它媒体,相关信息仅为传递更多信息之目的,不代表本网观点,亦不代表本网站赞同其观点或证实其内容的真实性。
      1、注册用户在本社区发表、转载的任何作品仅代表其个人观点,不代表本社区认同其观点。
      2、管理员及版主有权在不事先通知或不经作者准许的情况下删除其在本社区所发表的文章。
      3、本社区的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,举报反馈:点击这里给我发消息进行删除处理。
      4、本社区一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
      5、以上声明内容的最终解释权归《晓枫资讯-科技资讯社区》所有。
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~
严禁发布广告,淫秽、色情、赌博、暴力、凶杀、恐怖、间谍及其他违反国家法律法规的内容。!晓枫资讯-社区
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|晓枫资讯--科技资讯社区 本站已运行

CopyRight © 2022-2025 晓枫资讯--科技资讯社区 ( BBS.yzwlo.com ) . All Rights Reserved .

晓枫资讯--科技资讯社区

本站内容由用户自主分享和转载自互联网,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。

如有侵权、违反国家法律政策行为,请联系我们,我们会第一时间及时清除和处理! 举报反馈邮箱:点击这里给我发消息

Powered by Discuz! X3.5

快速回复 返回顶部 返回列表