使用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进行批量文件传输,提高工作效率。