473,608 Members | 2,287 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using select on a unix command in lieu of signal

Hi all,

Another newbie question. So you can't use signals on threads but you
can use select. The reason I want to do this in the first place it I
need a timeout. Fundamentally I want to run a command on another
machine, but I need a timeout. I have to do this to a LOT of machines
( > 3000 ) and threading becomes necessary for timeliess. So I created
a function which works with signals ( until you throw threading at it..
) but I can't seem to modify it correctly to use select. Can some
select ( pun intended ) experts out there point out the error of my
way..

Not working RunCmd using select

def runCmd( self, cmd, timeout=None ):

starttime = time.time()

child = popen2.Popen3(c md)
child.tochild.w rite("\n")
child.tochild.c lose()
child.wait()

results = []
results = "".join(child.f romchild.readli nes())

endtime = starttime + timeout

r, w, x = select.select(r esults, [], [], endtime - time.time())

if len(r) == 0:
# We timed out.
prefix = ("TIMED OUT:" + " " * maxlen)[:maxlen]
sys.stdout.writ e(prefix)
space = ""
os.kill(child.p id,9)
child.fromchild .close()

return results
Working RunCmd using signal

def handler(self, signum, frame):
self.logger.deb ug("Signal handler called with signal %s" %
signum)

def runCmd( self, cmd, timeout=None ):
self.logger.deb ug("Initializin g function %s - %s" %
(sys._getframe( ).f_code.co_nam e,cmd) )

# Set the signal handler and a 5-second alarm
signal.signal(s ignal.SIGALRM, self.handler)
signal.alarm(ti meout)

try:
child = popen2.Popen3(c md)
child.tochild.w rite("y\n")
child.tochild.c lose()
child.wait()

results = "".join(child.f romchild.readli nes())
out = child.fromchild .close()
self.logger.deb ug("command: %s Status: %s PID: %s " % (cmd,
out, child.pid))

if out is None:
out = 0

except:
self.logger.war ning( "command: %s failed!" % cmd)
kill = os.kill(child.p id,9)
self.logger.deb ug( "Killing command %s - Result: %s" %
(cmd, kill))
out = results = None

signal.alarm(0) # Disable the alarm

return out,results

Thanks much - Alternatively if anyone else has a better way to do what
I am trying to get done always looking for better ways. I still want
this to work though..

Aug 29 '05 #1
3 2480
"rh0dium" <sk****@pointci rcle.com> writes:
Thanks much - Alternatively if anyone else has a better way to do what
I am trying to get done always looking for better ways. I still want
this to work though..


You don't have to use select, since you can use timeouts with normal
socket i/o. So you could use threads. 3000 threads is a lot but not
insanely so.
Aug 29 '05 #2

Paul Rubin wrote:
"rh0dium" <sk****@pointci rcle.com> writes:
Thanks much - Alternatively if anyone else has a better way to do what
I am trying to get done always looking for better ways. I still want
this to work though..


You don't have to use select, since you can use timeouts with normal
socket i/o. So you could use threads. 3000 threads is a lot but not
insanely so.


OK I could use the timeout.. but I am using a queue as well. So each
thread gets several commands. I assumed (could be wrong) that if I use
a timeout the whole thread gets killed not the individual process. The
purpose of the queue was to limit the number of concurrent workers, and
keep the load on the machine somewaht manageable.

So to add more to this here is how I call the runCmd

# Initialize a que to 25 max hosts
workQ = Queue.Queue(25)

# Start some threads..
for i in range(MAX_THREA DS):
getReachableHos ts(queue=workQ) .start()

# Now give the threads something to do.. The nice thing here is
that by
# waiting unil now this will hold up the queue..
for host in base_hosts:
workQ.put(host)

# After this is finally done thow a null to close the threads..
for i in range(MAX_THREA DS):
workQ.put(None)

And then getReachables..

class getReachableHos ts(threading.Th read):
def __init__(self,q ueue=None, ):
self.logger = logging.getLogg er("metriX.%s" %
self.__class__. __name__)
self.logger.inf o("Initializi ng class %s" %
self.__class__. __name__)
self.__queue = queue
threading.Threa d.__init__(self )

def run(self):
self.logger.deb ug("Initializin g function %s" %
sys._getframe() .f_code.co_name )
while 1:
host = self.__queue.ge t(timeout=5)
if host is None:
break

self.logger.deb ug("Getting open ports on %s" % host)
command = "nmap -p 22,514 -oG - %s | perl -lane 'print
unless /^#/'" % host

(out,results)=s elf.runCmd(cmd= cmd,timeout=5)
Much appreciate the advice and help!!

Aug 29 '05 #3
So here's how I solved this.. It's seems crude - but hey it works.
select not needed..

def runCmd( self, cmd, timeout=None ):
self.logger.deb ug("Initializin g function %s - %s" %
(sys._getframe( ).f_code.co_nam e,cmd) )
command = cmd + "\n"

child = popen2.Popen3(c ommand)
t0 = time.time()

out = None
while time.time() - t0 < timeout:
if child.poll() != -1:
self.logger.deb ug("Command %s completed succesfully" %
cmd )
out = child.poll()
results = "".join(child.f romchild.readli nes())
results = results.rstrip( )
break
print "Still waiting..", child.poll(), time.time() -
t0, t0
time.sleep(.5)

if out == None:
self.logger.war ning( "Command: %s failed!" % cmd)
kill = os.kill(child.p id,9)
self.logger.deb ug( "Killing command %s - Result: %s" %
(cmd, kill))
out = results = None

else:

self.logger.deb ug("Exit: %s Reullts: %s" % (out,results))

child.tochild.c lose()
child.fromchild .close()
return out,results

Comments..


rh0dium wrote:
Paul Rubin wrote:
"rh0dium" <sk****@pointci rcle.com> writes:
Thanks much - Alternatively if anyone else has a better way to do what
I am trying to get done always looking for better ways. I still want
this to work though..


You don't have to use select, since you can use timeouts with normal
socket i/o. So you could use threads. 3000 threads is a lot but not
insanely so.


OK I could use the timeout.. but I am using a queue as well. So each
thread gets several commands. I assumed (could be wrong) that if I use
a timeout the whole thread gets killed not the individual process. The
purpose of the queue was to limit the number of concurrent workers, and
keep the load on the machine somewaht manageable.

So to add more to this here is how I call the runCmd

# Initialize a que to 25 max hosts
workQ = Queue.Queue(25)

# Start some threads..
for i in range(MAX_THREA DS):
getReachableHos ts(queue=workQ) .start()

# Now give the threads something to do.. The nice thing here is
that by
# waiting unil now this will hold up the queue..
for host in base_hosts:
workQ.put(host)

# After this is finally done thow a null to close the threads..
for i in range(MAX_THREA DS):
workQ.put(None)

And then getReachables..

class getReachableHos ts(threading.Th read):
def __init__(self,q ueue=None, ):
self.logger = logging.getLogg er("metriX.%s" %
self.__class__. __name__)
self.logger.inf o("Initializi ng class %s" %
self.__class__. __name__)
self.__queue = queue
threading.Threa d.__init__(self )

def run(self):
self.logger.deb ug("Initializin g function %s" %
sys._getframe() .f_code.co_name )
while 1:
host = self.__queue.ge t(timeout=5)
if host is None:
break

self.logger.deb ug("Getting open ports on %s" % host)
command = "nmap -p 22,514 -oG - %s | perl -lane 'print
unless /^#/'" % host

(out,results)=s elf.runCmd(cmd= cmd,timeout=5)
Much appreciate the advice and help!!


Aug 30 '05 #4

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

Similar topics

0
1459
by: mkent | last post by:
I'm trying to use signal.alarm to stop a run-away os.system command. Can anyone exlain the following behavior? Given following the trivial program: import os import signal def timeoutHandler(signum, frame): print "Timeout"
1
3379
by: William | last post by:
For the following code snippet: for ( ;; ) { numFDInSet = select( fdmax+1, &readfds, NULL, NULL, &tv ); // ... signal( SIGALRM, alarm_handler ); // ...
1
4006
by: Daveyk0 | last post by:
Hello there, I have a front end database that I have recently made very many changes to to allow off-line use. I keep copies of the databases on my hard drive and link to them rather than the live databases on the network. Is there a way, via code, when I get back in-house from being on the road to click a button, and select the backends I want to link to? I would want to delete all the current links and link to the "live"
6
16374
by: Joseph | last post by:
Hi, I am trying to develop a C# application that will run on Windows that will do the following * Select file name to process * FTP the file to a UNIX server * Process this file on UNIX using a program on UNIX "./pgmname -options Infilename > OutputFilename" * FTP the output of this program back to Windows * Process the resultant file and create output report file
14
1929
by: alsmeirelles | last post by:
Hi, I'm building a multithreaded application and I encountered a tiny and annoying problem. I use a select to wait for data to be read from a socket, after some reads, the select simply blocks and stays that way until I close the connection on the other side of the socket. When the socket is closed on the writer end the select releases and then I get only empty strings from the socket. My question is this: Why did it block? The reading...
7
11067
by: Adrian Casey | last post by:
I have a multi-threaded python application which uses pexpect to connect to multiple systems concurrently. Each thread within my application is a connection to a remote system. The problem is when one of the child threads runs a command which generates an unlimited amount of output. The classic example of this is the "yes" command. If you execute "pexpect.run('yes')", your cpu will sit at 100% forever. Here is a simple multi-threaded...
9
6474
by: Phoe6 | last post by:
Hi all, Consider this scenario, where in I need to use subprocess to execute a command like 'ping 127.0.0.1' which will have a continuous non- terminating output in Linux. # code # This hangs at this point. How should I handle these kind of commands (ping 127.0.0.1) with
5
6635
by: david | last post by:
I'm developing a program that runs using an asyncore loop. Right now I can adequately terminate it using Control-C, but as things get refined I need a better way to stop it. I've developed another program that executes it as a child process using popen2.Popen4(). I was attempting to use signals to stop it (using os.kill()) but I keep running into a problem where sending the signal causes an infinite loop of printing the message...
9
5811
by: thagor2008 | last post by:
Is the behaviour of throwing exceptions in a unix signal handler defined? eg: void sighandler(int sig) { ... do something throw myobj; }
0
8002
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
8475
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...
0
8338
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...
0
6816
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6013
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
5475
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
3962
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4024
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1329
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.