Paramiko 是一个纯Python实现的SSHv2协议库,提供了SSH客户端和服务器的功能。
1. 核心类介绍
SSHClient 类
主要的SSH客户端类,用于连接到远程服务器。
import paramiko
import logging
# 启用调试日志(可选)
logging.basicConfig(level=logging.DEBUG)
# 创建SSH客户端实例
ssh = paramiko.SSHClient()主机密钥策略
# 自动添加未知主机密钥(开发环境)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 拒绝未知主机(生产环境推荐)
ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
# 使用已知主机文件
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.WarningPolicy())2. 连接方式
密码认证
try:
ssh.connect(
hostname='192.168.1.100',
port=22,
username='username',
password='password',
timeout=10
)
print("连接成功")
except paramiko.AuthenticationException:
print("认证失败")
except paramiko.SSHException as e:
print(f"SSH连接错误: {e}")
except Exception as e:
print(f"其他错误: {e}")密钥认证
# 使用RSA密钥
private_key = paramiko.RSAKey.from_private_key_file('/path/to/private_key')
# 使用Ed25519密钥
private_key = paramiko.Ed25519Key.from_private_key_file('/path/to/private_key')
ssh.connect(
hostname='192.168.1.100',
username='username',
pkey=private_key
)带密码的密钥
private_key = paramiko.RSAKey.from_private_key_file(
'/path/to/private_key',
password='key_password'
)3. 执行命令
基本命令执行
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls -l')
# 获取输出
exit_status = stdout.channel.recv_exit_status() # 获取退出状态
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
print(f"退出状态: {exit_status}")
print(f"输出: {output}")
if error:
print(f"错误: {error}")带输入的命令执行
stdin, stdout, stderr = ssh.exec_command('sudo apt-get update')
stdin.write('your_password\n')
stdin.flush()
output = stdout.read().decode('utf-8')
print(output)超时设置
stdin, stdout, stderr = ssh.exec_command('long_running_command', timeout=30)
















