Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Copy file lên server remote bằng Python (SCP/SSH)

Hai cách chính: dùng lệnh scp qua subprocess, hoặc dùng thư viện scp + paramiko.

Cách 1: subprocess + scp (system command)

import subprocess
import os

p = subprocess.Popen(["scp", "my_file.txt", "username@server:/remote/path"])
sts = os.waitpid(p.pid, 0)  # chờ hoàn tất

Cách 2: paramiko + scp module (pure Python, khuyến nghị)

pip install paramiko scp
from paramiko import SSHClient
from scp import SCPClient

with SSHClient() as ssh:
    ssh.load_system_host_keys()
    ssh.connect('user@server', key_filename='~/.ssh/id_rsa')
    
    with SCPClient(ssh.get_transport()) as scp:
        scp.put('my_file.txt', '/remote/path/my_file.txt')  # upload
        # scp.get('/remote/path/remote_file.txt', 'local_file.txt')  # download

So sánh

Tiêu chísubprocess+scpparamiko+scp
Phụ thuộc OSCần scp commandPure Python
Xử lý lỗiKhó khănDễ dàng (exception)
Progress callbackKhôngCó (callback param)
Đa fileGọi nhiều lầnscp.put(list_files, remote_dir)