使用SFTP進行批量操作可以通過多種方式實現,以下是使用Python庫pysftp和命令行工具的方法:
pysftp進行批量操作pysftp庫:pip install pysftp
import pysftp
import os
local_dir = '本地目錄路徑'
remote_dir = '遠程目錄路徑'
with pysftp.Connection('服務器地址', username='用戶名', password='密碼') as sftp:
for filename in os.listdir(local_dir):
local_file = os.path.join(local_dir, filename)
remote_file = os.path.join(remote_dir, filename)
sftp.put(local_file, remote_file)
print("批量上傳完成!")
import pysftp
import os
local_dir = '本地目錄路徑'
remote_dir = '遠程目錄路徑'
with pysftp.Connection('服務器地址', username='用戶名', password='密碼') as sftp:
for filename in os.listdir(remote_dir):
remote_file = os.path.join(remote_dir, filename)
local_file = os.path.join(local_dir, filename)
sftp.get(remote_file, local_file)
print("批量下載完成!")
file_list.txt,每個文件路徑占一行。batch_upload.sh)來自動化SFTP批量上傳過程。#!/bin/bash
REMOTE_HOST="your_remote_host"
USERNAME="your_username"
PASSWORD="your_password"
REMOTE_DIR="/path/to/remote/directory"
sftp -b - $USERNAME@$REMOTE_HOST << EOF
cd $REMOTE_DIR
while read -r file; do
put "$file"
done < file_list.txt
EOF
為腳本添加可執行權限并運行:
chmod x batch_upload.sh
./batch_upload.sh
sftp命令結合while循環逐行讀取文件列表并下載文件。#!/bin/bash
REMOTE_HOST="your_remote_host"
USERNAME="your_username"
PASSWORD="your_password"
REMOTE_DIR="/path/to/remote/directory"
LOCAL_DIR="/path/to/local/directory"
sftp -b - $USERNAME@$REMOTE_HOST << EOF
cd $REMOTE_DIR
while read -r file; do
get "$file" "$LOCAL_DIR/$file"
done < file_list.txt
EOF
通過上述方法,你可以使用SFTP進行批量文件傳輸,提高工作效率。