在Linux中,使用SFTP(SSH File Transfer Protocol)脚本可以自动化文件传输过程
打开终端。
使用文本编辑器创建一个名为sftp_script.sh
的新文件。例如,使用nano编辑器:
nano sftp_script.sh
sftp_script.sh
文件中,编写以下内容并根据需要进行修改:#!/bin/bash
# 设置SFTP服务器的详细信息
sftp_server="your_sftp_server.com"
sftp_port="22"
sftp_username="your_username"
sftp_password="your_password"
# 设置本地和远程文件路径
local_file_path="/path/to/local/file"
remote_file_path="/path/to/remote/file"
# 使用SFTP连接到服务器并传输文件
sftp -oPort=$sftp_port $sftp_username@$sftp_server <<EOF
put $local_file_path $remote_file_path
bye
EOF
请确保将your_sftp_server.com
、your_username
、your_password
、/path/to/local/file
和/path/to/remote/file
替换为实际的值。
保存并关闭文件。
使脚本可执行:
chmod +x sftp_script.sh
./sftp_script.sh
这将使用SFTP连接到指定的服务器,并将本地文件上传到远程服务器。如果需要从远程服务器下载文件,只需将put
命令更改为get
命令即可。
注意:出于安全原因,建议使用SSH密钥对进行身份验证,而不是在脚本中使用密码。要在SFTP中使用SSH密钥,请将sftp_password
变量删除,并在<<EOF
之前添加以下行:
IdentityFile /path/to/your/private_key
将/path/to/your/private_key
替换为您的私钥文件的实际路径。