最近编程中用到sftp上传文件,且需要用crontab预设定时上传事件。而sftp不同于ftp,没有提供选项如 -i 可以将密码直接编码进程序。使用sftp指令,会自动请求用户输入密码。
总结一下可以避免sftp输入密码的三种方式:
1. lftp方式
#!/bin/sh
HOST=172.16.2.X
USER=kg_sftp
PASS=tnzk4a7w
echo "Starting to sftp..."
lftp -u ${USER},${PASS} sftp://${HOST} <
2. expect方式
Expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。
要使用expect需要预先安装tcl这个东西,然后再安装expect包。
tcl: http://prdownloads.sourceforge.net/tcl/tcl8.4.16-src.tar.gz
expect: http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz/download
例子:
#!/usr/local/bin/expect -f
#<---insert here your expect program location
#procedure to attempt connecting; result 0 if OK, 1 elsewhere
proc connect {passw} {
expect {
"(yes/no)?" {send "yes/r";exp_continue} #第一次使用SFTP时候会要求输入yes/no
"password:" {send "$passw/r" #自动输入密码
expect {
"sftp*" { #检测返回sftp>
return 0
}
}
}
}
# timed out
return 1
}
#read the input parameters
set user [lindex $argv 0]
set passw [lindex $argv 1]
set host [lindex $argv 2]
set location [lindex $argv 3]
set file1 [lindex $argv 4]
#puts "Am citit:/n";
#puts "user: $user";
#puts "passw: $passw";
#puts "host: $host";
#puts "location: $location";
#puts "file1: $file1";
#check if all were provided
if { $user == "" || $passw == "" || $host == "" || $location == "" || $file1 == "" } {
puts "Usage: /n"
exit 1
}
#sftp to specified host and send the files
spawn sftp $user@$host
set rez [connect $passw]
if { $rez == 0 } {
send "cd $location/r"
set timeout -1
send "put $file1/r"
#send "ls -l/r"
#send "quit/r"
#send "mkdir testsftp/r"
send "quit/r"
expect eof
exit 0
}
puts "/nCMD_ERR: connecting to server: $host!/n"
exit 1
0
expect也可以用两种形式调用
1 ./my.exp $usr $pwd $host $local $file
2. 代码中直接插入
expect<
...
!
3. (推荐)生成密钥对
因为这种方式不用把密钥卸载程序里,所以更安全