Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Experts,
Request support to fix the issue and arrange code(python2.6) in proper sequence
I have multiple input files from which i need to read third column value and pass it to command("show run interface gigabitEthernet %s\r\n" % data) present inside script which is doing telnet and extracting data. I also have one file which is having list of IP's to be used for telnet device one by one. Needed multiple output file for each input file.

Passing the value in this command inside script:

show run interface gigabitEthernet %s\r\n"


Issue : Script not able to generate multiple output file for multiple input files.
Output for all input file is getting generated in single output file 'result_s'

Have multiple input files containing data like below :

File 1:

Sessions,CPU,facility
43,17104773,1
45,17104234,2


File 2:
Sessions,CPU,facility
43,17104773,3
45,17104234,4


Need output at different path in separate file for each input file

What I have tried:

Python
<pre lang="Python">
#!/usr/bin/env python
import sys
import telnetlib
import os
import subprocess

import csv
import os
import logging

# This is the main logger object to be used throughout the script
logger = None

# Create the necessary log handles
#   A log file is created with the filename specified
#   Other log messages are also printed on the console as per the level
def createLogHandlers(logfile):
    global logger
    logging.basicConfig(filename=logfile ,
                        filemode='a',
                        level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S')
    logger = logging.getLogger('Telnet')

    # Create handler which logs messages on console
    log_console = logging.StreamHandler()
    log_console.setLevel(logging.DEBUG)
    log_console.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s %(message)s',
                                                datefmt='%a, %d %b %Y %H:%M:%S'))
    logger.addHandler(log_console)


# Global Objects
COLUMN_DATA = []
PATHSTR = "/tmp/input"
os.chdir (PATHSTR)

'''
This will extract data from all the files with filename
pattern "aa<number>" present in the PATHSTR
'''
def extract_column_data():
    global COLUMN_DATA
    fileCount = 1
    for file in os.listdir(PATHSTR):
        if file.startswith("aa"):
            logger.info("Reading from file %s, file counter = %d" % (file, fileCount))
            fileCount += 1

            infile = open(file)
            outfile = open('out_%d.txt' % fileCount, 'wb')

            csvreader = csv.DictReader(infile)
            csvwriter = csv.writer(outfile)

            for row in csvreader:
                # store the data in memory
                COLUMN_DATA.append(row['facility'])

                # Write the data to storage
                csvwriter.writerow(row['facility'])

            infile.close()
            outfile.close()



def my_function(device):
    global COLUMN_DATA
    f = open('result_S', 'w')
    user = "abc"
    password = "abc"
    try:
        # TELNET TO DEVICE
        telnet = telnetlib.Telnet(device)
        telnet.read_until('username: ', 3)
        telnet.write(user + '\r')
        telnet.read_until('password: ', 3)
        telnet.write(password + '\r')
        telnet.write("term len 0" + "\r\n")
        response = telnet.read_until('IST', timeout=5)

        logger.info("Logged into device ip = %s successfully" % device)

         for data in COLUMN_DATA:
            logger.info("Checking show run for interface %s" % data)
            telnet.write("show run interface gigabitEthernet %s\r\n" % data)
            response = telnet.read_until('S', timeout=5)
            logger.debug("Received response:\n%s " % response)

            f.write('\n' + str(device) + "\t" + "response:" + "\t" + response)
            telnet.write('\r\r')
            telnet.write('\r\r')
            #telnet.write('exit' + '\r')
    except NameError:
        logger.error("Script ERROR")
    except:
        logger.error("Telnet Failed")
    finally:
        f.close( )



### MAIN FUNCTION ###

if __name__ == "__main__":
    createLogHandlers('telnet_b.log')

    extract_column_data()

    IP_address = open("IP_file", "r")

    logger.info("Reading from file %s" % IP_address.name)
    for device in IP_address:
       logger.debug("Parsed device=%s" % device)
       logger.info("Running ping against device=%s" % device)
       res = subprocess.call(['ping', '-c', '2', device])
    if res == 0:
        logger.debug("Ping to device=%s successfull" % device)
        logger.info("Initating show run collection on device=%s" % device)
        my_function(device)
    else:
        print
        logger.warning("Ping to device=%s failed" % device)
Posted
Updated 23-Jul-19 21:47pm

1 solution

Python
def my_function(device):
    global COLUMN_DATA
    f = open('result_S', 'w')

You need to move the file open inside the loop where you test each interface, and use the interface number as a suffix on the filename. Similar to the code in the extract_column function.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900