Paramiko:SSH连接,Python的远程控制

文摘   2024-11-02 13:28   广东  

▼点击下方卡片关注我

▲点击上方卡片关注我


想在Python里远程连接服务器,执行Shell命令?Paramiko这个库就是专门干这个的。它是Python实现SSH2协议的一个库,说白了就是能让你用Python代码来远程控制服务器,跟在终端里敲命令是一个效果。


SSH连接基本用法

连接远程服务器最常用的方式是用户名密码认证:


1import paramiko

3# 创建SSH客户端

4ssh = paramiko.SSHClient()

5# 自动添加主机密钥

6ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

8# 连接远程服务器

9ssh.connect(

10 hostname='192.168.1.100',

11 port=22,

12 username='root',

13 password='password123'

14)

16# 执行命令

17stdin, stdout, stderr = ssh.exec_command('ls -l')

18# 获取输出

19result = stdout.read().decode()

20print(result)

22# 关闭连接

23ssh.close()

⚠️ 小贴士:


  • 记得处理连接异常,生产环境别裸写

  • 用完及时关连接,别耗服务器资源

  • 密码不要写死在代码里,该用配置文件存着


密钥认证登录

密码登录不够安全,用密钥认证更靠谱:


1import paramiko

3# 创建密钥对象

4private_key = paramiko.RSAKey.from_private_key_file(

5 '/path/to/id_rsa' # 私钥文件路径

6)

8ssh = paramiko.SSHClient()

9ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

11# 使用密钥连接

12ssh.connect(

13 hostname='192.168.1.100',

14 username='root',

15 pkey=private_key # 用密钥替代密码

16)

18# 后续操作一样...

19ssh.close()

批量执行命令

有时候要执行一堆命令,一个个写多麻烦:


1def batch_execute(ssh, commands):

2 “”“批量执行命令并获取结果”“”

3 results = []

4 for cmd in commands:

5 stdin, stdout, stderr = ssh.exec_command(cmd)

6 result = {

7 'command':cmd,

8 'output':stdout.read().decode(),

9 'error':stderr.read().decode()

10 }

11 results.append(result)

12 return results

14# 命令列表

15commands = [

16 'df -h', # 查看磁盘使用情况

17 'free -m', # 查看内存使用

18 'top -b -n 1' # 查看进程状态

19]

21# 执行命令

22results = batch_execute(ssh, commands)

24# 打印结果

25for result in results:

26 print(f“命令:{result['command']}”)

27 print(f“输出:\n{result['output']}”)

28 if result['error']:

29 print(f“错误:\n{result['error']}”)

30 print('-' * 50)

SFTP文件传输

SSH不光能执行命令,还能传文件:


1def upload_file(ssh, local_path, remote_path):

2 “”“上传文件到远程服务器”“”

3 sftp = ssh.open_sftp()

4 sftp.put(local_path, remote_path)

5 sftp.close()

7def download_file(ssh, remote_path, local_path):

8 “”“从远程服务器下载文件”“”

9 sftp = ssh.open_sftp()

10 sftp.get(remote_path, local_path)

11 sftp.close()

13# 使用示例

14upload_file(ssh, '/local/test.txt', '/remote/test.txt')

15download_file(ssh, '/remote/result.log', '/local/result.log')

⚠️ 小贴士:


  • 文件传输要考虑超时设置

  • 大文件建议用分块传输

  • 记得检查磁盘空间够不够


交互式命令执行

有些命令需要人机交互,比如输密码啥的:


1import time

3def interactive_shell(ssh, command, inputs):

4 “”“执行交互式命令”“”

5 # 获取Shell通道

6 channel = ssh.invoke_shell()

8 # 发送命令

9 channel.send(command + '\n')

10 time.sleep(0.5) # 等待命令响应

12 # 处理交互输入

13 for user_input in inputs:

14 channel.send(user_input + '\n')

15 time.sleep(0.5)

17 # 获取所有输出

18 output = ''

19 while channel.recv_ready():

20 output += channel.recv(1024).decode()

22 channel.close()

23 return output

25# 使用示例

26inputs = ['yes', 'new_password', 'new_password']

27result = interactive_shell(ssh, 'passwd', inputs)

差不多就这些,Paramiko还有不少高级功能,比如连接代理、压缩传输啥的。不过掌握这些基本操作,日常自动化运维应该够用了。最好配合异常处理和重试机制,生产环境用起来稳稳的。


往期回顾

◆ unittest:Python单元测试,守护你的代码

◆ logging:日志记录,Python的史官

◆ Pandas:Python数据分析的王者,掌握它就掌握了数据  

点赞分享


流向你

墨香玄
每日陪伴,聊聊关于车的这些事,理性与感性双管齐下,饮茶品文,有缘共谈!
 最新文章