利用expect + sftp 实现远程主机自动登录及下载

6 篇文章 0 订阅

利用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

注意:

  1. “-re”: 使用正则匹配条件
  2. 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,在这之前你的脚本会一直处于死循环状态。
    exp_continue
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值