1
\$\begingroup\$

I've written below python script just to invoke parallel threads of a command nslookup linux-host01 dns-server, i'm Just trying to flood the DNS Server dns-server with multiple number of queries in parallel way.

As an argument to this script i'm passing a hostlist file example linux-host01 , linux-host02 etc.

To achieve this i'm using threading module with the below code and this works fine, However, i'm using the the threading first time hence would like to know if this can be simplified of enhanced further.

import os
import threading
from sys import argv, exit


lock = threading.Lock()

hostfile = argv[1]

lst = []
with open(hostfile, 'r') as frb:
    for line in frb:
        lst.append(line.strip("\n"))

threads = []
thread_count = len(lst)

def pop_queue():
    host = None
    lock.acquire()
    if lst:
        host = lst.pop()
        lock.release()
    return host

def dequeue():
    while len(lst) != 0:
        host = pop_queue()
        if not host:
            return None
        else:
            dolookup(host)

def dolookup(name):
    while True:
        os.system("/usr/bin/nslookup %s dns-test01" %name)

for i in range(thread_count):
    t = threading.Thread(target=dequeue)
    t.start()
    print "started thread %s" %i
    threads.append(t)

[t.join() for t in threads]

Appreciate any help on this.

\$\endgroup\$
2
  • \$\begingroup\$ python has GIL (Global Interpreter Lock) so threads don't run in parallel. \$\endgroup\$ – furas Jul 24 '19 at 8:06
  • 2
    \$\begingroup\$ Another issue is that os.system() is quite an inefficient way to do a hostname lookup; it starts a new shell process, and that shell starts the nslookup binary. Try to use socket.getaddrinfo() instead. \$\endgroup\$ – G. Sliepen May 16 '20 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.