標籤:
現場服務器較多,密碼3個月到期,在到期時需更改密碼。
使用expect編寫,嘗試登陸2次後退出(防止密碼錯誤時帳號鎖定),逾時重試一次。
shell指令碼調用並定時執行,登陸成功後執行一條命令,如:hostname、uname等,根據退出狀態判斷密碼是否到期。
0--正常
1--傳入參數錯誤
2--timeout
3--密碼錯誤或到期
指令碼如下:
#!/usr/bin/expect################################################################ 串連遠程主機proc do_login {passwd} { set timeout 30 set done 1 set timeout_case 0 set ps1 {PS1="doraemon#";export PS1} while {$done<3} { expect { *assword* { send $passwd\r incr done } \[$%>#] { set done 5 send $ps1\r\r break } timeout { set done 1 switch -- $timeout_case { 1 { send_user "try again ...\n" } 2 { exit 2 expect eof } } incr timeout_case } } } if {$done==3} { exit 3 expect eof }}################################################################ 執行命令proc exec_cmd {cmd} { expect -re "doraemon#$" send_user "\$cmd: $cmd\n" send $cmd\r}################################################################ 退出proc logout {} { expect -re "doraemon#$" send exit\r expect eof}###############################################################if {$argc < 4} { send_user "Usage:$argv0 user pass ip command\n" exit 1}set user [lindex $argv 0]set pass [lindex $argv 1]set ip [lindex $argv 2]set num 3spawn ssh -o StrictHostKeyChecking=no -l $user $ip do_login $passwhile {$num<$argc} { set proc [lindex $argv $num] # 捕獲輸出用 set cmd "echo ==$ip==$user==`$proc`==" exec_cmd $cmd incr num} logout
Shell登陸遠程伺服器