Python Forum
problem to use multi-threads in a code for telnet sessions
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem to use multi-threads in a code for telnet sessions
#1
import threading
import telnetlib
import sys
import time
import os
import re
ohfmacfile = open ('/home/anna/scripts/ohfmac.txt','w')
def connectionTelnet(ip):
    user = "anna"
    password = "test@123"
    telnet = telnetlib.Telnet(ip)
    telnet.read_until("Username: ", 3)
    telnet.write(user + '\r')
    telnet.read_until("Password: ", 3)
    telnet.write(password + '\r')
    telnet.write("term length 0" + "\r\n")
    telnet.write("show mac address | i Fa" + "\r\n")
    telnet.write('exit' '\r\n')
    output=telnet.read_all()
    for line in output.split('\n')[4:]:
           if 'exit' in line:
              break
           else:
               data= re.sub('\s{2,}', ' ', line) # Remove multiple spaces and replace with single space
               vlan,mac,mactype,interface = data.strip().split(' ')
               ohfmacfile.write(ip+" "+vlan+" "+mac+" "+mactype+" "+interface+'\n')
print ("############################################")
print ("#            Switches MAC                  #")
print ("#                by me                     #")
print ("#                                          #")
print ("############################################\n")

def create_threads():
    threads = []
    with open('ohfbs.txt','r') as ipfile:
        for sr_no, line in enumerate(ipfile, start=1):
            ip = line.strip()
            host_up = os.system('ping ' '-c 5 -W 1 ' + str(ip) + ' >  /dev/null')
            if not host_up:
               print (u"\033[92m [+] Device Reachable "+ str(ip))
               th = threading.Thread(target = connectionTelnet ,args = (ip,))
               th.start()
               threads.append(th)
            else:
                print (u"\033[91m [-] Device Unreachable " + str(ip))
                print (u"\x1b[0m")
        for thr in threads:
            thr.join()

if __name__ == "__main__":
        create_threads()
        print "Exiting the program"
        ohfmacfile.close()
Above script is first checking whether devices is reachable or not, then its initiate multiple telnet session. However I am missing something, its not working in multi thread mode.

please guide.
Reply
#2
I think that the problem is calling multiple threads to write the same file.
I can't test right now but maybe you can think of something to check if this is really the problem.
Reply
#3
Some modification... but with erros

import threading
import paramiko
import telnetlib
import cmd
import sys
import time
import os
import re
ohfmacfile = open ('/home/anna/scripts/ohfmac.txt','w')
def connectionTelnet(ip):
    user = "anna"
    password = "test@123"
    telnet = telnetlib.Telnet(ip)
    telnet.read_until("Username: ", 3)
    telnet.write(user + '\r')
    telnet.read_until("Password: ", 3)
    telnet.write(password + '\r')
    telnet.write("term length 0" + "\r\n")
    telnet.write("show mac address | i Fa" + "\r\n")
    telnet.write('exit' '\r\n')
    output=telnet.read_all()
    for line in output.split('\n')[4:]:
           if 'exit' in line:
              break
           else:
               data= re.sub('\s{2,}', ' ', line) # Remove multiple spaces and replace with single space
               vlan,mac,mactype,interface = data.strip().split(' ')
               ohfmacfile.write(ip+" "+vlan+" "+mac+" "+mactype+" "+interface+'\n')

print ("############################################")
print ("#            TCL OHF MAC Finding           #")
print ("#                by me                     #")
print ("#                                          #")
print ("############################################\n")
def host_status():
    alive = []
    dead  = []
    with open('autoohfbs.txt','r') as ipfile:
        for sr_no, line in enumerate(ipfile, start=1):
            ip = line.strip()
            host_up = os.system('ping ' '-c 2 -W 1 ' + str(ip) + ' >  /dev/null')
            if not host_up:
               print (u"\033[92m [+] Device Reachable "+ str(ip))
               alive.append(ip)
            else:
                print (u"\033[91m [-] Device Unreachable " + str(ip))
                print (u"\x1b[0m")
                dead.append(ip)
        #print ('\n'.join('{}' for _ in range(len(alive))).format(*alive))
    threads = []
    for i in range(len(alive)):
        process = threading.Thread(target=connectionTelnet, args= alive[i],)
        process.start()
        threads.append(process)
    for process in threads:
        process.join()
if __name__ == "__main__":
         host_status()
         print "Exiting the program"
         ohfmacfile.close()
Output:
[+] Device Reachable 172.21.248.179 [+] Device Reachable 172.21.237.131 [+] Device Reachable 172.21.195.51 [+] Device Reachable 172.21.212.35 [+] Device Reachable 172.21.241.5 [+] Device Reachable 172.21.200.135 [-] Device Unreachable 172.21.248.131 [-] Device Unreachable 172.21.229.37 [+] Device Reachable 172.21.160.3
Error:
Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (14 given) Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (13 given) Exception in thread Thread-3: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (13 given)
Reply
#4
Check what is really coming in alive array:

print(alive[i])
process = threading.Thread(target=connectionTelnet, args = (alive[i],))
Reply
#5
showing alive[i] as ip address

Error:
[+] Device Reachable 172.21.248.179 [+] Device Reachable 172.21.237.131 [+] Device Reachable 172.21.195.51 [+] Device Reachable 172.21.212.35 [+] Device Reachable 172.21.241.5 [+] Device Reachable 172.21.200.135 [-] Device Unreachable 172.21.248.131 [-] Device Unreachable 172.21.229.37 [+] Device Reachable 172.21.160.3 172.21.248.179 172.21.237.131 Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (14 given) 172.21.195.51 Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (14 given) Exception in thread Thread-3: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (13 given) [b]172.21.212.35 172.21.241.5[/b] Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (13 given) 172.21.200.135 Exception in thread Thread-5: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (12 given) [b]172.21.160.3[/b] Exception in thread Thread-6: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (14 given) Exception in thread Thread-7: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner self.run() File "/usr/lib64/python2.7/threading.py", line 765, in run self.__target(*self.__args, **self.__kwargs) TypeError: connectionTelnet() takes exactly 1 argument (12 given)
Reply
#6
You're passing args as a list of args (every "char" in ip) for connectionTelnet().

Check my syntax for args.
process = threading.Thread(target=connectionTelnet, args = (alive[i],))
Reply
#7
Thanks gontajones,
Will update you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  requests_futures.sessions retry list of HTTP 429 Johanoosterwaal 0 1,534 Nov-20-2020, 09:23 PM
Last Post: Johanoosterwaal
  Telnet command in Python 3.9 Dre83 0 1,928 Nov-11-2020, 11:42 AM
Last Post: Dre83
  Sending command using telnet mradovan1208 1 3,880 Apr-24-2020, 07:09 PM
Last Post: Larz60+
  How to get a count of -Python- threads from the outside (or via code instrumentation) dstromberg 0 1,788 Jul-15-2019, 06:58 PM
Last Post: dstromberg
  Serial to telnet using Python Charles_Linquist 2 6,128 Jun-17-2019, 04:37 PM
Last Post: DeaD_EyE
  Code snippets for building multi column Listviews and or Treeview KevinBrown 3 3,275 Apr-14-2019, 06:50 PM
Last Post: Yoriz
  starting multi threads MuntyScruntfundle 7 3,423 Oct-11-2018, 08:52 PM
Last Post: nilamo
  Multi-processing - problem with running multiple *.py files at the same time Antonio 5 3,746 Sep-12-2018, 01:08 PM
Last Post: volcano63
  Multi thread telnet issue anna 0 2,099 Mar-29-2018, 05:35 PM
Last Post: anna
  telnet unexpected output printing anna 3 3,536 Jan-17-2018, 01:16 PM
Last Post: anna

Forum Jump:

User Panel Messages

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