檔案名稱:ssh_auto_login
複製代碼 代碼如下:
#!/usr/bin/expect
##
# ssh類比登陸器
#
# @author zhiyuan <hzyhouzhiyuan艾特gmail.com>
##
if {$argc<4} {
puts "Error params: $argv"
puts "Expect params :user passwd ip port [translate_id]"
exit 1
}
set default_passcode "這裡填通道機的預設密碼"
set user [lindex $argv 0]
set password [lindex $argv 1]
set ip [lindex $argv 2]
set port [lindex $argv 3]
set timeout 10
while 1 {
spawn ssh -p $port $user@$ip
#如果最後的字元匹配則執行命令\r結尾表示確定
expect {
"*yes/no" { send "yes\r";exp_continue}
"*password:" { send "$password\r" }
}
#這裡是需要通過通道機登陸時的匹配流程,根據需要自行修改。
expect {
"*PASSCODE:" {
send_user "請輸入通道機動態密碼:";
expect_user -re "(.*)\n"
set random_passcode $expect_out(1,string)
send "$default_passcode$random_passcode\r"
expect {
"Access Denied" { continue }
"Enter:" { send "1\r" }
}
set translate_ip [lindex $argv 4]
if { $translate_ip != "" } {
expect "*):" { send "$translate_ip\r" }
}
}
#"Last login:*" { }
}
break
}
#無法匹配$,還不知道怎麼解決
#expect -re "*\$" { puts "test123"; send "source /etc/profile\r" }
#expect "*\$" { send "cd ~\r" }
send_user "login success!"
interact
上邊是ssh的自動登入,可以配合下邊的shell使用,很方便。
檔案名稱:xxx_launcher
複製代碼 代碼如下:
#!/bin/sh
##
# 伺服器登陸器
#
# @author zhiyuan <hzyhouzhiyuan@gmail.com>
##
channel_user="user_namexxx"
channel_passwd="xxxx"
#內網通道機
internal_ip1=xxx.xxx.xxx.xxx
#聯通
unicom_ip1=xxx.xxx.xxx.xxx
#電信
telecom_ip1=xxx.xxx.xxx.xxx
case "$1" in
ci)
expect ssh_auto_login $channel_user $channel_passwd $internal_ip3 22
cl)
expect ssh_auto_login $channel_user $channel_passwd $unicom_ip1 22
cd)
expect ssh_auto_login $channel_user $channel_passwd $telecom_ip1 22
149)
expect ssh_auto_login channel_user channel_passwd xxx.xx.xxx.xxx 22
49)
expect ssh_auto_login $channel_user $channel_passwd $unicom_ip1 22 需要通道機跳轉的ipxxx.xxx.xx
*)
echo "協助資訊:"
echo "\tthere is not a server named [$1]"
echo "\t伺服器149:\t149"
echo "\t伺服器49:\t49"
esac
此時登陸某個伺服器的時候就直接 用上述shell帶要登入的伺服器參數即可,如: ./xxx_launcher 49