张芷铭的个人博客

Paramiko 是 Python 的 SSH 客户端库,支持远程命令执行和 SFTP 文件传输。

安装

1
pip install paramiko

SSH 连接

1
2
3
4
5
6
7
8
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("hostname", port=22, username="user", password="pass")

# 或使用密钥
# ssh.connect("hostname", username="user", key_filename="/path/to/key")

执行远程命令

1
2
3
stdin, stdout, stderr = ssh.exec_command("ls -la")
print(stdout.read().decode())
print(stderr.read().decode())

SFTP 文件传输

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
sftp = ssh.open_sftp()

# 下载文件
sftp.get("/remote/path/file.txt", "/local/path/file.txt")

# 上传文件
sftp.put("/local/path/file.txt", "/remote/path/file.txt")

# 列出目录
files = sftp.listdir("/remote/path")

sftp.close()

完整示例

 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
import paramiko
import os

# 连接配置
host, port = "server.ip", 22
username, password = "user", "pass"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)

# 执行命令读取远程文件
stdin, stdout, stderr = ssh.exec_command("cat /path/to/file.csv")
lines = stdout.read().decode().splitlines()

# 提取文件路径并下载
file_path = lines[0].split("\t")[0]
local_path = os.path.join("./downloads", os.path.basename(file_path))

sftp = ssh.open_sftp()
sftp.get(file_path, local_path)
sftp.close()

ssh.close()
print(f"Downloaded: {local_path}")

VSCode Remote SSH vs Paramiko

方式适用场景优点
VSCode Remote SSH手动操作、少量文件可视化、简单
Paramiko批量下载、自动化可编程、适合脚本

最佳实践

  1. 使用 SSH Key 替代密码
  2. 使用 with 语句管理连接
  3. 处理异常和超时
  4. 使用线程池并行传输多文件

Comments