萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python Paramiko 實現 SSH 遠程操作 Linux 服務器完整指南

Paramiko 核心能力

Paramiko 是 Python 領先的 SSHv2 協議實現,支援命令執行、文件傳輸 (SFTP)、端口轉發、密鑰認證,是自動化運維、部署腳本、雲資源管理的標準工具。

安裝與依賴

pip install paramiko
# 依賴 cryptography, bcrypt, pynacl 等加密庫

基礎連接與命令執行


import paramiko

def ssh_execute(host, username, password, command, port=22, timeout=10):
    """執行單條命令,返回 (stdout, stderr, exit_code)"""
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自動接受未知主機鑰
    
    try:
        client.connect(
            hostname=host,
            port=port,
            username=username,
            password=password,
            timeout=timeout,
            allow_agent=False,
            look_for_keys=False
        )
        
        stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
        exit_code = stdout.channel.recv_exit_status()  # 阻塞等待命令結束
        
        return stdout.read().decode('utf-8'), stderr.read().decode('utf-8'), exit_code
        
    finally:
        client.close()

# 使用示例
stdout, stderr, code = ssh_execute(
    '172.28.102.249', 'root', 'toor', 
    'ifconfig; free -h; df -h'
)
print(f"Exit: {code}")
print(f"STDOUT:\n{stdout}")
if stderr: print(f"STDERR:\n{stderr}")

密鑰認證(生產環境推薦)


def ssh_with_key(host, username, key_path, command, port=22):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    private_key = paramiko.RSAKey.from_private_key_file(key_path)
    # 或支援 Ed25519: paramiko.Ed25519Key.from_private_key_file(key_path)
    
    client.connect(hostname=host, port=port, username=username, 
                   pkey=private_key, timeout=10)
    
    stdin, stdout, stderr = client.exec_command(command)
    return stdout.read().decode(), stderr.read().decode(), stdout.channel.recv_exit_status()

SFTP 文件傳輸


def sftp_transfer(host, username, password, local_path, remote_path, upload=True):
    transport = paramiko.Transport((host, 22))
    transport.connect(username=username, password=password)
    
    sftp = paramiko.SFTPClient.from_transport(transport)
    
    try:
        if upload:
            sftp.put(local_path, remote_path)
            print(f"Uploaded: {local_path} -> {remote_path}")
        else:
            sftp.get(remote_path, local_path)
            print(f"Downloaded: {remote_path} -> {local_path}")
    finally:
        sftp.close()
        transport.close()

# 批量上傳目錄
def sftp_upload_dir(sftp, local_dir, remote_dir):
    for root, dirs, files in os.walk(local_dir):
        for d in dirs:
            local = os.path.join(root, d)
            remote = os.path.join(remote_dir, os.path.relpath(local, local_dir))
            try:
                sftp.mkdir(remote)
            except IOError:
                pass  # 目錄已存在
        for f in files:
            local = os.path.join(root, f)
            remote = os.path.join(remote_dir, os.path.relpath(local, local_dir))
            sftp.put(local, remote)

進階:交互式 Shell 與通道控制


def interactive_shell(host, username, password):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host, username=username, password=password)
    
    channel = client.invoke_shell()  # 獲取交互式 Shell 通道
    channel.settimeout(0.5)
    
    # 發送命令
    channel.send("cd /var/log\n")
    channel.send("tail -f syslog\n")
    
    # 讀取輸出 (非阻塞輪詢)
    while True:
        if channel.recv_ready():
            output = channel.recv(4096).decode('utf-8', errors='ignore')
            print(output, end='')
        if channel.exit_status_ready():
            break
        time.sleep(0.1)
    
    channel.close()
    client.close()

異常處理與重試策略


import socket
from paramiko.ssh_exception import (
    AuthenticationException, SSHException, NoValidConnectionsError
)

def robust_ssh_execute(host, username, password, command, max_retries=3):
    for attempt in range(max_retries):
        try:
            return ssh_execute(host, username, password, command)
        except AuthenticationException:
            raise  # 認證失敗不重試
        except (SSHException, NoValidConnectionsError, socket.timeout, socket.error) as e:
            if attempt == max_retries - 1:
                raise
            wait = 2 ** attempt  # 指數退避
            print(f"Attempt {attempt+1} failed: {e}, retry in {wait}s")
            time.sleep(wait)

生產環境最佳實踐

  1. 連接池複用:長連接執行多命令,避免頻繁握手開銷
  2. Known Hosts 驗證:生產環境禁用 AutoAddPolicy,預載入 known_hosts
  3. 並發控制:使用 concurrent.futures.ThreadPoolExecutor 限制並發連接數
  4. 日誌審計:記錄命令、耗時、退出碼、輸出摘要
  5. 跳板機/代理:paramiko.ProxyCommand 支援堡壘機跳轉

現代替代:Fabric / Invoke


# Fabric 3 (基於 Paramiko/Invoke)
from fabric import Connection

c = Connection('host', user='root', connect_kwargs={"password": "toor"})
result = c.run('uname -a', hide=True)
print(result.stdout)
c.put('local.txt', '/remote.txt')

Paramiko 是 Python SSH 自動化的基石,掌握其核心 API 能構建強大的基礎設施自動化工具鏈。

copyright © 萬盛學電腦網 all rights reserved