運維一段時間的內網服務器,每次需要遠程傳輸文件時,就需要輸入服務器的密碼,很是麻煩,就結合expect自己寫了個腳本。
1、expect
expect是一種自動交互語言,能實現在shell腳本中為scp和ssh等自動輸入密碼自動登錄
源碼安裝參考Linux expect源碼安裝
2、expect 結合scp腳本實現實例
1 #!/bin/expect -d 2 set timeout 20 3 set file_name_expect [lindex $argv 0] 4 puts $file_name_expect 5 spawn scp $file_name_expect root@192.168.4.12:/usr/local/tmp 6 expect { 7 "yes/no" { #Are you sure you want to continue connecting (yes/no)? 8 send "yes\n" 9 expect "password" { send "123456\n" } #root@192.168.4.12's password 10 } 11 "password" { send "123456\n" } 12 13 } 14 expect eof 15 exit
第1行使用expect來解釋執行腳本(路徑根據自己安裝的路徑修改) -d 顯示調試信息
第2行設置超時時間,默認是10秒。10秒后沒有expect內容出現退出
第3行從命令行中獲取參數值並賦值
第4行輸出打印
第5行spawn是進入expect環境后才可以執行的expect內部命令,主要的功能是給ssh運行進程加個殼,用來傳遞交互指令。
第6~13行 從進程接收字符串, 根據匹配(expect)到的字符串"yes/no","password",向交互界面發送(send)信息