I am writing a python script which checks for number of active connections for a particular IP / port. For this I use os.system( 'my_command') to grab the output. os.system returns the exit status of the command I've passed it (0 means the command returned without error). How can I store this value which os.system throws to STDOUT in a variable ? So that this variable can used later in the function for counter. Something like subprocess, os.popen can help. Can someone suggest ?
            Asked
            
        
        
            Active
            
        
            Viewed 2.0k times
        
    4 Answers
18
            
            
        a=os.popen("your command").read()
new result stored at variable a :)
 
    
    
        jack-X
        
- 287
- 5
- 14
- 
                    The correct one did not worked for me but this one was perfect! – VicoMan Mar 12 '14 at 08:59
6
            import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = p.communicate()
 
    
    
        agf
        
- 171,228
- 44
- 289
- 238
- 
                    Would not the third line you mentioned be under parenthesis ? Like, (out, error) = p.communicate() and then say print "the result is: ", out – Ashutosh Narayan Jul 19 '11 at 11:15
- 
                    1No, in Python, you don't need the parenthesis. Tuples can be implicitly created and automatically packed and unpacked. Yes, you can then do `print 'The output was', out, 'and the error was', error` – agf Jul 19 '11 at 11:18
- 
                    OK, got that. Is this is the right syntax to execute the following netstat command -> result = subprocess.Popen(["netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"], stdout=subprocess.PIPE, stderr= subprocess.PIPE) ? I get an error : File "/usr/lib/python2.7/subprocess.py", line 672, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1202, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory Why am I getting so ? – Ashutosh Narayan Jul 19 '11 at 11:43
- 
                    
- 
                    try this `result = subprocess.Popen('''sh -c "netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"''')` Edit: or try it with `shell=True` as @Jakob-Bowyer suggested below. Needed because you're not just running one command, but instead are using the pipe `|` feature of the shell. – agf Jul 19 '11 at 11:51
- 
                    ``` result = subprocess.Popen(["netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"], stdout=subprocess.PIPE, stderr= subprocess.PIPE) ``` I am accepting IP & Port as raw input from user. – Ashutosh Narayan Jul 19 '11 at 11:56
- 
                    Ah, then you want `result = subprocess.Popen('''netstat -plant | awk '{print $4}' | grep %s:%s | wc -l''' % (ip, port), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)` If this solves your problem, please accept my answer. – agf Jul 19 '11 at 12:04
- 
                    It worked this time, but, I am not getting the value printed in variable "out" when I say ``` out, error = result.communicate() print "the connections are: ", out ``` – Ashutosh Narayan Jul 19 '11 at 12:10
- 
                    What do you get when you do just `print subprocess.Popen('ls | cat', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()`? Something like `('DLLs\nDoc\nLICENSE.txt\nLib\nNEWS.txt\nPIL-wininst.log\nREADME.txt\nRemovePIL.exe\nRemovenumpy.exe\nRemovepywin32.exe\nRemovesetuptools.exe\nScripts\nTools\ninclude\nlibs\nnumpy-wininst.log\npython.exe\npython.exe.self\npythonw.exe\npythonw.exe.bak\npywin32-wininst.log\nsetuptools-wininst.log\ntcl\nw9xpopen.exe\n', '')` ? – agf Jul 19 '11 at 12:13
1
            
            
        import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, error = p.communicate()
 
    
    
        Jakob Bowyer
        
- 33,878
- 8
- 76
- 91
0
            
            
        netstat -plant | awk '{print $4}' | grep %s:%s | wc -l
You can use Python to do the splitting, grepping and counting:
process = subprocess.Popen(['netstat', '-plant'], stdout=subprocess.PIPE)
num_matches = 0
host_and_port = "%s:%s" % (ip, port)
for line in process.stdout:
    parts = line.split()
    if parts[3] == host_and_port: # or host_and_port in parts[3]
        num_matches += 1
print num_matches
 
    
    
        Rosh Oxymoron
        
- 20,355
- 6
- 41
- 43
- 
                    This also solves my problem ; but @agf 's answer was a one liner – Ashutosh Narayan Jul 19 '11 at 13:30
