Python in Unix
How to run command on unix
Commands cannot be run directly on a unix server like we do in shell script.
SYNTAX:
- system("Command")
- check_output("Command", shell=True)
- call("Command", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
Diff:
1.Will print the output on screen, can store this in a variable but additional “0” will come on newline
- Output will not come on the screen. Can store it in a variable and print it. However, extra newline character come with it.
- It gives status of the command. Whether command was successfully executed or not.
e.g:
***********************
#!/usr/bin/python
import subprocess
os.system("ls –ltr /tmp”)
***********************
Using output from subprocess:
output=subprocess.check_output("command", shell=True)
Caution:the result stored in output is not Boolean so you can’t compare it in if statement. Below code will not work correctly. Also, the output is having change line character in the end.
Below Code will not work
***************************
#!/usr/bin/python
import subprocess
output=subprocess.check_output("grep -i noexec_user_stack_log /etc/system | wc -l", shell=True)
if output == 0:
print("Correct")
else:
print("Incorrect")
**************************
Correct code is:
*************************
#!/usr/bin/python
import subprocess
exit_code = subprocess.call("grep -i noexec_user_stack_log /etc/system | wc -l", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if exit_code == 0:
print("Correct")
else:
print("Incorrect")
**************************
Making it simple by use of function:
from subprocess import PIPE, Popen
def cmdline(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return process.communicate()[0]
print cmdline("cat /etc/host")
print cmdline('ls -ltr')
print cmdline('grep "max" /etc/system')
print cmdline('nslookup google.com')
How to use variable in commands
Simply using a variable inside os.system will not work.
e.g:
*******************
#!/usr/bin/python
import os,sys
FILE=sys.argv[1]
os.system("ls -ltr /tmp")
os.system('chmod 750 /tmp/%(FILE)s' % locals())
******************
How to assign unix command output to a variable and use it
When we store output from subprocess.check_output in a variable, it also stores newline character with the output. We need to remove it first then we can add any string or variable after that to print in same line.
*******************
#!/usr/bin/python
import subprocess,os,sys
SERVER=subprocess.check_output("hostname", shell=True)
LUN_ID=sys.argv[1]
cmd="zp{}".format(SERVER).strip()
cmd="{}_zpool_fs {}".format(cmd,LUN_ID)
print cmd
*******************