linux通过shell脚本实现telnet交互式自动化
首先需要有expect:
可以通过以下命令查看是否安装,如果未安装直接 yum install expect,如果不行请自行百度安装。
[root@localhost home]# whereis expect expect: /usr/bin/expect /usr/share/man/man1/expect.1.gz [root@localhost home]# expect expect1.1>
编写脚本如下:
#!/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执行标志
EOF #结束标志
expect {} #是expect要实现交互的命令集
[root@localhost home]# ssh root@10.10.22.38 root@10.10.22.38's password:
"*yes/*"
"*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 "secur enable protocol-detect\r"} } expect { "*admin>" {send "secur set port-abnormal detect 2\r"} } expect { "*admin>" {send "secur show protocol-detect status\r"} } expect { "*admin>" {send "secur show port-abnormal-detect level\r"} } expect { "*admin>" {send "exit\r"} } EOF
python实现
#!/usr/bin/python import telnetlib host = ''10.32.17.10'' user = ''root'' password = ''123456'' commands = [''en'',password,''conf t'',''int fa0/1'',''switchport mode multi'',''end''] tn = telnetlib.Telnet(host) tn.read_until("Username:") tn.write(user + "n") tn.read_until("Password:") tn.write(password + "n") for command in commands: tn.write(command+''n'') tn.write("exitn") print tn.read_all() print ''Finish!''

浙公网安备 33010602011771号