Код:
#!/usr/bin/python
import telnetlib
import re
HOST = "172.16.0.17"
user = 'user'
password = 'sdsdsd'
tn = telnetlib.Telnet(HOST)
tn.read_until("BCM96338 ADSL Router")
tn.read_until("Login:")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ifconfig ppp_0_1_32_1\n")
tn.write("logout\n")
str = tn.read_all()
pattern = re.compile (".*inet addr:([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*");
ip = pattern.findall(str)
print str
print ip[0]
Все работает, но иногда глючить. Результаты:
1. ОК
2. Висит пока не пошлешь Ctrl+C
3. Что-то не то
Код:
#1-------------------------------------------------------------
vovan@it:~/scripts/python$ ./telnet.py
> ifconfig ppp_0_1_32_1
ppp_0_1_32_1 Link encap:Point-Point Protocol
inet addr:91.124.30.30 P-t-P:195.5.5.206
Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1370 Metric:1
RX packets:365390 errors:0 dropped:0 overruns:0 frame:0
TX packets:251691 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:3
RX bytes:466480711 (444.8 MiB) TX bytes:15954770 (15.2 MiB)
> logout
Bye bye. Have a nice day!!!
91.124.30.30
#2-------------------------------------------------------------
vovan@it:~/scripts/python$ ./telnet.py
Traceback (most recent call last):
File "./telnet.py", line 20, in <module>
str = tn.read_all()
File "/usr/lib/python2.5/telnetlib.py", line 337, in read_all
self.fill_rawq()
File "/usr/lib/python2.5/telnetlib.py", line 528, in fill_rawq
buf = self.sock.recv(50)
KeyboardInterrupt
#3-------------------------------------------------------------
vovan@it:~/scripts/python$ ./telnet.py
sdsdsd
ifconfig ppp_0_1_32_1
logout
Traceback (most recent call last):
File "./telnet.py", line 24, in <module>
print ip[0]
IndexError: list index out of range
Вероятно я что-то упускаю?