有些主机之前从未连过,首次连接时需要输入yes存入连接信息,而有些已经连接过的主机无需再输入yes,直接输入密码即可,针对这种情况,可用多个expect进行匹配,代码如下
expect {
"(yes/no)"
{
send "yes\r"
expect "*assword:" {send "$password\r"}
sleep 1
interact
exit
}
"assword"
{
send "$password\r"
sleep 1
interact
exit
}
}
expect多种用法参考
执行的时候要用expect connect.sh
最终代码:
#!/usr/bin/env expect -f
set host [lindex $argv 1]
set netip [lindex $argv 0]
set passwd "JSBZB@1"
if { $host > 132 && $host < 137 } {
set passwd "JSBZB@1"
}
if { $host >= 223 && $host <= 236 } {
set passwd "JSBZB@1"
}
if { $host >= 137 && $host <=139 || $host eq 35 } {
set passwd "JSBZB@2"
}
set by1 "120,121,122"
set by2 "123,124,2"
set by3 "10,180,214"
set by4 "91,86,206"
set by5 "49,64,87,155,158"
set js3 "163,151,205,202,107,108"
if {[regexp -nocase $host $js3]} {
set passwd "JSBZB@3"
}
if {[regexp -nocase $host $by1]} {
set passwd "BIANYUAN@1"
}
if {[regexp -nocase $host $by2]} {
set passwd "BIANYUAN@2"
}
if {[regexp -nocase $host $by3]} {
set passwd "BIANYUAN@3"
}
if {[regexp -nocase $host $by4]} {
set passwd "BIANYUAN@4"
}
if {[regexp -nocase $host $by5]} {
set passwd "BIANYUAN@5"
}
spawn ssh root@192.168.$netip.$host
sleep 1
expect "assword:"
send "$passwd\r"
sleep 1
interact
exit
参考代码:代码链接
#!/bin/bash
expect <<'EOF'
spawn ssh dinesh@xxx.xxx.xx.xxx "uname -a"
set count 0
expect {
timeout {puts "timeout happened"}
eof {puts "eof received"}
"password:" {send "password\r";exp_continue}
"Permission denied" {incr count;exp_continue}
}
set results $expect_out(buffer)
if {[regexp -nocase "Linux" $results]} {
puts "It is a Linux Machine"
} elseif {[regexp -nocase "Aix" $results]} {
puts "It is a AIX machine"
} else {
puts "Unknown machine"
}
EOF
bash跟expect组合
#! /bin/bash
#set host [lindex $argv 0]
read -s -p "输入连接主机最后的IP号" host
b2node="49,64,87,155,158"
if [[ $b2node =~ $host ]]
then
expect << EOF
spawn ssh root@192.168.212.$host
expect "assword"
send "BIANYUAN@5\r"
sleep 1
interact
#exit
expect eof
EOF
#注意EOF要顶格,没有空格
else
echo "不包含"
fi
问题:在连接上执行一个命令后就直接退出登录了