接着寫一個稍微複雜點的腳本,分發文件到指定服務器腳本。
首先我們要知道遠程分發文件的命令格式
scp 源文件 驗證用戶@遠程主機:遠程目錄 [root@130 ~]# scp auto_yes.exp [email protected]:/tmp/
需求就是通過腳本來實現發送,不需要輸入密碼,也就是驗證用戶是固定的還有密碼是固定的,其他的主機IP和目的路徑是不固定的,我們通過設置爲位置變量來實現自定義化。最終實現的效果:
[root@DECMDB01 ~]# expect batch_file.exp 172.18.0.20 yezi.txt /tmp/ spawn scp yezi.txt [email protected]:/tmp/ yezi.txt 100% 343 0.3KB/s 00:00
全程不需要輸入密碼,而只需要指定主機IP和發送的文件已經發送到目的主機的目的路徑,其他的密碼和驗證用戶都已經在腳本中設置好了
看一下腳本:
#!/usr/bin/expect if { $argc != 3 } { puts "Please use: 'expect $argv0 ip source_file d_path'" exit } set ip [lindex $argv 0] set sfile [lindex $argv 1] set dpath [lindex $argv 2] set password "rxadmin123" # spawn scp $sfile root@$ip:$dpath expect { "*yes/no" {exp_send "yes\n";exp_continue} "*password" {exp_send "$password\n"} } expect eof
標記分析一下:
#!/usr/bin/expect if { $argc != 3 } { ##先做一個判斷,如果位置變量不是3個則提示"Please...d_path",這裏的argc和Shell裏的$#是一樣的 puts "Please use: 'expect $argv0 ip source_file d_path'" ##puts後面提示內容,用""標記 exit ##退出判斷 } set ip [lindex $argv 0] ##設置ip變量,這裏的argv 0等於Shell裏的$1 set sfile [lindex $argv 1] ##設置sfile變量,這裏的argv 1等於Shell裏的$2 set dpath [lindex $argv 2] ##設置dpath變量,這裏的argv 1等於Shell裏的$3 set password "123456" ##設置密碼123456爲$password # spawn scp $sfile root@$ip:$dpath expect { "*yes/no" {exp_send "yes\n";exp_continue} ##這裏的exp_send和send類似 "*password" {exp_send "$password\n"} } expect eof ##結束腳本
!!! 需要注意的是裏面的每個符號都爲英文符號,{}和""以及;的用法都是固定格式,請牢記,建議腳本複製後故意刪除符號進行測試符號的作用