Advertisement
Guest User

Untitled

a guest
Aug 7th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.42 KB | None | 0 0
  1. #!/usr/bin/python
  2. import logging
  3. import socket
  4. import ipaddress
  5. import sys
  6. import subprocess
  7. import pexpect
  8. import os
  9. import errno
  10. import getpass
  11. import csv
  12.  
  13. class mainCode():
  14.  
  15.     #Logging Params
  16.     logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename='logfiles/logall.log', level=logging.DEBUG)
  17.     logging.debug('Logging started')
  18.  
  19.     #Define Variables
  20.     loginUser = 'Telarus'
  21.     loginPassword = 'Mhmlw!69'
  22.     ldapUser = 'james.ditrapani'
  23.     debugOut = False
  24.     logging.info('Variables Declared..')
  25.  
  26.     def getLDAP(self):
  27.         ldapPassword = getpass.getpass('Please enter LDAP Password: ')
  28.         self.pcode2IP(ldapPassword)
  29.  
  30.     def pcode2IP(self, ldapPassword):
  31.         while True:
  32.             print('\n1. Yes')
  33.             print('2. No\n')
  34.             userSelect = int(raw_input("Do you need to convert pcodes to IP's?: "))
  35.             if userSelect == 1:
  36.                 with open('pcodes.txt') as pcodes:
  37.                     if self.debugOut == True:
  38.                         try:
  39.                             print('\n###########################')
  40.                             print('### REMOVING IP LISTS!! ###')
  41.                             print('###########################\n')
  42.                             os.remove('telarusiplist.txt') #Debug only!
  43.                             os.remove('otwiplist.txt') #Debug only!
  44.                         except OSError:
  45.                             print('OSError: Files do not exist! Moving on..')
  46.                     for line in pcodes:
  47.                         try:
  48.                             removeclient_id = line.split(',')
  49.                             print(removeclient_id)
  50.                             productCode = removeclient_id[0]
  51.                             client_id1 = removeclient_id[1]
  52.                             client_id = client_id1.strip('\n')
  53.                             resolvedIP = socket.gethostbyname(productCode.strip())
  54.                             line1 = productCode.strip('\n')
  55.                             resolvedIP1 = resolvedIP.strip('\n')
  56.                             logging.info('Resolved {0} to {1}!'.format(line1, resolvedIP1))
  57.                             print('Resolved {0} to {1}!'.format(line1, resolvedIP1))
  58.                             if ipaddress.ip_address(u'{0}'.format(resolvedIP1)) in ipaddress.ip_network(u'10.0.0.0/8'):
  59.                                 os.system("echo '{0},{1}' >> otwiplist.txt".format(resolvedIP1, client_id))
  60.                                 logging.debug('Adding {0} to OTW IP List..'.format(resolvedIP1))
  61.                                 #self.checkAlive(ldapPassword)
  62.                             else:
  63.                                 os.system("echo '{0}' >> telarusiplist.txt".format(resolvedIP1))
  64.                                 logging.debug('Adding {0} to Telarus IP List..'.format(resolvedIP1))
  65.                         except socket.gaierror:
  66.                             print('Failed to resolve {0}'.format(line1))
  67.                             logging.info('Failed to resolve {0}'.format(line1))
  68.                             logging.info('Device selected: {0} - {1}'.format(line1, resolvedIP1))
  69.            
  70.             elif userSelect == 2:
  71.                 print('Please select 1')
  72.  
  73.             else:
  74.                 print('\n{0} is an invalid input!\n'.format(userSelect))
  75.  
  76.             self.checkAlive(ldapPassword, resolvedIP1, line1)
  77.  
  78.     def checkAlive(self, ldapPassword, resolvedIP1, line1):
  79.         with open('otwiplist.txt') as ipList:
  80.             for line in ipList:
  81.                 removeclientIDNEWLINE = line.rstrip('\n')
  82.                 print('removeclientIDNEWLINE: {0}'.format(removeclientIDNEWLINE))
  83.                 removeclientID = removeclientIDNEWLINE.split(',')
  84.                 print('removeclientID: {0}'.format(removeclientID))
  85.                 currentDevice = removeclientID[0]
  86.                 client_id = currentDevice[1]
  87.                 print(currentDevice, client_id)
  88.                 logging.info('Checking if {0} is online..'.format(currentDevice))
  89.                 check = os.system('ping -c 1 {0}'.format(currentDevice))
  90.                 if check == 0:
  91.                     logging.info('{0} responded successfully!'.format(currentDevice))
  92.                     os.system("echo 'Device: {0} is online... proceeding to configure' >> logfiles/logfile.txt".format(currentDevice))
  93.                     print('Device: {0} is online... proceeding to configure'.format(currentDevice))
  94.                     self.connectDevice(currentDevice, ldapPassword, client_id, resolvedIP1, line1)
  95.                 else:
  96.                     logging.info('{0} has failed to respond! Marking as offline..'.format(currentDevice))
  97.                     os.system('echo {0} >> logfiles/offlinedevice.txt'.format(currentDevice))
  98.                     os.system("echo 'Device: {0} is offline! Ending.' >> logfiles/logfile.txt".format(currentDevice))
  99.                     pass
  100.             print('\n')
  101.             exit()
  102.  
  103.     def connectDevice(self, currentDevice, ldapPassword, client_id, resolvedIP1, line1):
  104.         sc = pexpect.spawn('telnet {0}'.format(currentDevice))
  105.         sc.logfile_read = sys.stdout
  106.         eofError = 'pexpect.EOF, timeout=None'
  107.         connectionClosed = sc.expect([eofError, 'Username:'])
  108.         if connectionClosed == 0:
  109.             logging.info('### {0} has closed the connection, needs investigation! ###'.format(currentDevice))
  110.             pass
  111.         else:
  112.             sc.sendline(self.loginUser)
  113.             sc.expect('Password:')
  114.             sc.sendline(self.loginPassword)
  115.         checkError = sc.expect(['Error: Authentication failed.', 'Request Denied', '>'])
  116.         if checkError == 0:
  117.             logging.info('{0} has failed with default credentials! Checking LDAP...'.format(currentDevice))
  118.             sc.expect('Username:')
  119.             sc.sendline(self.ldapUser)
  120.             sc.expect('Password:')
  121.             sc.sendline(ldapPassword)
  122.             sc.expect('>')
  123.             self.configHuawei(currentDevice, sc, client_id, resolvedIP1, line1)
  124.             pass
  125.         if checkError == 1:
  126.             logging.info('{0} has been detected as a Cisco! Sending LDAP....'.format(currentDevice))
  127.             sc.expect('Username:')
  128.             sc.sendline(self.ldapUser)
  129.             sc.expect('Password:')
  130.             sc.sendline(ldapPassword)
  131.             self.configCisco(currentDevice, sc, client_id, resolvedIP1, line1)
  132.         else:
  133.             logging.info('Succesfully connected to {0} with default credentials'.format(currentDevice))
  134.             self.configHuawei(currentDevice, sc, client_id, resolvedIP1, line1)
  135.             pass
  136.  
  137.  
  138.     def configHuawei(self, currentDevice, sc, client_id, resolvedIP1, line1):
  139.         model_type = 'Huawei'
  140.         sc.sendline('system-view')
  141.         sc.expect(']')
  142.         self.exporttoCSV(model_type, client_id, resolvedIP1, line1, currentDevice)
  143.  
  144.     def configCisco(self, currentDevice, sc, client_id, resolvedIP1, line1):
  145.         model_type = 'Cisco ' #Will need to screenscrape to get the model
  146.         sc.expect('\#')
  147.         sc.sendline('conf t')
  148.         sc.expect('\)')
  149.         self.exporttoCSV(model_type, client_id, resolvedIP1, line1, currentDevice)
  150.  
  151.     def exporttoCSV(self, model_type, client_id, line1, resolvedIP1, currentDevice):
  152.         site_id = line1
  153.         carriage_id = 'carriageID'
  154.         management_ip = currentDevice
  155.         snmp_ro = 'snmpread'
  156.         snmp_rw = 'snmpwrite'
  157.         serial_number = 'serialnumber'
  158.         mac_address = 'macaddress'
  159.         asset_number = 'assettag'
  160.  
  161.         with open('cpeimport.csv', 'a') as cpefile:
  162.             csvData = [client_id, site_id, carriage_id, management_ip, self.loginUser, self.loginPassword, snmp_ro, snmp_rw, serial_number, model_type, mac_address, asset_number]
  163.             writecpe = csv.writer(cpefile, dialect='excel')
  164.             writecpe.writerow(csvData)
  165.  
  166. code = mainCode()
  167. code.getLDAP()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement