利用expect + sftp 实现远程主机自动登录及下载:
#!/usr/bin/expect -f
## Create by Cyril.
## "Usage:./downFilesFromStation USER PWD RemoteIP SourcePath DownloadPath"
if {$argc<5} {
puts stderr "Usage:./downFilesFromStation USER PWD RemoteIP SourcePath DownloadPath"
exit 1
}
set timeout 5
set USER [lindex $argv 0]
set PWD [lindex $argv 1]
set RemoteIP [lindex $argv 2]
set SourcePath [lindex $argv 3]
set TargetPath [lindex $argv 4]
set cmd_prompt "sftp>"
spawn sftp $USER@$RemoteIP
# spawn ssh $USER@$RemoteIP
expect {
"Are you sure you want to continue connecting (yes/no)?" { send "yes\r"; }
}
expect {
"Password:" {send "${PWD}\r"; }
}
expect {
"sftp>" {send "get -r ${SourcePath} ${TargetPath} \r";}
}
expect {
"sftp>" {send "exit \r"}
}
##interact ##interact可以使程序执行完后留在远端
19/04/10 更新 :
上面的代码可改写为如下高级用法:
#!/usr/bin/expect -f
## Create by Cyril.
## "Usage:./downFilesFromStation USER PWD RemoteIP SourcePath DownloadPath"
if {$argc<5} {
puts stderr "Usage:./downFilesFromStation USER PWD RemoteIP SourcePath DownloadPath"
exit 1
}
set timeout 5
set USER [lindex $argv 0]
set PWD [lindex $argv 1]
set RemoteIP [lindex $argv 2]
set SourcePath [lindex $argv 3]
set TargetPath [lindex $argv 4]
set cmd_prompt "sftp>"
spawn sftp $USER@$RemoteIP
# spawn ssh $USER@$RemoteIP
expect {
-re "(.*)(yes/no)?" { send "yes\r"; exp_continue}
-re "(.?)assword:" {send "${PWD}\r"; exp_continue}
-re "$cmd_prompt" {send "get -r ${SourcePath} ${TargetPath} \r";}
eof {
send_error "EOF...exit";
exit
} timeout 10 {
send_user "Timeout...exit";
exit
}
}
expect -re "$cmd_prompt" { send "exit\r";}
expect eof
注意:
- “-re”: 使用正则匹配条件
- exp_continue:
参阅官方帮助文档:
1>. exp_continue将会【从头开始重新匹配】【同一个expect内】的所有条件。
2>. exp_continue将会重置timeout的时间。举个例子,如果初始值为5s,当exp_continue执行完后,timeout的值仍为5s。
3>.exp_continue -continue_timer
可以阻止timeout时间重置。
4>. 慎用exp_continue,小心陷入死循环。一旦expect的所有匹配项都使用exp_continue,除非spawn项结束执行或者EOF,在这之前你的脚本会一直处于死循环状态。