subprocess in thread python to check reachability - 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: subprocess in thread python to check reachability (/thread-12623.html) |
subprocess in thread python to check reachability - anna - Sep-04-2018 Hi All, I would like to put subprocess in thread to check reachability in less time. Below is the my code. First its check reachability and put alive hosts in alive list and initiate threads to telnet and capture Serial number and Hardware information. I am implementing to check more than 2500+ devices. import threading import unidecode import telnetlib import time import re import subprocess alive = [] dead = [] user = 'eci' password = 'Hi-test123' def open_telnet(host): timeout = 120 sr_no = 0 try: session = telnetlib.Telnet(host, 23, timeout) time.sleep(1) #session.set_debuglevel(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("eer".encode('ascii') + b"\r") session.write(" ".encode('ascii')) session.write(" ".encode('ascii')) session.write(" ".encode('ascii')) time.sleep(2) output = session.read_until("MCR64A >".encode('ascii'), timeout ) session.write(("logout"+"\r").encode('ascii')) session.close() #print(output) for line in output.split('\n')[1:]: #print line if 'HW DESCRIPTION' in line: hw_description = line.split('||')[1] elif 'SERIAL NUMBER' in line: sr_number = line.split('||')[1] print('{} {} {}'.format(host.strip(),sr_number.strip(),hw_description.strip())) except Exception as excp: print('time out:- {}\n '.format(host)) def hostdetails(): with open('eciserial.txt', 'r') as f: for ip in f: ip.strip() result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],stdout=f, stderr=f).wait() if result: dead.append(ip) else: alive.append(ip) def create_threads(): threads = [] for ip in alive: th = threading.Thread(target = open_telnet ,args = (ip,)) th.start() time.sleep(0.5) threads.append(th) for thr in threads: thr.join() if __name__ == "__main__": hostdetails() create_threads() print('Rechable :', len(alive)) print "Exiting the program" RE: subprocess in thread python to check reachability - woooee - Sep-04-2018 What is the problem with the code you posted? Also, you should be able to use the less complicated subprocess' check_ouput() function for the ping results. RE: subprocess in thread python to check reachability - anna - Sep-05-2018 No issue in current code, however posted for improvement/correction for speed up process. regards Anna RE: subprocess in thread python to check reachability - woooee - Sep-05-2018 Most of the time taken is because of the time.sleep statements. |