2.第二个脚本:通过中转机上传下载文件(在只能通过中转机才能登陆远程机的情况下)
上传命令如下:expect ~/bin/ex.sh Desktop/MozillaFirefox.desktop wls81@localhost:/tmp/
下载命令如下:expect ~/bin/ex.sh wls81@localhost:/home/wls81/test/a Desktop/
#!/usr/bin/expect -f set a [lindex $argv 0] set b [lindex $argv 1] set localdir /home/mfleat/ set localhost mfleat@localhost set transdir ~/lifa803/ set tempdir /tmp/ proc send_passwd {passwd } { #发送密码的函数 expect { *yes/no* {send "yes\r";exp_continue} *assword:* {send "$passwd\r"} } } proc exec_result {} { #返回执行结果的函数 send "echo \$?\r" expect -re "\n(.*)\r" return $expect_out(1,string) } proc get_filename {path} { #获得path中的文件名的函数 set filearray [split $path "/"] set countall [llength $filearray];set countall [expr $countall - 1 ] set filename [lrange $filearray $countall $countall] return $filename } #up or down 判断是上传还是下载 if { [string match *Desktop* $a] } { #通过本地Desktop位置 来判断是上传还是下载 set upfile ${localdir}$a set destlist [split $b :] set desthost [lrange $destlist 0 0] set destdir [lrange $destlist 1 1] set filename [ get_filename $upfile] } else { set downfile $a set filename [ get_filename $downfile] set dest ${localhost}:${localdir}$b } # if is up file if { [info exists upfile] } { spawn ssh public@localhost send_passwd "x" expect *public@* send "scp ${localhost}:${upfile} ${transdir}\r" send_passwd "6" expect *public@* set result [exec_result] if { $result == "0" } { send "scp ${transdir}${filename} ${desthost}:${tempdir}\r" } send_passwd "x" expect *public@* set result [exec_result] if { $result == "0" } { send "ssh wls81@localhost\r" send_passwd "x" expect *wls81@* send "ls -l ${tempdir}/$filename \r " #发送一些执行结果 } interact } #if is download file if { [info exists downfile] } { spawn ssh public@localhost send_passwd "x" expect *public@* send "scp $downfile ${transdir}\r" send_passwd "x" expect *public@* set result [exec_result] if { $result == "0" } { send "scp ${transdir}${filename} ${dest}\r" send_passwd "9" expect *public@* set result [exec_result] if { $result == "0" } { send "echo Good\r" } } }
解释:
上传原理是通过中转机在本地拉数据,然后向远程机推数据。(特别适合不知道中转机的密码的情况)
下载原理同上传,比上传简单
其中 上传不会直接覆盖原文件,只是上传到远程机的一个tempdir (因为有时候原文件可能没权限覆盖)