Python Forum
Multithread telnet not working Parallel
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multithread telnet not working Parallel
#1
#!/usr/bin/python
import threading
import sys
import os
import unidecode
import telnetlib
import time
import re
from time import sleep
outfile = open('zyxelmac.txt','w')
def open_telnet(ip):
        user = 'admin'
        password = '1234'
        sr_no = 0
        try:
            telnet = telnetlib.Telnet(ip, 23, 2)
            telnet.read_until('User name:', 3)
            telnet.write(user.encode('ascii') + '\r')
            telnet.read_until('Password:', 3)
            telnet.write(password.encode('ascii') + '\r')
            telnet.write('statistics mac 1~48' + '\r\r\r\r')
            telnet.read_until('>')
            telnet.write(' exit''\r')
            output = telnet.read_all()
            sleep(2)
            data = iter(output.split('\n'))

            try:
                        for line in data:
                                if "Port:" in line:
                                        port1 = line.split(':')
                                        port = str(port1[:5])
                                        port2 = port[10:13].strip()
                                        port3 = port2.replace('\\','')
                                        next(data)
                                        next(data)
                                        port_mac = next(data)[1:]
                                        outfile.write(ip+' '+port3+' '+port_mac)
                                        outfile.write('\n')
            except StopIteration:
                   pass
        except Exception as excp:
            print(excp)
def create_threads():
    threads = []
    with open('zyxel.txt','r') as ipfile:
        for sr_no, line in enumerate(ipfile, start=1):
            ip = line.strip()
            th = threading.Thread(target = open_telnet ,args = (ip,))
            th.start()
            threads.append(th)
            for thr in threads:
                thr.join()

if __name__ == "__main__":
        create_threads()
        print "Exiting the program"
        outfile.close()
above script is working sequentially and not Parallel. please suggest.
Reply
#2
what if u indent lines 52 & 53 ...
with open('zyxel.txt','r') as ipfile:
        for sr_no, line in enumerate(ipfile, start=1):
            ip = line.strip()
            th = threading.Thread(target = open_telnet ,args = (ip,))
            th.start()
            threads.append(th)
        for thr in threads:   #indent this line
            thr.join()        #indent this line
the code likely started & joined each thread simultanously, could be the main reason why scripts works sequentially
swallow osama bin laden
Reply
#3
Thanks,

now one small issue, in mutli thread.. lines are being printed as below,

10.217.128.69 5 2 2000 f8:e9:03:80:3a:6d^M10.217.128.127 5 1 3607 e8:cc:18:b1:4b:89
10.217.128.127 11 2 3607 e8:cc:18:60:a7:53
10.217.128.127 12 3 3607 e4:6f:13:86:7c:41
10.217.128.127 25 4 3607 e4:6f:13:86:7a:e8
10.217.128.127 30 5 3607 3c:1e:04:33:87:55
10.217.128.127 39 6 3607 28:28:5d:ed:c2:aa^M10.217.128.74 16 3 3740 00:17:7c:7c:a0:9a

I am expecting like below

10.217.128.69 5 2 2000 f8:e9:03:80:3a:6d
10.217.128.127 5 1 3607 e8:cc:18:b1:4b:89
10.217.128.127 11 2 3607 e8:cc:18:60:a7:53
10.217.128.127 12 3 3607 e4:6f:13:86:7c:41
10.217.128.127 25 4 3607 e4:6f:13:86:7a:e8
10.217.128.127 30 5 3607 3c:1e:04:33:87:55
10.217.128.127 39 6 3607 28:28:5d:ed:c2:aa
10.217.128.74 16 3 3740 00:17:7c:7c:a0:9a
Reply
#4
tbh i dont have any idea what telnet is all about,
my best guess is '^M' indicates more than 1 ports 'arrived' at the same time ,sort of , so their results printed at the same line

try change line 38 to outfile.write(ip+' '+port3+' '+port_mac+'\n')

you should get exact outcome in your 'zyxelmac.txt', not in console/ python shell where few spaces maybe printed inconsistantly between printed results because of '\n'
swallow osama bin laden
Reply
#5
thanks, will check and update you.
Reply
#6
Hi All,

I have below script to telnet devices and gather MAC details with noappend mode and storing in file. I would like to convert this to python script.
##########
#log_user 0
set timeout 10
set f [open "UT-ROM-Batch-1.txt"]
set hosts [split [read -nonewline $f] "\n"]
log_file
foreach host $hosts {
spawn telnet $host
expect {
"Login:" {
}
timeout {
continue
}
}

send "admin\r"
expect "Password:"
send "1234\r"
expect "Alfran1>"
send "dsl -c\r" # Prompt change
expect "\\$" # New prompt
log_file -noappend /home/anna/scripts/ut/$host.umac
send "get bridge port forwarding\r"
expect "\\$"
send "\x1A" # Send control+z to come out from inner prompt
expect "Alfran1>" # Outer prompt
send "exit\r"
log_file

}
expect eof
close $f
Reply
#7
You should take a look into docs.python.org/3.6/library/telnetlib.html.

And crosspost: https://python-forum.io/Thread-Multithre...g-Parallel
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#8
import telnetlib
import re
from time import sleep
user = 'admin'
password = '1234'
ip = '10.19.1.49'
telnet = telnetlib.Telnet(ip, 23, 2)
telnet.read_until('Login:', 3)
telnet.write(user.encode('ascii') + '\r')
telnet.read_until('Password:', 3)
telnet.write(password.encode('ascii') + '\r')
telnet.expect([r"\w+ >$"],2)
telnet.write('dsl -c' + '\r')
telnet.expect([r'\\$'],2)
telnet.write('get bridge port forwarding' +'\r')
telnet.read_until('$')
telnet.write('\x1A')
telnet.expect([r"\w+ >$"],2)
telnet.write(' exit'+'\r')
output = telnet.read_all()
sleep(2)
print(output)
tried about script but not able to print output.
Regex for inner prompt - telnet.expect([r'\\$'],2)
Control character from Control+z -is '\x1A', suggest.. how i can trouble shoot this?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  telnet from ssh tunnel oldfart 3 7,064 Jul-17-2020, 02:28 PM
Last Post: noobami99
  telnet to a device under tacacs management kang18 0 1,540 Jun-05-2020, 06:11 AM
Last Post: kang18
  3.6 telnet eyler 3 11,211 Jun-28-2019, 05:22 AM
Last Post: Khanhamid90
  Any suggestion on python library to use for both ssh and telnet? lord_mani 4 3,669 Jun-25-2019, 04:07 PM
Last Post: gb74razor
  telnet question jacklee26 2 2,462 Mar-30-2019, 06:45 AM
Last Post: jacklee26
  Retrieve output from telnet command Networker 1 4,041 Mar-12-2019, 01:36 PM
Last Post: searching1
  Aggregate multiple telnet connections Jibeji 1 4,220 Mar-02-2018, 07:21 PM
Last Post: mpd
  Python telnet script for IP list mangesh 1 54,497 Jun-26-2017, 11:12 PM
Last Post: DeaD_EyE
  Need advice: UDP? TCP? Multithread? Guybrush 5 5,065 Apr-28-2017, 08:04 PM
Last Post: wavic

Forum Jump:

User Panel Messages

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