paramiko 是一个 Python 库,它实现了 SSHv2 协议,允许用户在 Python 程序中执行远程命令、传输文件以及与支持 SSH 的服务器进行安全的交互。以下是使用 paramiko 模块的基本步骤和范例:
基本使用方法:
- 安装模块:
pip install paramiko
- 创建 SSH 客户端: 使用 paramiko.SSHClient 创建一个新的 SSH 客户端对象。
import paramiko
ssh = paramiko.SSHClient()
- 自动添加主机密钥到本地缓存(可选): 为了简化初次连接时的信任验证,可以设置客户端策略以自动接受未知主机的密钥。
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- 建立 SSH 连接: 提供远程主机地址、端口号、用户名及密码来连接远程服务器。
ssh.connect(hostname='remote_host', port=22, username='username', password='password')
- 执行远程命令: 可以通过 exec_command() 方法执行命令,并获取标准输出和错误输出。
stdin, stdout, stderr = ssh.exec_command('ls -l')
# 获取命令结果
output = stdout.read().decode('utf-8') # 解码为字符串
error_output = stderr.read().decode('utf-8')
print("Command Output:\n", output)
print("Error Output:\n", error_output)
- 关闭连接: 在完成所有操作后,确保关闭 SSH 连接。
ssh.close()
示例代码整合:
import paramiko
def run_remote_command(host, port, username, password, command):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname=host, port=port, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.read().decode('utf-8')
error_output = stderr.read().decode('utf-8')
print(f"Command Output: {output}")
print(f"Error Output: {error_output}")
except paramiko.AuthenticationException as e:
print("Authentication failed.")
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
ssh.close()
# 使用示例
run_remote_command(
host='your_server_ip',
port=22,
username='username',
password='password',
command='ls -l /home/user'
)
注意事项:
- 如果使用的是私钥认证,可以通过 RSAKey.from_private_key_file() 加载私钥并替换密码参数:
pkey = paramiko.RSAKey.from_private_key_file('/path/to/private_key.pem')
ssh.connect(..., pkey=pkey)
- 在实际应用中,应谨慎处理敏感信息如密码和私钥内容,避免硬编码。
- 对于长时间运行的任务,可能需要处理子进程的通道或流以防止阻塞。