天天看點

linux expect, spawn自動登入

今天寫一個腳本,需要與終端輸出互動,學習着使用了簡單的spawn與expect,感覺很友善,記錄一下。

1. 首先要保證linux server上安裝了expect,我自己的伺服器跑的是suse 10.2,比較老的版本,預設沒有安裝expect,下了個rpm包裝上先。(現在外面跑得suse enterprise基本都是11或者12的,看來要趕緊更新了,不然下個rpm包很多都沒有對應的版本)安裝了之後,/usr/bin/目錄下有expect可執行檔案。

2. 關于expect,先說明一下,隻有spawn的内容才能expect捕獲到,expect的内容包括了:終端的輸出,eof和逾時。

3. 根據個簡單的登入腳本說明下:

#!/usr/bin/expect--> 1
set timeout 30--> 2
spawn ssh [email protected] -p 22--> 3
#expect {
#       "(yes/no)?" {send "yes\r"}
#}
expect {
"Password:" {send "****\r"}--> 4
}
expect {
"#" {send "cd /home/software\r"}--> 5
}
interact-->6      

其中: 

1)#!/usr/bin/expect,不再是#!/bin/sh了

2) set timeout 30,首先設定一個逾時時間;

3) spawn一個ssh登入程序;

4) 當終端輸出“Password”時輸入密碼;

5) 登入之後,輸入一個路徑;