Python Forum
threading for method outside class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
threading for method outside class
#1
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


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 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  class definition and problem with a method HerrAyas 2 252 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  super() and order of running method in class inheritance akbarza 7 735 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Concurrent futures threading running at same speed as non-threading billykid999 13 1,826 May-03-2023, 08:22 AM
Last Post: billykid999
  Using one child class method in another child class garynewport 5 1,583 Jan-11-2023, 06:07 PM
Last Post: garynewport
  [Solved] Novice question to OOP: can a method of class A access attributes of class B BigMan 1 1,314 Mar-14-2022, 11:21 PM
Last Post: deanhystad
  class, attribute and method Frankduc 9 2,467 Feb-27-2022, 09:07 PM
Last Post: deanhystad
  Subclass initialized property used in parent class method. Is it bad coding practice? saavedra29 5 1,770 Feb-07-2022, 07:29 PM
Last Post: saavedra29
  Class Method to Calculate Age Doesn't Work gdbengo 1 1,705 Oct-30-2021, 11:20 PM
Last Post: Yoriz
  Tutorials on sockets, threading and multi-threading? muzikman 2 2,123 Oct-01-2021, 08:32 PM
Last Post: muzikman
  anonymous method in a class Skaperen 8 3,595 May-23-2021, 11:17 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020