在CentOS系統中,使用SFTP(SSH File Transfer Protocol)進行文件傳輸是一種常見的需求。為了實現自動化操作,可以編寫腳本來執行一系列的SFTP命令。以下是一個基本的示例,展示如何使用Shell腳本來自動化SFTP操作。
假設你需要從一個本地目錄上傳文件到遠程服務器,并從遠程服務器下載文件到本地目錄。你可以創建一個名為sftp_script.sh
的Shell腳本,并按照以下步驟進行配置:
創建Shell腳本文件:
nano sftp_script.sh
編寫SFTP腳本:
在腳本中,你可以使用expect
工具來自動化交互式的SFTP會話。首先確保你已經安裝了expect
:
sudo yum install expect -y
然后編寫腳本內容:
#!/usr/bin/expect -f
# 設置超時時間
set timeout 20
# 設置變量
set host "remote_host"
set username "your_username"
set password "your_password"
set local_dir "/path/to/local/directory"
set remote_dir "/path/to/remote/directory"
set local_file "local_file.txt"
set remote_file "remote_file.txt"
# 啟動SFTP會話
spawn sftp $username@$host
# 匹配密碼提示并輸入密碼
expect "password:"
send "$password\r"
# 切換到遠程目錄
expect "sftp>"
send "cd $remote_dir\r"
# 上傳文件
expect "sftp>"
send "put $local_dir/$local_file\r"
# 下載文件
expect "sftp>"
send "get $remote_dir/$remote_file $local_dir\r"
# 退出SFTP會話
expect "sftp>"
send "bye\r"
# 結束expect腳本
expect eof
賦予腳本執行權限:
chmod +x sftp_script.sh
運行腳本:
./sftp_script.sh
如果你希望使用SSH密鑰認證而不是密碼認證,可以按照以下步驟進行配置:
生成SSH密鑰對(如果還沒有):
ssh-keygen -t rsa
將公鑰復制到遠程服務器:
ssh-copy-id your_username@remote_host
修改腳本以使用密鑰認證:
#!/usr/bin/expect -f
# 設置超時時間
set timeout 20
# 設置變量
set host "remote_host"
set username "your_username"
set private_key "/path/to/private_key"
set local_dir "/path/to/local/directory"
set remote_dir "/path/to/remote/directory"
set local_file "local_file.txt"
set remote_file "remote_file.txt"
# 啟動SFTP會話
spawn sftp -i $private_key $username@$host
# 匹配密碼提示并輸入密碼(如果需要)
expect "password:"
send "your_password\r"
# 切換到遠程目錄
expect "sftp>"
send "cd $remote_dir\r"
# 上傳文件
expect "sftp>"
send "put $local_dir/$local_file\r"
# 下載文件
expect "sftp>"
send "get $remote_dir/$remote_file $local_dir\r"
# 退出SFTP會話
expect "sftp>"
send "bye\r"
# 結束expect腳本
expect eof
通過這種方式,你可以實現SFTP操作的自動化,并且提高腳本的安全性和可靠性。