januu agrawal
januu agrawal

Reputation: 45

Run multiple threads simultaneously but print one by one python?

As you might have an idea what I am talking about. So let me explain it more clearly.

For ex:- I have four threads which runs simulatenoulsy, Something like that.

th1 = threading.Thread(target=connCheck,  args= (newurl, schemess, 21))
th2 = threading.Thread(target=connCheck,  args=( newurl, schemess, 22))
th3 = threading.Thread(target=connCheck,  args= (newurl, schemess,80))
th4 = threading.Thread(target=connCheck,  args=(newurl, schemess,8080))

(this is the scanner for scanning ports of port number 21, 22, 80, 8080.)

And I run these threads like this:-

th1.start()
th2.start()
th3.start()
th4.start()
th4.join()

NOTE:- connCheck is a function to tell that what ports are open.

So in my terminal it shows that both ports are open BUT in a very bad manner. Sometimes it prints like this

List of port open:-

[+]21 [+]22 [+]80
[+]8080

And somethimes it prints like this:-

List of port open:-

[+]21 
[+]22 [+]80
[+]8080

And sometimes it prints some other way.

So What I want them to print in a Single good mannner like Line wise. But the most important thing to remember is I want to run all the above threads simultaneously so that it would not affect the speed of scan.

So I am come here to ask you. So please any one guide me in here.

Thanks

[EDIT]:- Here is the conncheck function:-

try: 

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(3)

        result = sock.connect_ex((ip, port))

        newip = schemess+ip+slash

        if port == 21:
            if result == 0:

                print "\t [+]" + str(port)
                ftpurls.append(newip)
                dicta(newip, port)


        else:
            if result == 0:


                    print '\t' + str(port)+ '\n'

                    dicta(newip, port)                      


        sock.close()
    except Exception as e:
        print str(e) + '\n'

Please ignore the dicta function.

Upvotes: 1

Views: 1489

Answers (1)

thuyein
thuyein

Reputation: 1792

There are a few ways to do it, using locks and another one is using logging module. I have been writing multithreading code using threading.Lock(), but I recently found out that logging is much more easier to use.

lock = threading.Lock()
with lock:
     print("...")

with lock will call lock.acquire() on enter, and on exit, it will call lock.release(). Or you can manually call those. But make sure to release it after you've acquired or you would be facing deadlocks.

The other easier way is to use logging as I mentioned. logging library is thread-safe, meaning any threads can use the functions at the same time. Using this module also allows you to write logs to the logfiles.

import logging

logging.basicConfig(format='%(message)s')
logging.info("...")

Upvotes: 1

Related Questions