If you wanted to run bash shell commands inside of a script (python), how would you do it;
beginner here :)

Thanks for the input,

RHCE

There are different ways. The old simple way is

os.system("mycommand")

Now it's considered better to write

import subprocess
child = subprocess.Popen("mycommand", shell = True)

You could add pipe arguments to write into your command's stdin and read from it's stdout or stderr (see the documentation of the subprocess module) like this

import subprocess
child = subprocess.Popen("mycommand", shell=True, stdin = subprocess.PIPE)
child.stdin.write("hello my command\n")

I like very much the 3rd way, wich gives you the exit status of the command and also it's output like in a terminal

from commands import getstatusoutput
status, output = getstatusoutput("mycommand")
if status:
    print "mycommand failed with exit status %d" % status
else:
   print "mycommand exited normally"
if output:
    print output

Thank you, very helpful! Do you have any sources that I could read up on that helped you?

Is there a way to launch firefox with specific url?

child = subprocess.Popen("firefox", shell = True)

???

thank you for the help, the browser module is a perfect solution :)

Can you help me with this? :

File /usr/lib/python2.4/subprocess.py", line 542, in __init__errread, errwrite)
File "/usr/lib/python2.4/subprocess.py", Line 975, in_execute_chile raise child_execption

My guess is that there may be too many child process' or not an "in __init__ statemen"t at the beginning of my code????

Thanks for everything.

I looked into my subprocess.py. I think the execution of the child process failed for some reason. If you can do that, try to run the other process from a terminal to see if something goes wrong. What was the command passed to Popen ?

Simple iptables check. Are you familiar with iptables?

SSH D8 = subprocess.Popen("iptables --line-numbers -vnL | grep [1:5] | grep sshd")
if D8 :
print "Deliverable 8 Success 10 of 10"
else:
print "0 of 10, check INPUT chain"

* I understand that the spaceing is off, but it is because of the quote box

I think that when you use Popen with a linux pipeline, you must put the argument shell=True to the call to Popen. See if it works. Otherwise, no, I'm not familiar with iptables.

* I understand that the spaceing is off, but it is because of the quote box

Instead of quote use code tags:
[code=python] The code goes in here and doesn't lose formatting

[/code]

My script runs all the way through but doesn't catch the errors. Can you tell me if this is sytacticaly correct?

D1 = webbrowser.open("http://www.yahoo.com")

if D1 :
        print "Deliverable 1 Success 10 of 10"
else:
        print "0 of 10, check http access"

AND

#Verify only stat:ESTABLISHED traffic is going through INPUT chain
D3 = subprocess.Popen("iptables --line-numbers -vnL | grep [1:5] | grep RELATED,ESTABLISHED", shell = True)
if D3 :
        print "Deliverable 3 Success 10 of 10"
else:
        print "0 of 10, check INPUT chain"

Basically for the second example, it is supposed to print "0 of 10" but prints "Deliverable 3 Success..." The IF statement is not doing it's job :(

Thank you

I don't understand your if statement. The call to subprocess.Popen returns a subprocess.Popen object, which will always be non zero. If you want to check the output, you should probably use the technique used here http://www.python.org/doc/2.5.2/lib/node535.html
wiht the stdout=subprocess.PIPE argument and the call to communicate .

What does this mean?

output = p2.communicate()[0]

communicate reads data from the subprocess stdout and stderr. It returns a pair of strings, so output = p2.communicate()[0] means wait until the child process is done and read the output which it sent to stdout. Communicate can also send data to the child's stdin if you declare stdin = subprocess.PIPE in the call to Popen.

Here is a complete example:

# FILE fooo.py
import sys
s = sys.stdin.read()
print s.upper()
raise Exception

#  FILE bar.py
import subprocess as SP

child = SP.Popen("python fooo.py", shell=True,
          stdin=SP.PIPE, stdout=SP.PIPE, stderr=SP.PIPE)

theInput = "Give me bacon and eggs, said the other man"
theOutput, theError = child.communicate(theInput)

print("--> theOutput was %s" % repr(theOutput))
print("--> theError was %s" % repr(theError))

And here is my result in a terminal

[~] python bar.py
--> theOutput was 'GIVE ME BACON AND EGGS, SAID THE OTHER MAN\n'
--> theError was 'Traceback (most recent call last):\n  File "fooo.py", line 6, in <module>\n    raise Exception\nException\n'
[~]

Thank you, that helps. But it's just a stepping stone.

can you explain the

%s" %

?

I've combined both idea's :

#!/usr/bin/python


import subprocess as SP



D3 = SP.Popen("ifconfig eth0", shell=True,
        stdout=SP.PIPE, stderr=SP.PIPE)

#theInput = "10.0.0.12"
theOutput, theError = D3.communicate()

print("> theOutput was %s" % repr(theOutput))
print("> theError was %s" % repr(theError))

The Return is :

> theOutput was 'eth0      Link encap:Ethernet  HWaddr 00:0B:DB:62:1F:90  \n          inet addr:10.0.0.12  Bcast:10.0.0.255  Mask:255.255.255.0\n          inet6 addr: fe80::20b:dbff:fe62:1f90/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:188208 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:837379 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:100 \n          RX bytes:57320230 (54.6 MiB)  TX bytes:155304040 (148.1 MiB)\n          Base address:0xdc80 Memory:ff6e0000-ff700000 \n\n'
> theError was ''

It looks really jumbled is there a way to compact it down?

Instead of printing the repr of the string you can write

print("> theOutput was")
print (theOutput)

the % is a string formatting operation.

Assuming theOutput is a string, you could write

if theOutput == "10.0.0.2":
    print("correct")
else:
    print("incorrect")

The following is returning "incorrect", when in fact it should call "correct"?? :

#!/usr/bin/env python


import subprocess as SP



D3 = SP.Popen("ifconfig eth0 | grep 10.0.0.12 | cut -c 21-29", shell=True,
	stdin=SP.PIPE, stdout=SP.PIPE, stderr=SP.PIPE)

#theInput = "10.0.0.12" 
#theOutput, theError = D3.communicate()
theOutput = D3.communicate()

#print("> theOutput was %s" % repr(theOutput))
#print("> theError was %s" % repr(theError))
if theOutput == "10.0.0.12" :
	print ("correct")
else:
	print ("incorrect")

The following command (used in the code).... :

ifconfig eth0 | grep 10.0.0.12 | cut -c 21-29"

....pulls the "correct" number 10.0.0.12. but the if statement seems to overlook this. Any suggesstions?

Assuming theOutput is a string

Better yet, How do I put "theOutput" into string format?

print '%s' % theOutput

Or in most cases print theOutput

I'm sorry I don't need to necesarilly "print" theOutput, but if it matches what I'm looking for (10.0.0.12) then print correct or incorrect. Make sense? I have this :

#!/usr/bin/env python


import subprocess as SP



D3 = SP.Popen("ifconfig eth0 | grep 10.0.0.12 | cut -c 21-29", shell=True,
        stdin=SP.PIPE, stdout=SP.PIPE, stderr=SP.PIPE)

#theInput = "10.0.0.12"
#theOutput, theError = D3.communicate()
theOutput = D3.communicate()

#print("> theOutput was %s" % repr(theOutput))
#print("> theError was %s" % repr(theError))
if theOutput == "10.0.0.12" :
        print ("correct")
else:
        print ("incorrect")

So uncomment the print statements for theOutput and verify first that you're getting what you want.

Post here the output of this program for us.

Hey, sorry I've been away for a couple of days, hope all is well. My script is working pretty good right now. Thanks so much for the help. In about week I'll be ready to post it.

But for the meanwhile if I had this:

grade = 0
print "Final grade is 'grade' out of 100

I want it to look like this:

Final grade is 0 out of 100
*I know, stupid question.

if you want to print a variable in the middle of a print statement there are two ways to do it.

grade = 0
print "Final grade is",grade,"out of 100"

OR

grade = 0 
print "Final grade is %i out of 100" %grade

Hope that helps.

if you want to print a variable in the middle of a print statement there are two ways to do it.

grade = 0
print "Final grade is",grade,"out of 100"

OR

grade = 0 
print "Final grade is %i out of 100" %grade

Hope that helps.

Thanks for the quick reply

Back again :)

if I do a raw _input :

raw_input('What is your id?')

How do I assign the answer to a variable for future use?

String?

Thanks,

This article has been dead for over six months. Start a new discussion instead.