延續 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() # 暫停查看結果
r"" 原始字串或雙反斜線避免逸出問題sftp.get(remote, local) 參數順序:遠端路徑在前、本地路徑在後-----BEGIN RSA PRIVATE KEY-----)paramiko.util.log_to_file() 記錄除錯資訊