My First Python Script

- python

The truth is, I don’t write it from scratch. Just copy paste from some sources, and tweaked it a little bit. But the result is good.

Here you go.

import telnetlib
import time
import socket

#devices.txt contains an IP address on each line
with open('mydevices.txt','r') as f:
    ips = f.read().splitlines()

#print(ips)
#alternatively we can use a list
#ips=['10.1.1.10','10.1.1.20','10.1.1.30']


user = 'user1'
password = 'pass1'

#iterate through the list of devices and execute the same commands
for ip in ips:
    try:
        tn = telnetlib.Telnet(ip, timeout=7)

        tn.read_until(b'Username: ', timeout=7)
        tn.write(user.encode('ascii') + b'\n')

        if password:
            tn.read_until(b'Password: ', timeout=7)
            tn.write(password.encode('ascii') + b'\n')

        tn.write(b'enable\n')
        tn.write(b'ena1\n')
        # create snmp
        tn.write(b'configure terminal\n')
        tn.write(b'snmp-server community mySNMP ro\n')
        tn.write(b'end\n')
        # tn.write(b'terminal length 0\n')
        tn.write(b'sh run | i snmp\n')
        tn.write(b'exit\n')
        # exit command is mandatory to be able read using read_all()
        # result = tn.read_all().decode()
        line = tn.read_all().decode('ascii')
        print(line)
        tn.close()
    except:
        print((ip)+", timeout")
        pass

Beberapa hal yang perlu diketahui adalah:

192.168.255.11
1.1.1.1
192.168.255.10

Semoga bermanfaat.