-

   rss_rss_hh_new

 - e-mail

 

 -

 LiveInternet.ru:
: 17.03.2011
:
:
: 51

:


[ ] Python

, 18 2017 . 15:11 +
.

? .
.
, - ?
.

. . , .

,
, cisco : TCL IOS Python NX-OS IOS-XR . network automation network programmability, Cisco .

Cisco : Juniper c PyEZ, HP, Huawei .

Netconf, Restconf, Ansible, Puppet Python, Python, Python. , .

, , : DNS?.
, , Python SNMP. traceroute.

, , MPLS-TE, , ICMP traceroute ping . traceroute IP , . , , , ? , DNS. , unnumbered, , DNS, , ICMP .

DNS . , description , hostname . . .

.

, , , , , , .

, , . SNMP. , , .

,


Python.
sudo apt-get install python3

SNMP, IP , . pip.
sudo apt install python-pip

.
pip install pysnmp

pip install datetime

pip install ipaddress

hostname. SNMP OID. OID , OID. hostname 1.3.6.1.2.1.1.5.0.

, hostname.

# import section
from pysnmp.hlapi import *
from ipaddress import *
from datetime import datetime

# var section

#snmp
community_string = 'derfnutfo'  # From file
ip_address_host = '192.168.88.1'  # From file
port_snmp = 161
OID_sysName = '1.3.6.1.2.1.1.5.0'  # From SNMPv2-MIB hostname/sysname

# function section

def snmp_getcmd(community, ip, port, OID):
    return (getCmd(SnmpEngine(),
                   CommunityData(community),
                   UdpTransportTarget((ip, port)),
                   ContextData(),
                   ObjectType(ObjectIdentity(OID))))

def snmp_get_next(community, ip, port, OID):
    errorIndication, errorStatus, errorIndex, varBinds = next(snmp_getcmd(community, ip, port, OID))
    for name, val in varBinds:

        return (val.prettyPrint())

#code section

sysname = (snmp_get_next(community_string, ip_address_host, port_snmp, OID_sysName))
print('hostname= ' + sysname)

:
hostname= MikroTik

:

:

1. pysnmp SNMP

2. ipaddress . , .

3. datetime- . .

:

1. community
2.
3. SNMP
4. OID

:

1. snmp_getcmd
2. snmp_get_next

GET , , comminity OID.
snmp_getcmd. , :)

:

1. ip . , . , pysnmp traceback. , , , , , . , , .

2. , , pysnmp , traceback. SNMP.

3. , .


.
check_ip .
get_from_file , , .
.

filename_of_ip = 'ip.txt' #    Ip 
#log
filename_log = 'zone_gen.log' #   

def check_ip(ip): #  ip  
    try:
        ip_address(ip)
    except ValueError:
        return False
    else:
        return True

def get_from_file(file, filelog): #  ip   .   -     
    fd = open(file,'r')
    list_ip = []
    for line in fd:
       line=line.rstrip('\n')
       if check_ip(line):
           list_ip.append(line)
       else:
            filed.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ': Error    ip  ' + line)
            print('Error    ip  ' + line)
    fd.close()
    return list_ip

#code section

#  
filed = open(filename_log,'w')

#   
filed.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + '\n')

ip_from_file = get_from_file(filename_of_ip, filed)

for ip_address_host in ip_from_file:
    sysname = (snmp_get_next(community_string, ip_address_host, port_snmp, OID_sysName))
    print('hostname= ' + sysname)

filed.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + '\n')
filed.close()

ip.txt
192.168.88.1
172.1.1.1
12.43.dsds.f4
192.168.88.1

snmp. SNMP.
Error ip 12.43.dsds.f4
hostname= MikroTik
Traceback (most recent call last):
File "/snmp/snmp_read3.py", line 77, in print('hostname= ' + sysname)
TypeError: Can't convert 'NoneType' object to str implicitly

Process finished with exit code 1

traceback , . .

pysnmp


snmp_get_next errorIndication, errorStatus, errorIndex, varBinds. varBinds , , error, . . snmp, .

def errors(errorIndication, errorStatus, errorIndex, ip, file):
    #      False    
    if errorIndication:
        print(errorIndication, 'ip address ', ip)
        file.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + str(errorIndication) + ' = ip address = ' + ip + '\n')
        return False
    elif errorStatus:
        print(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        file.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?' + '\n'))
        return False
    else:
        return True

snmp_get_next . , , .


def snmp_get_next(community, ip, port, OID, file):
    errorIndication, errorStatus, errorIndex, varBinds = next(snmp_getcmd(community, ip, port, OID))
    if errors(errorIndication, errorStatus, errorIndex, ip, file):
        for name, val in varBinds:
            return (val.prettyPrint(), True)
    else:
        file.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : Error snmp_get_next ip = ' + ip + ' OID = ' + OID + '\n')
        return ('Error', False)

code section, , . , :

1. Sysname , . , .

2. , Huawei Catos hostname. OID ( , , ), domain .

3. , comminity , , - , .

4. , .

for ip_address_host in ip_from_file:
    #   sysname hostname+domainname,     
    sysname, flag_snmp_get = (snmp_get_next(community_string, ip_address_host, port_snmp, OID_sysName, filed))

    if flag_snmp_get:
        #  ,    snmp
        if sysname == 'No Such Object currently exists at this OID':
            #   community .  ,   traceback.     ,    community,     hostname,        
            print('ERROR community', sysname, ' ', ip_address_host)
            filed.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + 'ERROR community sysname = ' + sysname + '  ip = ' + ip_address_host + '\n')
        else:
            if log_level == 'debug':
                filed.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + '  sysname ' + sysname + ' type ' + str(type(sysname)) + ' len ' + str(len(sysname)) + ' ip ' + ip_address_host + '\n')
            if len(sysname) < 3
                if log_level == 'debug' or log_level == 'normal':
                    filed.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + 'Error sysname  3  = ' + sysname + '  ip = ' + ip_address_host + '\n')
            if sysname.find(domain) == -1:
                # -  hostname  ,  Huawei  Catos
                sysname = sysname + '.' + domain
                  if log_level == 'debug' or log_level == 'normal':
                    filed.write("check domain     : " + sysname + " " + ip_address_host + " " + "\n")

        print('hostname= ' + sysname)

ip.txt
Error ip 12.43.dsds.f4
hostname= MikroTik.mydomain.ru
No SNMP response received before timeout ip address 172.1.1.1
hostname= MikroTik.mydomain.ru

, , . hostname c , snmp.

.


# import section
from pysnmp.hlapi import *
from ipaddress import *
from datetime import datetime

# var section

#snmp
community_string = 'derfnutfo'  
ip_address_host = '192.168.88.1'  
port_snmp = 161
OID_sysName = '1.3.6.1.2.1.1.5.0'  # From SNMPv2-MIB hostname/sysname
filename_of_ip = 'ip.txt' #    Ip 
#log
filename_log = 'zone_gen.log'  #   
log_level = 'debug'

domain='mydomain.ru'

# function section

def snmp_getcmd(community, ip, port, OID):
# type class 'generator' errorIndication, errorStatus, errorIndex, result[3] - 
#  get       SNMP   OID
    return (getCmd(SnmpEngine(),
                   CommunityData(community),
                   UdpTransportTarget((ip, port)),
                   ContextData(),
                   ObjectType(ObjectIdentity(OID))))

def snmp_get_next(community, ip, port, OID, file):
#   class generator  def snmp_get
#  errors,   class 'pysnmp.smi.rfc1902.ObjectType'  OID ( name)    ( val)
#    
    errorIndication, errorStatus, errorIndex, varBinds = next(snmp_getcmd(community, ip, port, OID))

    if errors(errorIndication, errorStatus, errorIndex, ip, file):
        for name, val in varBinds:
            return (val.prettyPrint(), True)
    else:
        file.write(datetime.strftime(datetime.now(),
                                     "%Y.%m.%d %H:%M:%S") + ' : Error snmp_get_next ip = ' + ip + ' OID = ' + OID + '\n')
        return ('Error', False)

def get_from_file(file, filelog):  
# ip    file,    filelog     
     fd = open(file, 'r')
     list_ip = []
     for line in fd:
         line=line.rstrip('\n')
         if check_ip(line):
            list_ip.append(line)
         else:
            filed.write(datetime.strftime(datetime.now(),
                                              "%Y.%m.%d %H:%M:%S") + ': Error    ip  ' + line)
            print('Error    ip  ' + line)
     fd.close()

     return list_ip

def check_ip(ip): 
#   ip   . False   .
    try:
       ip_address(ip)
    except ValueError:
        return False
    else:
        return True

def errors(errorIndication, errorStatus, errorIndex, ip, file):
    #        False     file
    if errorIndication:
       print(errorIndication, 'ip address ', ip)
       file.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + str(
                errorIndication) + ' = ip address = ' + ip + '\n')
       return False
    elif errorStatus:
         print(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + '%s at %s' % (
         errorStatus.prettyPrint(),
         errorIndex and varBinds[int(errorIndex) - 1][0] or '?' ))
         file.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + ' : ' + '%s at %s' % (
         errorStatus.prettyPrint(),
         errorIndex and varBinds[int(errorIndex) - 1][0] or '?' + '\n'))
         return False
    else:
         return True

#code section

#  
filed = open(filename_log,'w')

#   
filed.write(datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S") + '\n')

ip_from_file = get_from_file(filename_of_ip, filed)

for ip_address_host in ip_from_file:
    #  sysname hostname+domainname,  
    sysname, flag_snmp_get = (snmp_get_next(community_string, ip_address_host, port_snmp, OID_sysName, filed))

    if flag_snmp_get:
        #  ,    snmp
        if sysname == 'No Such Object currently exists at this OID':
             #  community .  ,   traceback.     ,    community,     hostname,    
            print('ERROR community', sysname, ' ', ip_address_host)
            filed.write(datetime.strftime(datetime.now(),
                                          "%Y.%m.%d %H:%M:%S") + ' : ' + 'ERROR community sysname = ' + sysname + '  ip = ' + ip_address_host + '\n')
        else:

            if log_level == 'debug':
                filed.write(datetime.strftime(datetime.now(),
                                              "%Y.%m.%d %H:%M:%S") + ' : ' + '  sysname ' + sysname + ' type ' + str(
                    type(sysname)) + ' len ' + str(len(sysname)) + ' ip ' + ip_address_host + '\n')
            if len(sysname) < 3:
                sysname = 'None_sysname'
                if log_level == 'debug' or log_level == 'normal':
                    filed.write(datetime.strftime(datetime.now(),
                                                  "%Y.%m.%d %H:%M:%S") + ' : ' + 'Error sysname  3  = ' + sysname + '  ip = ' + ip_address_host + '\n')
            if sysname.find(domain) == -1:
                # -  hostname  ,  Huawei  Catos
                sysname = sysname + '.' + domain
                if log_level == 'debug' or log_level == 'normal':
                    filed.write("check domain     : " + sysname + " " + ip_address_host + " " + "\n")

        print('hostname= ' + sysname)

filed.close()

, description , bind. .

P.S.: , - - .
: _ _ _. .
Original source: habrahabr.ru (comments, light).

https://habrahabr.ru/post/333614/

:  

: [1] []
 

:
: 

: ( )

:

  URL