Basic telnetlib

telnetlib adalah salah satu modul python yang digunakan untuk melakukan telnet dengan python. pada contoh kali ini, kita coba telnet ke perangkat cisco IOS. Telnetlib sudah ada sejak python di install. testing telnetlib :

zufar@zufar:~$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import telnetlib
>>> quit()
zufar@zufar:~$

pastikan IOS dapat terhubung ke python client :

vyos@vyos:~$ configure
[edit]
vyos@vyos# set interfaces ethernet eth0 address dhcp
[edit]
vyos@vyos# set service telnet 
[edit]
vyos@vyos# commit
[ interfaces ethernet eth0 address dhcp ]
Starting DHCP client on eth0 ...

[edit]
vyos@vyos# save
Saving configuration to '/config/config.boot'...
Done
[edit]
vyos@vyos# run show interfaces
Codes: S - State, L - Link, u - Up, D - Down, A - Admin Down
Interface        IP Address                        S/L  Description
---------        ----------                        ---  -----------
eth0             192.168.122.250/24                u/u  
lo               127.0.0.1/8                       u/u  
                 ::1/128
[edit]
vyos@vyos# ping 192.168.122.1 -c 3
PING 192.168.122.1 (192.168.122.1) 56(84) bytes of data.
64 bytes from 192.168.122.1: icmp_req=1 ttl=64 time=0.484 ms
64 bytes from 192.168.122.1: icmp_req=2 ttl=64 time=0.533 ms
64 bytes from 192.168.122.1: icmp_req=3 ttl=64 time=0.487 ms

--- 192.168.122.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 0.484/0.501/0.533/0.028 ms

pada python client, buat file python

import telnetlib
import time

host = '192.168.122.250'
user = 'vyos'
passwd = 'vyos'

# open connection
connect = telnetlib.Telnet(host=host,port=23)

# find prompt login?
connect.read_until('login: ')

# enter username
connect.write(user+'\n')

# find prompt password?
connect.read_until('Password: ')

# enter password
connect.write(passwd+'\n')

# find prompt $?
connect.read_until('$ ')

# show interfaces
connect.write('show interfaces\n')

# read output
time.sleep(1)
output =  connect.read_very_eager()
print output

# close connection
connect.close()

lalu coba jalankan

zufar@zufar:~/Documents/Technology/Programming/Python/telnetlib$ python lab1.py
show interfaces
Codes: S - State, L - Link, u - Up, D - Down, A - Admin Down
Interface        IP Address                        S/L  Description
---------        ----------                        ---  -----------
eth0             192.168.122.250/24                u/u
lo               127.0.0.1/8                       u/u
                 ::1/128
vyos@vyos:~$
zufar@zufar:~/Documents/Technology/Programming/Python/telnetlib$

Comments are closed.