Sep-04-2018, 06:03 AM
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.
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"
