473,659 Members | 2,683 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

thread help

Howdy,

Below is a script that I'm using to try and count the number of HTTP
servers within a company's private network. There are 65,536 possible
hosts that may have HTTP servers on them. Any way, I wrote this script
at first w/o threads. It works, but it takes days to run as it probes
one IP at a time... so I thought I'd try to make it threaded so it could
test several dozen IPs at once.

I'm no expert on threading, far from it. Could someone show me how I can
make this work correctly? I want to probe 64 unique IP address for HTTP
servers simultaneously, not the same IP addy 64 times (as I'm doing
now). Any tips would be much appreciated.

Bart

import urllib2, socket, threading, time

class trivialthread(t hreading.Thread ):
def run(self):
socket.setdefau lttimeout(1)

hosts = []
networks = []

# Add the network 192.168.0 possibility.
networks.append ("192.168.0. ")
n = 0
while n < 255:
n = n + 1
# Generate and add networks 192.168.1-255 to the list of networks.
networks.append ("192.168.%s ." %(n))

for network in networks:
h = 0
# Add the n.n.n.0 host possibility
hosts.append(ne twork+str(h))
while h < 255:
h = h + 1
# Add hosts 1 - 255 to each network.
hosts.append(ne twork+str(h))

websites = file('websites. txt', 'w')
for ip in hosts:
try:
f = urllib2.urlopen ("http://%s" %ip)
f.read()
f.close()
print>> websites, ip
except urllib2.URLErro r:
print ip
except socket.timeout:
print ip, "Timed Out............ ......."
except socket.sslerror :
print ip, "SSL Error.......... ........."
websites.close( )

if __name__ == '__main__':
threads = []
for x in range(64):
thread = trivialthread()
threads.append( thread)
for thread in threads:
thread.start()
while threading.activ eCount() > 0:
print str(threading.a ctiveCount()), "threads running incl. main"
time.sleep(1)
Jul 18 '05 #1
11 1683
In article <ca**********@s olaris.cc.vt.ed u>,
Bart Nessux <ba*********@ho tmail.com> wrote:

I'm no expert on threading, far from it. Could someone show me how I can
make this work correctly? I want to probe 64 unique IP address for HTTP
servers simultaneously, not the same IP addy 64 times (as I'm doing
now). Any tips would be much appreciated.


Create a threading.Threa d subclass that takes one IP address and a list
of ports to scan. Start 64 instances of this class, each with a
different IP address.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
Jul 18 '05 #2
Aahz wrote:
Bart Nessux <ba*********@ho tmail.com> wrote:
Could someone show me how I can make this work correctly? I want to probe
64 unique IP address for HTTP servers simultaneously, ...
Create a threading.Threa d subclass that takes one IP address and a list
of ports to scan. Start 64 instances of this class, each with a
different IP address.


An alternative is to create a que into which you push IP addresses to
contact, and have each thread read addresses off the queue when they are
free to process them. This has the advantage of decoupling the number
of threads from the number of addresses you want to examine.

-Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #3
In article <40********@nnt p0.pdx.net>,
Scott David Daniels <Sc***********@ Acm.Org> wrote:
Aahz wrote:
Bart Nessux <ba*********@ho tmail.com> wrote:

Could someone show me how I can make this work correctly? I want to probe
64 unique IP address for HTTP servers simultaneously, ...


Create a threading.Threa d subclass that takes one IP address and a list
of ports to scan. Start 64 instances of this class, each with a
different IP address.


An alternative is to create a que into which you push IP addresses to
contact, and have each thread read addresses off the queue when they are
free to process them. This has the advantage of decoupling the number
of threads from the number of addresses you want to examine.


Absolutely, but that requires a bit more work for someone who isn't
already familiar with threading.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
Jul 18 '05 #4
Scott David Daniels wrote:
An alternative is to create a que into which you push IP addresses to
contact, and have each thread read addresses off the queue when they are
free to process them. This has the advantage of decoupling the number
of threads from the number of addresses you want to examine.


That is also the general best design pattern for doing threading.
Have a Queue.Queue object where you place work items and have
threads pull items off the queue and execute it. You can use
callbacks or another Queue for placing the results on.

The Queue.Queue class has the nice property that it is very
thread safe, and you can do both blocking and timed waits
on it.

The other problem to deal with that is particular to Python is
how to stop threads when you want to shutdown or cancel actions.
At the very least you can have a 'shutdown' message you place
on the Queue that when any thread reads, it shuts down.

Unfortunately Python doesn't allow interrupting a thread,
so any thread doing something will run to completion. You
can check a variable or something in lines of Python
code, but cannot do anything when in C code. For example
if you do some networking stuff and the C code (eg a DNS
lookup followed by a TCP connect) takes 2 minutes, then
you will have to wait at least that long.

In the simplest case you can just make all your threads be
daemon. Python will shutdown when there are no non-daemon
threads left, so you can just exit your main loop and all
will shutdown. However that means the worker threads just
get abruptly stopped in the middle of what they were
doing.

(IMHO it would be *really* nice if Python provided a way
to interrupt threads).

Roger
Jul 18 '05 #5
Roger Binns wrote:
In the simplest case you can just make all your threads be
daemon. Python will shutdown when there are no non-daemon
threads left, so you can just exit your main loop and all
will shutdown. However that means the worker threads just
get abruptly stopped in the middle of what they were
doing.

(IMHO it would be *really* nice if Python provided a way
to interrupt threads).


Sounds like you can't eat your cake and have it, too. If
you _could_ interrupt threads**, wouldn't that mean "the worker
threads just get abruptly stopped in the middle of what they
were doing"?

-Peter

** There is a way to interrupt threads in Python now, but
it requires an extension routine, or perhaps something with
ctypes. Findable in the archives for this newsgroup/list.
Jul 18 '05 #6
Peter Hansen wrote:
Sounds like you can't eat your cake and have it, too. If
you _could_ interrupt threads**, wouldn't that mean "the worker
threads just get abruptly stopped in the middle of what they
were doing"?


I meant in the same way that can in Java. In that case an
InterruptedExce ption is thrown which the thread can catch
and do whatever it wants with.

As an example at the moment, socket.accept is a blocking
call and if a thread is executing that there is no way
of stopping it.

This would make shutdown and reconfiguration s possible.
For example you could interrupt all relevant threads
and they could check a variable to see if they should
shutdown, bind to a different port, abandon the current
work item etc.

Roger
Jul 18 '05 #7
Roger Binns wrote:
Peter Hansen wrote:
Sounds like you can't eat your cake and have it, too. If
you _could_ interrupt threads**, wouldn't that mean "the worker
threads just get abruptly stopped in the middle of what they
were doing"?


I meant in the same way that can in Java. In that case an
InterruptedExce ption is thrown which the thread can catch
and do whatever it wants with.


I didn't think things worked quite that way in Java. For
example, I thought InterruptedExce ption was seen by a thread
only if it had actually been asleep at the time it was sent.

I also didn't know it would actually terminate certain
blocking calls, such as in socket stuff.

Oh well, it's been a while...

-Peter
Jul 18 '05 #8
Scott David Daniels wrote:
Aahz wrote:
Bart Nessux <ba*********@ho tmail.com> wrote:
Could someone show me how I can make this work correctly? I want to
probe >>64 unique IP address for HTTP servers simultaneously, ...

Create a threading.Threa d subclass that takes one IP address and a list
of ports to scan. Start 64 instances of this class, each with a
different IP address.

An alternative is to create a que into which you push IP addresses to
contact, and have each thread read addresses off the queue when they are
free to process them. This has the advantage of decoupling the number
of threads from the number of addresses you want to examine.

-Scott David Daniels
Sc***********@A cm.Org


I like this idea. I read up on the queue and threading module at
python.org and a few other sites around the Web and came up with this,
however, it doesn't work. I get these errors when it runs:

Exception in thread Thread-149:
Traceback (most recent call last):
File "/usr/lib/python2.3/threading.py", line 434, in __bootstrap
self.run()
File "/usr/lib/python2.3/threading.py", line 414, in run
self.__target(* self.__args, **self.__kwargs )
File "www_reads_thre aded_1.py", line 49, in sub_thread_proc
f = urllib2.urlopen (url).read()
File "/usr/lib/python2.3/urllib2.py", line 129, in urlopen
return _opener.open(ur l, data)
File "/usr/lib/python2.3/urllib2.py", line 324, in open
type_ = req.get_type()
AttributeError: 'NoneType' object has no attribute 'get_type'

The problem I have is this: I know too little about thread programming.
If anyone thinks the code I have below could be made to work for my
tasks (probe 65,000 IPs for HTTP servers using threads to speed things
up), then please *show* me how I might change it in order for it to work.

Thanks again,
Bart

networks = []
hosts = []
urls = []
#socket.setdefa ulttimeout(30)
max_threads = 2
http_timeout = 30
start_time = time.time()

# Add the network 192.168.0 possibility.
networks.append ("192.168.0. ")

# Generate and add networks 192.168.1-255 to the list of networks.
n = 0
while n < 255:
n = n + 1
networks.append ("192.168.%s ." %(n))

# Generate and add hosts 1-255 to each network
for network in networks:
h = 0
# Add the n.n.n.0 host possibility
hosts.append(ne twork+str(h))
while h < 255:
h = h + 1
hosts.append(ne twork+str(h))

for ip in hosts:
ip = "http://" + ip
urls.append(ip)

urls = dict(zip(urls,u rls))
# print urls

# Create a queue of urls to feed the threads
url_queue = Queue.Queue()
for url in urls:
url_queue.put(u rl)
# print url

def test_HTTP(url_q ueue):
def sub_thread_proc (url, result):
# try:
f = urllib2.urlopen (url).read()
# except Exception:
# print "Exception"
# else:
result.append(u rl)
while 1:
try:
url = url_queue.get(0 )
except Queue.Empty:
return
result = []
sub_thread = threading.Threa d(target=sub_th read_proc,
args=(url,resul t))
sub_thread.setD aemon(True)
sub_thread.star t()
sub_thread.join (http_timeout)
print result

test_HTTP(urls)
Jul 18 '05 #9
Bart Nessux <ba*********@ho tmail.com> writes:

The problem I have is this: I know too little about thread programming.
If anyone thinks the code I have below could be made to work for my
tasks (probe 65,000 IPs for HTTP servers using threads to speed things
up), then please *show* me how I might change it in order for it to work.


I haven't been following this thread but if I was doing this I would want to
use asynchronous programming. It would finally force me to get to grips with
twisted.

Eddie
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
1547
by: serge calderara | last post by:
Dear all, I have a function that I need to run in a thread due to the fact that it can takes long time to execute according to the amount of data to collect. This function is also populating a treeview control whne collected data gets finished. In order to achieve this I have used the following code : System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf GetListOfReelsFromRemoteDB))
6
2321
by: Tony Proctor | last post by:
Hi everyone We're experiencing some serious anomalies with the scheduling of ASP threads. I'd be interested to hear if anyone knows what algorithm is used (e.g. simple round-robin, or something more sophisticated), and what situations might perturb it. Even a hint as to what would be considered normal scheduling might help. The root of our problem is that we observed a normally well-behaved web application suddenly limit itself to a...
4
1974
by: Leonardo Hyppolito | last post by:
Hello, I am trying to write a multithread program that simulates producers and consumers. My program can have many producers and many consumers (each in a separate thread). It has a storage place (buffer) with "n" capacity. The user provides these parameters on startup. The buffer works with a circular queue. It's a console application. My implementation is working with Semaphores to synchornize everything. I think it's synchornized...
7
2700
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates that. Problem is that when program is started many threads are created (see output section), when only two should be running at any time. Can you please help me to identify me where the problem is? Best regards
20
2392
by: Bob Day | last post by:
Using VS 2003, VB, MSDE... There are two threads, A & B, that continously run and are started by Sub Main. They instantiationsl of identical code. Thread A handles call activity on telephone line 1 and Thread B handles call activity on telephone line 2. They use a common SQL datasource, but all DataSets are unique to each thread. Is there a way for thread A to occasionally communication to thread B that something has happened? ...
7
2683
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
1
2993
by: alundi | last post by:
Greetings: I'd like to post this as a new thread to an article in microsoft.public.dotnet.languages.vb originally made by nevin and replied to by Alan Pretre back in December ("ThreadState == not in the enumeration"). Like nevin, I have a VB.NET multi-threaded application, and quite frequently, after my main application class will call Thread.Suspend() on the thread the ThreadState of the Suspended Thread will be a value of 96. From...
6
6864
by: Sergey Poberezovskiy | last post by:
I have the following code in C# that I have trouble converting to VB(2.0): private delegate void openDialog(); private void openWindowsDialog(openDialog open) { Thread thread = new Thread(new ThreadStart(open)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); }
8
2975
by: Brad Walton | last post by:
Hello. First post, but been doing a bit of reading here. I am working on a project in Java, but decided to switch over to C# after seeing some of the additional features I can get from C#. One of the big changes I want to make is event-driven code (rather than the linear flow I had in Java). I have spent a week or so searching Google, talking to a couple of programming friends, and just chewing on it in my brain. I think I have an ok handle...
0
8427
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8332
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8746
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8525
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.