萬盛學電腦網

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

Python Paramiko 實戰:SSH 遠端執行指令與 SFTP 自動下載伺服器日誌

延續 SSH 連線基礎,本文示範如何結合 paramiko.SSHClient 執行遠端腳本,並透過 SFTPClient 批量下載日誌檔案,涵蓋密碼與金鑰兩種認證方式。

完整自動化腳本

#coding:utf-8
import paramiko, time

hostname = "your.host"
port = 22
username = "app"
password = "secret"

if __name__ == "__main__":
    # 1. SSH 執行遠端腳本
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname, port, username, password, timeout=4)
    stdin, stdout, stderr = ssh.exec_command("sh ~/log/check")
    print(stdout.read())
    ssh.close()

    # 2. SFTP 下載日誌
    transport = paramiko.Transport((hostname, port))
    transport.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(transport)

    files = sftp.listdir("/home/app/log/")
    for f in files:
        print(f)

    today = time.strftime('%Y-%m-%d', time.localtime())
    sftp.get("/home/app/log/server.txt", r"C:\Users\Administrator\Desktop\server.txt")
    sftp.get(f"/home/app/log/{today}.log.zip", f"C:\\Users\\Administrator\\Desktop\\{today}.log.zip")

    # 3. 金鑰認證示範
    pkey = paramiko.RSAKey.from_private_key_file(r"E:\yy\tools\key\rsa.txt")
    ssh2 = paramiko.SSHClient()
    ssh2.load_system_host_keys()
    ssh2.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh2.connect(hostname, port, username, pkey=pkey)
    stdin, stdout, stderr = ssh2.exec_command("ls -l /home/app/log")
    print(stdout.read())
    ssh2.close()

    raw_input()  # 暫停查看結果

關鍵點提醒

  • Windows 路徑建議使用 r"" 原始字串或雙反斜線避免逸出問題
  • sftp.get(remote, local) 參數順序:遠端路徑在前、本地路徑在後
  • 金鑰檔需為 OpenSSH 格式(-----BEGIN RSA PRIVATE KEY-----)
  • 生產環境請啟用 paramiko.util.log_to_file() 記錄除錯資訊
copyright © 萬盛學電腦網 all rights reserved