Multi thread telnet issue - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Multi thread telnet issue (/thread-9256.html) |
Multi thread telnet issue - anna - Mar-29-2018 Below script is working, however randomly few devices showing as time out, but those devices are reachable to able to telnet. Thanks for our Moderators/admin and members supporting for this script. #!/usr/bin/python import threading import sys import os import unidecode import telnetlib import time import re from time import sleep start = time.time() user = 'eciecidslam' password = 'Hi-FOCuS' start = time.time() macfile = open('mumecimac.txt','w') def open_telnet(host): #with open('eci.txt','r') as ipfile: # for sr_no, line in enumerate(ipfile, start=1): # host = line.strip() timeout = 120 sr_no = 0 try: session = telnetlib.Telnet(host, 23, timeout) time.sleep(2) session.read_until(b"Login :") session.write((user+"\r").encode('ascii')) time.sleep(2) session.read_until(b"Password :",2) session.write((password + "\r").encode('ascii')) time.sleep(2) session.read_until(b"MCR64A >") session.write("dishash all".encode('ascii') + b"\r") output = session.read_until("MCR64A >".encode('ascii'), timeout ) for line in output.decode('utf-8').split('\n')[4:]: line = line.split('|') if len(line) == 8: mac, bport, vlan = map(lambda x: x.strip(), line[:3]) mac_address = mac2norm(mac) #MyList = host,mac_address, bport, vlan command = "bportr " +bport session.write((command +"\r").encode('ascii')) portoutput = session.read_until("MCR64A >".encode('ascii'), timeout ) for line in portoutput.split('\n'): if 'Port:' in line: port = line.replace(' ','').split(':')[1] #MyList += (port,) macfile.write('{} {} {} {} {}\n'.format(host,mac_address, bport, vlan, port)) session.write(("logout"+"\r").encode('ascii')) session.close() except Exception as excp: print('time out:- {}\n '.format(host)) def mac2norm(mac): mac = mac.split(' ') return '{:0>2}:{:0>2}:{:0>2}:{:0>2}:{:0>2}:{:0>2}'.format(*mac).upper() def create_threads(): threads = [] with open('mumeci.txt','r') as ipfile: for sr_no, line in enumerate(ipfile, start=1): host = line.strip() time.sleep(2) th = threading.Thread(target = open_telnet ,args = (host,)) time.sleep(5) th.start() threads.append(th) for thr in threads: thr.join() if __name__ == "__main__": create_threads() print ("Exiting the program") #outfile.close() macfile.close() print('It took', time.time()-start, 'seconds.') |