插件窝 干货文章 Python怎么通过paramiko库实现远程执行linux命令

Python怎么通过paramiko库实现远程执行linux命令

Paramiko 命令 SSH 使用 651    来源:    2025-04-24

使用Paramiko库实现远程执行Linux命令

Paramiko是一个Python实现的SSHv2协议库,可以用于远程连接Linux服务器并执行命令。下面我将详细介绍如何使用Paramiko实现这一功能。

基本使用方法

1. 安装Paramiko

首先需要安装paramiko库:

pip install paramiko

2. 基本连接与执行命令

import paramiko

# 创建SSH客户端实例
ssh = paramiko.SSHClient()

# 自动添加主机密钥(生产环境应考虑更安全的方式)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接服务器
ssh.connect(hostname='服务器IP', 
           port=22, 
           username='用户名', 
           password='密码')

# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls -l')

# 获取命令输出
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')

# 打印输出
print("输出:", output)
if error:
    print("错误:", error)

# 关闭连接
ssh.close()

高级用法

1. 使用密钥认证

# 使用私钥文件连接
private_key = paramiko.RSAKey.from_private_key_file('/path/to/private_key.pem')
ssh.connect(hostname='服务器IP', 
           port=22, 
           username='用户名', 
           pkey=private_key)

2. 执行多个命令

# 使用分号分隔多个命令
commands = """
cd /tmp;
ls -l;
pwd;
"""
stdin, stdout, stderr = ssh.exec_command(commands)

3. 使用SSH Transport复用连接

transport = paramiko.Transport(('服务器IP', 22))
transport.connect(username='用户名', password='密码')

ssh = paramiko.SSHClient()
ssh._transport = transport

# 执行命令...
stdin, stdout, stderr = ssh.exec_command('uname -a')

# 完成后关闭
transport.close()

4. 处理交互式命令

# 创建交互式shell
channel = ssh.invoke_shell()
channel.send('sudo ls /root\n')
channel.send('密码\n')  # 如果是sudo需要密码

import time
time.sleep(1)  # 等待命令执行

output = channel.recv(9999).decode('utf-8')
print(output)

完整示例代码

import paramiko
from getpass import getpass

def remote_execute(host, port, username, password=None, key_path=None, command=''):
    try:
        # 创建SSH客户端
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接服务器
        if key_path:
            private_key = paramiko.RSAKey.from_private_key_file(key_path)
            ssh.connect(hostname=host, port=port, username=username, pkey=private_key)
        else:
            ssh.connect(hostname=host, port=port, username=username, password=password)

        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)

        # 获取输出
        output = stdout.read().decode('utf-8').strip()
        error = stderr.read().decode('utf-8').strip()

        return {
            'output': output,
            'error': error,
            'status': 'success'
        }

    except Exception as e:
        return {
            'output': '',
            'error': str(e),
            'status': 'failed'
        }
    finally:
        # 确保连接关闭
        if 'ssh' in locals():
            ssh.close()

# 使用示例
if __name__ == '__main__':
    host = input("输入服务器IP: ")
    port = 22
    username = input("输入用户名: ")
    use_key = input("使用密钥认证? (y/n): ").lower() == 'y'

    if use_key:
        key_path = input("输入私钥路径: ")
        password = None
    else:
        key_path = None
        password = getpass("输入密码: ")

    command = input("输入要执行的命令: ")

    result = remote_execute(
        host=host,
        port=port,
        username=username,
        password=password,
        key_path=key_path,
        command=command
    )

    print("\n执行结果:")
    if result['status'] == 'success':
        if result['output']:
            print("输出:\n", result['output'])
        if result['error']:
            print("错误:\n", result['error'])
    else:
        print("执行失败:", result['error'])

安全注意事项

  1. 不要硬编码密码:在实际应用中,应该使用环境变量或配置文件来存储敏感信息
  2. 验证主机密钥:生产环境中不应该使用AutoAddPolicy,而应该预先验证主机密钥
  3. 使用SSH密钥:尽可能使用SSH密钥认证而非密码认证
  4. 限制权限:使用具有最小必要权限的账户执行命令
  5. 清理敏感信息:使用后及时清理内存中的密码等敏感信息

常见问题解决

  1. 认证失败

    • 检查用户名/密码是否正确
    • 确认服务器是否允许密码认证(/etc/ssh/sshd_config中PasswordAuthentication yes
    • 如果是密钥认证,确认私钥文件权限是否为600
  2. 连接超时

    • 检查网络连接
    • 确认防火墙是否放行了SSH端口
    • 确认SSH服务是否正常运行
  3. 命令无输出

    • 确保命令会产生输出(有些命令如cd不会产生输出)
    • 添加-v参数查看详细执行过程

通过以上方法,你可以灵活地使用Paramiko库在Python中实现远程执行Linux命令的功能。