Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import logging
- import socket
- import ipaddress
- import sys
- import subprocess
- import pexpect
- import os
- import errno
- import getpass
- import csv
- class mainCode():
- #Logging Params
- logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename='logfiles/logall.log', level=logging.DEBUG)
- logging.debug('Logging started')
- #Define Variables
- loginUser = 'Telarus'
- loginPassword = 'Mhmlw!69'
- ldapUser = 'james.ditrapani'
- debugOut = False
- logging.info('Variables Declared..')
- def getLDAP(self):
- ldapPassword = getpass.getpass('Please enter LDAP Password: ')
- self.pcode2IP(ldapPassword)
- def pcode2IP(self, ldapPassword):
- while True:
- print('\n1. Yes')
- print('2. No\n')
- userSelect = int(raw_input("Do you need to convert pcodes to IP's?: "))
- if userSelect == 1:
- with open('pcodes.txt') as pcodes:
- if self.debugOut == True:
- try:
- print('\n###########################')
- print('### REMOVING IP LISTS!! ###')
- print('###########################\n')
- os.remove('telarusiplist.txt') #Debug only!
- os.remove('otwiplist.txt') #Debug only!
- except OSError:
- print('OSError: Files do not exist! Moving on..')
- for line in pcodes:
- try:
- removeclient_id = line.split(',')
- print(removeclient_id)
- productCode = removeclient_id[0]
- client_id1 = removeclient_id[1]
- client_id = client_id1.strip('\n')
- resolvedIP = socket.gethostbyname(productCode.strip())
- line1 = productCode.strip('\n')
- resolvedIP1 = resolvedIP.strip('\n')
- logging.info('Resolved {0} to {1}!'.format(line1, resolvedIP1))
- print('Resolved {0} to {1}!'.format(line1, resolvedIP1))
- if ipaddress.ip_address(u'{0}'.format(resolvedIP1)) in ipaddress.ip_network(u'10.0.0.0/8'):
- os.system("echo '{0},{1}' >> otwiplist.txt".format(resolvedIP1, client_id))
- logging.debug('Adding {0} to OTW IP List..'.format(resolvedIP1))
- #self.checkAlive(ldapPassword)
- else:
- os.system("echo '{0}' >> telarusiplist.txt".format(resolvedIP1))
- logging.debug('Adding {0} to Telarus IP List..'.format(resolvedIP1))
- except socket.gaierror:
- print('Failed to resolve {0}'.format(line1))
- logging.info('Failed to resolve {0}'.format(line1))
- logging.info('Device selected: {0} - {1}'.format(line1, resolvedIP1))
- elif userSelect == 2:
- print('Please select 1')
- else:
- print('\n{0} is an invalid input!\n'.format(userSelect))
- self.checkAlive(ldapPassword, resolvedIP1, line1)
- def checkAlive(self, ldapPassword, resolvedIP1, line1):
- with open('otwiplist.txt') as ipList:
- for line in ipList:
- removeclientIDNEWLINE = line.rstrip('\n')
- print('removeclientIDNEWLINE: {0}'.format(removeclientIDNEWLINE))
- removeclientID = removeclientIDNEWLINE.split(',')
- print('removeclientID: {0}'.format(removeclientID))
- currentDevice = removeclientID[0]
- client_id = currentDevice[1]
- print(currentDevice, client_id)
- logging.info('Checking if {0} is online..'.format(currentDevice))
- check = os.system('ping -c 1 {0}'.format(currentDevice))
- if check == 0:
- logging.info('{0} responded successfully!'.format(currentDevice))
- os.system("echo 'Device: {0} is online... proceeding to configure' >> logfiles/logfile.txt".format(currentDevice))
- print('Device: {0} is online... proceeding to configure'.format(currentDevice))
- self.connectDevice(currentDevice, ldapPassword, client_id, resolvedIP1, line1)
- else:
- logging.info('{0} has failed to respond! Marking as offline..'.format(currentDevice))
- os.system('echo {0} >> logfiles/offlinedevice.txt'.format(currentDevice))
- os.system("echo 'Device: {0} is offline! Ending.' >> logfiles/logfile.txt".format(currentDevice))
- pass
- print('\n')
- exit()
- def connectDevice(self, currentDevice, ldapPassword, client_id, resolvedIP1, line1):
- sc = pexpect.spawn('telnet {0}'.format(currentDevice))
- sc.logfile_read = sys.stdout
- eofError = 'pexpect.EOF, timeout=None'
- connectionClosed = sc.expect([eofError, 'Username:'])
- if connectionClosed == 0:
- logging.info('### {0} has closed the connection, needs investigation! ###'.format(currentDevice))
- pass
- else:
- sc.sendline(self.loginUser)
- sc.expect('Password:')
- sc.sendline(self.loginPassword)
- checkError = sc.expect(['Error: Authentication failed.', 'Request Denied', '>'])
- if checkError == 0:
- logging.info('{0} has failed with default credentials! Checking LDAP...'.format(currentDevice))
- sc.expect('Username:')
- sc.sendline(self.ldapUser)
- sc.expect('Password:')
- sc.sendline(ldapPassword)
- sc.expect('>')
- self.configHuawei(currentDevice, sc, client_id, resolvedIP1, line1)
- pass
- if checkError == 1:
- logging.info('{0} has been detected as a Cisco! Sending LDAP....'.format(currentDevice))
- sc.expect('Username:')
- sc.sendline(self.ldapUser)
- sc.expect('Password:')
- sc.sendline(ldapPassword)
- self.configCisco(currentDevice, sc, client_id, resolvedIP1, line1)
- else:
- logging.info('Succesfully connected to {0} with default credentials'.format(currentDevice))
- self.configHuawei(currentDevice, sc, client_id, resolvedIP1, line1)
- pass
- def configHuawei(self, currentDevice, sc, client_id, resolvedIP1, line1):
- model_type = 'Huawei'
- sc.sendline('system-view')
- sc.expect(']')
- self.exporttoCSV(model_type, client_id, resolvedIP1, line1, currentDevice)
- def configCisco(self, currentDevice, sc, client_id, resolvedIP1, line1):
- model_type = 'Cisco ' #Will need to screenscrape to get the model
- sc.expect('\#')
- sc.sendline('conf t')
- sc.expect('\)')
- self.exporttoCSV(model_type, client_id, resolvedIP1, line1, currentDevice)
- def exporttoCSV(self, model_type, client_id, line1, resolvedIP1, currentDevice):
- site_id = line1
- carriage_id = 'carriageID'
- management_ip = currentDevice
- snmp_ro = 'snmpread'
- snmp_rw = 'snmpwrite'
- serial_number = 'serialnumber'
- mac_address = 'macaddress'
- asset_number = 'assettag'
- with open('cpeimport.csv', 'a') as cpefile:
- 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]
- writecpe = csv.writer(cpefile, dialect='excel')
- writecpe.writerow(csvData)
- code = mainCode()
- code.getLDAP()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement