Nov-17-2019, 07:05 AM
Hi All,
I have modified original script to work with ZyXEL DSLAM devices, need to guidance to implement threading for method of class but outside of the class
I have modified original script to work with ZyXEL DSLAM devices, need to guidance to implement threading for method of class but outside of the class
import threading import sys import os import subprocess import socket from telnetlib import Telnet import unidecode #import telnetlib import time import re from time import sleep class ZyXEL: """ Telnet to ZyXEL DSLAM and collect Port, vlan and MAC details """ newline = "\n" character_time_spacing_seconds = 0.1 line_time_spacing_seconds = 0.1 def __init__(self): self.host = "" self.timeout = "" self.sr_no = 0 self.port = 0 self.username = "" self.password = "" self.session = 0 self.prompt = ">" self.response_timeout = 5 # timeout self.liveHost = [] #list of live hosts def write_command(self, commandstr): """ Write a command to the peer """ #self.session.write(commandstr) commandstr_len = len(commandstr) for i in range(0, commandstr_len): self.session.write(commandstr[i].encode('ascii')) time.sleep(self.character_time_spacing_seconds) if commandstr[i] == '\r': time.sleep(self.line_time_spacing_seconds) # Login to device def login(self, username, password): """ Log in at the device """ output = self.session.read_until(b":", self.response_timeout) if output.find(b"User name:") != -1: self.session.write(username.encode('ascii') + self.newline.encode('ascii')) self.session.read_until(b"Password:", self.response_timeout) self.session.write(password.encode('ascii') + self.newline.encode('ascii')) pass_response = self.session.read_until(self.prompt.encode('ascii'), self.response_timeout) if self.prompt.encode('ascii') not in pass_response: return False else: self.session.close() return False return True def execute_command_lowlevel(self, command, timeout=None): """ Execute a command and return the result """ if timeout is None: timeout = self.response_timeout commandstr = command + self.newline self.write_command(commandstr) output = self.session.read_until(self.prompt.encode('ascii'), timeout) ret = output[:-len(self.prompt)] return ret def execute_command(self, command, timeout=None): """ Execute a command on the device """ retries_remaining = 3 while retries_remaining > 0: try: return self.execute_command_lowlevel(command, timeout) except EOFError: retries_remaining = retries_remaining - 1 print("Got EOFError, reconnecting...") self.connect_and_login() def connect_and_login(self): """ Establish a Telnet session and login""" self.session = Telnet() try: self.session.open(self.host, self.port, self.response_timeout) except socket.timeout: return False if not self.login(self.username, self.password): return False try: self.execute_command_lowlevel('\r') except EOFError: return False return True def open(self, host, port, username, password): """ Open a connection to a device """ self.host = str(host) # In case we receive a Unicode string self.port = port self.prompt = self.host[:self.host.find(".")] + ">" self.username = username self.password = password connect_login_result = self.connect_and_login() return connect_login_result def close(self): """ Close the connection""" self.execute_command("exit") def dslam_rechability_check(self, ip): """ Check device is up or not """ ping_reply = subprocess.call(['ping', '-c', '2', '-w', '2', '-q', '-n', ip],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if ping_reply == 0: self.liveHost.append(ip) # append to list else: pass return self.liveHost # return live host list if __name__ == "__main__": start = time.time() device = ZyXEL() with open('zyxel.txt','r') as ipfile: #device ip file threads = [] for sr_no, line in enumerate(ipfile, start=1): host = line.strip() th = threading.Thread(target = device.dslam_rechability_check ,args = (host,)) th.start() threads.append(th) for thr in threads: thr.join() for Livehost in device.liveHost: # this list is return by class print("Working on {}".format(Livehost)) result = device.open(Livehost,23,'admin','1234') data = device.execute_command('statistics mac 1~48'+'\r\r') mac_detail = iter(data.decode('utf-8').split('\n')) try: for line in mac_detail: if "Port:" in line: port1 = line.split(':') port = line.strip().split()[1] """ Parsing below output data Port: 1 index vid mac ----- ---- ----------------- 1 2000 10:62:eb:66:07:76 Port: 4 index vid mac ----- ---- ----------------- 2 2000 0c:d2:b5:63:50:be Port: 5 index vid mac ----- ---- ----------------- 3 2000 80:26:89:c8:88:d3 """ next(mac_detail) next(mac_detail) port_mac = next(mac_detail)[1:] index,vid,mac = port_mac.split() print ('{} {} {} {} {}'.format(Livehost,port,index,vid,mac)) except StopIteration: pass device.close() #close session print('It took', time.time()-start, 'seconds.')Want to implement threading for below code for faster completion.
for Livehost in device.liveHost: # this list is return by class print("Working on {}".format(Livehost)) result = device.open(Livehost,23,'admin','1234') data = device.execute_command('statistics mac 1~48'+'\r\r') mac_detail = iter(data.decode('utf-8').split('\n')) try: for line in mac_detail: if "Port:" in line: port1 = line.split(':') port = line.strip().split()[1] """ Parsing below output data Port: 1 index vid mac ----- ---- ----------------- 1 2000 10:62:eb:66:07:76 Port: 4 index vid mac ----- ---- ----------------- 2 2000 0c:d2:b5:63:50:be Port: 5 index vid mac ----- ---- ----------------- 3 2000 80:26:89:c8:88:d3 """ next(mac_detail) next(mac_detail) port_mac = next(mac_detail)[1:] index,vid,mac = port_mac.split() print ('{} {} {} {} {}'.format(Livehost,port,index,vid,mac)) except StopIteration: pass device.close() #close session