首页 > 技术文章 > scp使用expect自动输入密码

mosicol 2020-05-09 16:59 原文

1.安装expect

yum install expect

2.编写脚本

#!/usr/bin/expect
set timeout 10
set username [lindex $argv 0]
set host [lindex $argv 1]
#{}包起来密码,因为密码中有个“[”会报错,或者使用\转义  解决方法:http://www.itkeyword.com/doc/8240821665859082x125/expect-script-error-missing-close-brackets
set password {[nk3d*****sgj9}
set src_file [lindex $argv 2]
set dest_file [lindex $argv 3]
spawn scp $username@$host:$src_file $dest_file
expect {
"(yes/no)?"
{
send "yes\n"
expect "*assword" { send "$password\n"}
}
"*assword"
{
send "$password\n"
}
}
expect "100%"
expect eof

3.赋予执行权限并执行

chmod +x sa.exp
./sa.exp root host /root/*.tar.gz /root/

4.针对missing close-bracket的解决办法:

 

推荐阅读