Tuesday, January 20, 2015

Invoke a shell script via python script and print result

1. Create your shell script.
> vi call.sh
Contents:
#!/bin/bash
return_str(){
        echo "shell return"
}

return_str

2. Give executable permission to run the script.
> chmod +x call.sh

Note: 
If you don't give executable permission, following error occurs.
-------------------
Traceback (most recent call last):
  File "invoke.py", line 4, in <module>
    toPrint2 = check_output(['./call.sh'])
  File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied

3. Create your python script.
> vi invoke.py
Contents:
from subprocess import check_output

print "-------------------"
toPrint2 = check_output(['./call.sh'])
print toPrint2


4. Run your python script.
> python invoke.py
-------------------
shell return

Now lets try something advanced. 
Say you have a web server starting in a given port and you want to know as soon as the server comes online.

This is how you do it.

1. Change python script as follows
Content:
from subprocess import call
print "-------------------"
call(['./portListener.sh'], shell="True")

2. Create our new shell script to listen to the port
> vi portListener.sh
Content:
#!/bin/bash
echo -n Please wait... 
while ! echo exit | nc 192.168.92.4 9443; do
echo -n '.';
sleep 1; # Scan for every 1 second interval.
done
echo Server 192.168.92.4 is online on port 9443...

3. Give executable permission to run the script
> chmod +x portListener.sh

4. Run the python script
>  python invoke.py
-------------------
Please wait.............

Here you can see the progress bar in action waiting for the server to become online.

5. Start your server.
Say that it's ip is 192.168.92.4 and running on port 9443. I have used WSO2 ELB 2.1.0 for my testing in a virtual machine environment.
Also make sure that your python script running instance can access this server's network.

6. Once the server becomes online, the script will be completed saying the given server is online.
-------------------
Please wait..............................Server 192.168.92.4 is online on port 9443...

Have fun...