使用SFTP进行批量操作可以通过命令行或编写脚本来实现。以下是几种常见的方法:
上传多个文件到远程服务器:
sftp user@hostname "put *.txt"
这将上传当前目录下的所有.txt
文件到远程服务器的当前目录。
从远程服务器下载多个文件:
sftp user@hostname "get *.log"
这将下载远程服务器当前目录下的所有.log
文件到本地当前目录。
batch_upload.sh
的脚本文件,内容如下:#!/bin/bash
REMOTE_HOST="your_remote_host"
USERNAME="your_username"
PASSWORD="your_password"
REMOTE_DIR="/path/to/remote/directory"
# 使用sftp命令连接到远程服务器
sftp -b - $USERNAME@$REMOTE_HOST << EOF
cd $REMOTE_DIR
# 从file_list.txt中逐行读取文件路径
while read -r file; do
# 上传文件
put "$file"
done < file_list.txt
quit
EOF
chmod x batch_upload.sh
./batch_upload.sh
pip install pysftp
import pysftp
with pysftp.Connection('your_server', username='your_username', password='your_password') as sftp:
local_dir = 'local_folder'
remote_dir = '/remote/path/folder'
for filename in os.listdir(local_dir):
local_path = os.path.join(local_dir, filename)
remote_path = os.path.join(remote_dir, filename)
sftp.put(local_path, remote_path)
print("批量上传完成!")
这段代码会把本地目录下的所有文件都上传到远程目录。
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
import com.jcraft.jsch.*;
public class SFTP批量操作 {
public static void main(String[] args) {
String SFTPHOST = "your_sftp_server_hostname";
int SFTPPORT = 22;
String SFTPUSER = "your_username";
String SFTPPASS = "your_password";
String SFTPWORKINGDIR = "/path/to/remote/directory";
Session session = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.cd(SFTPWORKINGDIR);
String localDirectory = "local_folder";
String remoteDirectory = "/remote/path/folder";
for (File file : new File(localDirectory).listFiles()) {
String localFilePath = file.getAbsolutePath();
String remoteFilePath = remoteDirectory + "/" + file.getName();
channelSftp.put(localFilePath, remoteFilePath);
}
} catch (JSchException | SftpException e) {
e.printStackTrace();
} finally {
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.exit();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
}
这段代码实现了从本地文件夹批量上传文件到服务器目标文件夹。
请根据您的具体需求和环境选择合适的方法进行SFTP批量操作。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:SFTP如何进行批量操作