def importHostsToDB(csvImport): # For each line in csvImport, run validation checks for x in csvImport.split('\n'): if x: # Split array by comma's xArray = x.split(',') # 0 is hostname, 1 is IP address, 2 is device type, 3 is ios type if not validateIPAddress(xArray[1]): return False, "Invalid IP address for host %s - value entered: %s" % (xArray[0], xArray[1]) if xArray[2].lower() not in ("switch", "router", "firewall"): return False, "Invalid device type for host %s - value entered: %s" % (xArray[0], xArray[2]) if stripNewline(xArray[3].lower()) not in ("ios", "ios-xe", "nx-os", "asa"): return False, "Invalid IOS type for host %s - value entered: %s" % (xArray[0], xArray[3]) # Each line has been validated, so import all lines into DB for x in csvImport.split('\n'): if x: # Split array by comma's xArray = x.split(',') # 0 is hostname, 1 is IP address, 2 is device type, 3 is ios type hostname = xArray[0] ipv4_addr = xArray[1] if xArray[2].lower() == 'switch': type="Switch" elif xArray[2].lower() == 'router': type="Router" elif xArray[2].lower() == 'firewall': type="Firewall" else: type="Error" if stripNewline(xArray[3].lower()) == 'ios': ios_type = "cisco_ios" elif stripNewline(xArray[3].lower()) == 'ios-xe': ios_type = "cisco_xe" elif stripNewline(xArray[3].lower()) == 'nx-os': ios_type = "cisco_nxos" elif stripNewline(xArray[3].lower()) == 'asa': ios_type = "cisco_asa" else: ios_type = "Error" try: host = models.Host(hostname=hostname, ipv4_addr=ipv4_addr, type=type, ios_type=ios_type) db.session.add(host) # This enables pulling ID for newly inserted host db.session.flush() db.session.commit() except: return False, "Error during import of devices into database" return True, "Successfully added all %s devices" % (len(csvImport))
def validatePortProtocolUserInput(input): # Loop for each inputted port number and protocol for x in input: # Reduce all spacing to just a single space per section x = fn.replaceDoubleSpaces(x) # Strip any new lines from the input x = fn.stripNewline(x) # Split string by spaces. The 1st field is the port, the 2nd field is the protocol xList = x.split(" ") # Port is xList[0], protocol is xList[1] if not ifn.validatePortNumber( xList[0]) or not ifn.validatePortProtocol(xList[1]): # Port number and protocol isn't valid, return False return False # All port number and protocol are valid, return True return True
def validateIPMaskUserInput(input): # Loop for each inputted source IP address and subnet mask for x in input: # Reduce all spacing to just a single space per section x = fn.replaceDoubleSpaces(x) # Strip any new lines from the input x = fn.stripNewline(x) # Split string by spaces. The 1st field is the IP address, the 2nd field is the subnet mask xList = x.split(" ") # IP address is xList[0], subnet mask is xList[1] if not ifn.validateIPAddress(xList[0]) or not ifn.validateSubnetMask( xList[1]): # IP address or subnet mask isn't valid, return False return False # All IP addresses and subnet masks are valid, return True return True
creds = fn.setUserCredentials(user, pw) # Save SSH username as userInitials for now, until implemented later #userInitials = creds.un # Set up the SSH session now, prints an error and closes the script if the SSH connection fails ssh = nfn.getSSHSession(deviceType, hostFW, creds) # If outputFileName not predefined, ask user for filename outputFileName = outputDirectory + ufn.userGetOutputFileName(outputFileName) # Get change ticket number from user changeTicket = raw_input( "What is the change ticket associated with this firewall change? ") # Strip new lines from user input changeTicket = fn.stripNewline(changeTicket) # Ask user for description on the above IP addresses print "\nDescribe this ticket and the source/dest IP addresses in 1 or 2 words only." srcDesc = raw_input( "This will be used for naming the different ACL groupings for this change: " ) # Strip any new lines from the input srcDesc = fn.stripNewline(srcDesc) # Replace any white space the user entered with underscores srcDesc = fn.replaceSpacesWithUnderscore(srcDesc) # Loop to validate user input while True: # Text to tell user what type of input we are looking for typeOfInput = "All source IP addresses and their subnet mask, separated by space (ex: 10.1.2.3 255.255.255.255)"
startTime = fn.getCurrentTime() # Counter for progress bar i = 0 # Progress bar for each email address listed in file fn.printProgress(i, emailCount, prefix='Progress:', suffix='Complete') # For each line extracted from the file, loop for line in fileLines: # Split each line on whitespace line = line.split(',') # Set email address and recipient name emailAddr = line[0] emailRecipient = line[1] # Strip new lines from email address and recipient name, if any emailAddr = fn.stripNewline(emailAddr) emailRecipient = fn.stripNewline(emailRecipient) # Set the email address as the recipient m.setRecipients(emailAddr) # Set the email subject m.setSubject('Email script test %s' % (i + 1)) # Set the body of text here m.setBody("""Dear %s,\n This is an example of a generic email being sent out.\n This is the whole email #%s.\n Sincerely,\n \n %s""" % (emailRecipient, i + 1, creds.un)) # Send the message
# Count how many switches are in the import file switchCount = fn.file_len(switchFileName) # Counter for progress bar i = 0 # Progress bar for each switch listed in file fn.printProgress(i, switchCount, prefix = 'Progress:', suffix = 'Complete') # For each line extracted from the file, loop for line in fileLines: # Split each line on whitespace line = line.split(',') # Set switch name and IP variables switchName = fn.stripNewline(line[0]) switchIP = fn.stripNewline(line[1]) # Dictionary to store results in; instantiate as empty resultList = {} # If 'line' is empty/all whitespace, this will fail try: # Connect to device; return unique list of STP blocked ports on host # Index 0 is device hostname, index 1 is device IP address # Initiate an SSH session ssh = sfn.connectToSSH(switchIP, creds) # Verify ssh connection established and didn't return an error if sfn.sshSkipCheck(ssh): # Set variable to True if switch was skipped switchSkipped = True # Establish SSH interactive session
# Get current time in format that can be appended to file name currentDate = time.strftime("%m-%d-%Y") currentTime = time.strftime("%H%M") outputDirectory = "%s/%s" % (outputDirectory, currentDate) # Get current time for later calculations on how long script took to run startTime = fn.getCurrentTime() # Make new directory for the current date fn.makeDirectory(outputDirectory) # Loop for each listed item imported into fileLines array for line in fileLines: # Strip newlines from imported devices line = fn.stripNewline(line) # Split each line on whitespace line = line.split(',') # Get running config from network device - line[1] is IP address commandRunConfig = sfn.runSSHCommand("show run", line[1], creds) # Save pulled running-config to file as a backup - line[0] is hostname backupFileName = "%s/%s_%s.txt" % (outputDirectory, line[0], currentTime) fn.writeCommandToFile(commandRunConfig, backupFileName) # Increment progress bar counter i += 1 # Progress bar for user on device count fn.printProgress(i, deviceCount, prefix = 'Progress:', suffix = 'Complete')
if fn.isHostIOSorNXOS(host) == "NXOS": command3 = "show cdp neighbors interface %s detail | inc \"IPv4 Address\"" % (portChannelInt) elif fn.isHostIOSorNXOS(host) == "IOS": command3 = "show cdp neighbors %s detail | inc IP address" % (portChannelInt) else: fn.debugErrorOut('Command3 NXOS vs IOS') # Run 3rd command, save output to 'result' result = sfn.runSSHCommand(command3, host, creds) # Reduce all spacing to just a single space per section result3 = fn.replaceDoubleSpaces(result) # Split string by spaces. We are looking for the 4th field ipAddressList = result3.split(" ") # Strip any newlines from the string, store as new host host = fn.stripNewline(ipAddressList[3]) continue # If device shows up as on a TenGigabitEthernet interface, assume it's on another switch elif ("Te" in iface): # Device is on another switch by MAC address table # teAbbrev is "Te5/1" for the TenGigabitEthernet interface teAbbrev = iface.replace("nGigabitEthernet", "") # Find IP address for switch where MAC address can be found off of # Different commands if NX-OS vs IOS/IOS-XE if fn.isHostIOSorNXOS(host) == "NXOS": command2 = "show cdp neighbors interface %s detail | inc \"IPv4 Address\"" % (teAbbrev) elif fn.isHostIOSorNXOS(host) == "IOS": command2 = "show cdp neighbors %s detail | inc IP address" % (teAbbrev)