Ubuntu SFTP支持大文件传输的配置与优化方法
要支持大文件传输,首先需确认SFTP服务已正确安装并配置。安装OpenSSH服务器(包含SFTP功能):
sudo apt update && sudo apt install openssh-server
编辑SSH配置文件/etc/ssh/sshd_config,启用SFTP子系统(取消注释或添加以下行):
Subsystem sftp /usr/lib/openssh/sftp-server
若需限制用户访问特定目录(如/home/username/uploads),可添加Match规则(推荐用于安全隔离):
Match Group sftpusers
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
注意:ChrootDirectory需指向用户主目录(如%h),且该目录及其父目录需设置为root:root所有权、755权限(避免用户越权修改);用户需在单独子目录(如uploads)中写入文件,该子目录需设置为755权限并归属用户。
通过命令行参数调整SFTP的缓冲区大小和超时时间,减少大文件传输中断风险:
sftp -o SendBufSize=65536 -o TimeOut=600 username@remote_host
SendBufSize:设置发送缓冲区大小(单位:字节,如65536=64KB),增大缓冲区可提升传输效率;TimeOut:设置连接超时时间(单位:秒,如600=10分钟),避免因网络波动导致传输中断。将大文件分割为小块(如1GB/块),分别传输后合并:
# 分割文件(本地)
split -b 1G /path/to/largefile.zip /path/to/temp/largefile.zip.part.
# 传输分块(SFTP)
sftp username@remote_host <<EOF
put /path/to/temp/largefile.zip.part.* /remote/directory/
EOF
# 合并分块(远程)
ssh username@remote_host "cat /remote/directory/largefile.zip.part.* > /remote/directory/largefile.zip"
使用-C选项启用断点续传,传输中断后可继续未完成的部分:
sftp -C username@remote_host <<EOF
put /path/to/largefile.zip /remote/directory/
EOF
传输前压缩文件(如用gzip),降低传输时间和带宽占用:
gzip /path/to/largefile.zip
sftp username@remote_host <<EOF
put /path/to/largefile.zip.gz /remote/directory/
EOF
远程服务器解压:gunzip /remote/directory/largefile.zip.gz。
通过pv命令实时显示传输进度(需提前安装:sudo apt install pv):
# 监控上传进度
pv /path/to/largefile.zip | sftp username@remote_host <<EOF
put - /remote/directory/largefile.zip
EOF
# 监控下载进度
sftp username@remote_host <<EOF
get /remote/directory/largefile.zip -
EOF | pv > /path/to/local/largefile.zip
chmod 755 /remote/directory);sudo ufw allow 22)。通过以上配置和优化,Ubuntu SFTP可高效、稳定地支持大文件传输。