linux通过shell脚本实现telnet交互式自动化
原创
©著作权归作者所有:来自51CTO博客作者白灰软件测试的原创作品,请联系作者获取转载授权,否则将追究法律责任
首先需要有expect:
可以通过以下命令查看是否安装,如果未安装直接 yum install expect,如果不行请自行百度安装。
[root@localhost home]# whereis expect
expect: /usr/bin/expect /usr/share/man/man1/expect.1.gz
[root@localhost home]# expect
编写脚本如下:
#!/bin/bash
passwd="123456"
/usr/bin/expect <<-EOF
set timeout 50
spawn ssh root@10.10.22.38
expect {
"*yes/*" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect "*]*"
send "df -h\r"
EOF
解释一下:
/usr/bin/expect <<-EOF #开始用expcet执行标志
expect {} #是expect要实现交互的命令集
[root@localhost home]# ssh root@10.10.22.38
"*password:" { send "$passwd\r" } #如上如果遇到返回值 *代表无限字符,后面是password:则执行 send发送字符串 \r回车
expect "*]*" #等待出现]执行下一条命令
send "df -h\r" #执行命令并回车。
#!/bin/bash
passwd="admin"
/usr/bin/expect <<-EOF
set timeout 50
spawn telnet 0
expect {
"Login*" { send "admin\r"}
}
expect {
"*assword:" { send "$passwd\r" }
}
expect {
"*admin>" {send "security enable protocol-detect\r"}
}
expect {
"*admin>" {send "security set port-abnormal detect 2\r"}
}
expect {
"*admin>" {send "security show protocol-detect status\r"}
}
expect {
"*admin>" {send "security show port-abnormal-detect level\r"}
}
expect {
"*admin>" {send "exit\r"}
}
EOF