Call linux command in python

How to call a shell script from python code?

Where test.sh is a simple shell script and 0 is its return value for this run.

Note: it’s preferable to pass subprocess.call() a list rather than a string (see command to Hugo24 below for the example and reasons).

This gives: OSError: [Errno 13] Permission denied. my script does not required to run with sudo. @Manoj Govindan

@alper go the folder where you have placed the script and run the command, chmod +x script.sh . Note: script.sh is a placeholder for your script, replace it accordingly.

There are some ways using os.popen() (deprecated) or the whole subprocess module, but this approach

import os os.system(command) 

why isn’t this the most upvoted answer? Isn’t not having to import a module the better solution? Must be some drawback here?

With subprocess you can manage input/output/error pipes. It is also better when you have many arguments — with os.command() you will have to create whole command line with escaping special characters, with subprocess there is simple list of arguments. But for simple tasks os.command() may be just sufficient.

To quote from that link: The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; *using that module is preferable to using this function.*

In case you want to pass some parameters to your shell script, you can use the method shlex.split():

import subprocess import shlex subprocess.call(shlex.split('./test.sh param1 param2')) 

with test.sh in the same folder:

#!/bin/sh echo $1 echo $2 exit 0 
$ python test.py param1 param2 

Assuming test.sh is the shell script that you would want to execute

Use the subprocess module as mentioned above.

Читайте также:  Linux can create thread

Note: calling subprocess with a list is safer since it doesn’t necessitate passing the (potentially unsanitized) string through a shell for parsing/interpretation. The first item in the list will be the executable and all other items will be passed as arguments.

I’m running python 3.5 and subprocess.call([‘./test.sh’]) doesn’t work for me.

I give you three solutions depends on what you wanna do with the output.

1 — call script. You will see output in your terminal. output is a number.

import subprocess output = subprocess.call(['test.sh']) 

2 — call and dump execution and error into string. You don’t see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn’t work for me.

import subprocess from subprocess import Popen, PIPE session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE) stdout, stderr = session.communicate() if stderr: raise Exception("Error "+str(stderr)) 

3 — call script and dump the echo commands of temp.txt in temp_file

import subprocess temp_file = open("temp.txt",'w') subprocess.call([executable], stdout=temp_file) with open("temp.txt",'r') as file: output = file.read() print(output) 

Don’t forget to take a look at the doc subprocess

Источник

Execute shell commands in Python

I’m currently studying penetration testing and Python programming. I just want to know how I would go about executing a Linux command in Python. The commands I want to execute are:

echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080 

If I just use print in Python and run it in the terminal will it do the same as executing it as if you was typing it yourself and pressing Enter ?

6 Answers 6

You can use os.system() , like this:

os.system('echo 1 > /proc/sys/net/ipv4/ip_forward') os.system('iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080') 

Better yet, you can use subprocess’s call, it is safer, more powerful and likely faster:

from subprocess import call call('echo "I like potatos"', shell=True) 

Or, without invoking shell:

If you want to capture the output, one way of doing it is like this:

import subprocess cmd = ['echo', 'I like potatos'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) o, e = proc.communicate() print('Output: ' + o.decode('ascii')) print('Error: ' + e.decode('ascii')) print('code: ' + str(proc.returncode)) 

I highly recommend setting a timeout in communicate , and also to capture the exceptions you can get when calling it. This is a very error-prone code, so you should expect errors to happen and handle them accordingly.

Читайте также:  A4tech mouse driver linux

@binarysubstrate, deprecated as in not supported or not available? I’ve been recently working on machine with 2.7 (not by choice), and os.system still works.

With Python 3.4 the shell=True has to be stated otherwise the call command will not work. By default call will try to open a file specified by the string unless the shell=True is set. It also looks like that in Python 3.5 call is replaced with run

The first command simply writes to a file. You wouldn’t execute that as a shell command because python can read and write to files without the help of a shell:

with open('/proc/sys/net/ipv4/ip_forward', 'w') as f: f.write("1") 

The iptables command is something you may want to execute externally. The best way to do this is to use the subprocess module.

import subprocess subprocess.check_call(['iptables', '-t', 'nat', '-A', 'PREROUTING', '-p', 'tcp', '--destination-port', '80', '-j', 'REDIRECT', '--to-port', '8080']) 

Note that this method also does not use a shell, which is unnecessary overhead.

import os os.system("your command here") 

This isn’t the most flexible approach; if you need any more control over your process than «run it once, to completion, and block until it exits», then you should use the subprocess module instead.

As a general rule, you’d better use python bindings whenever possible (better Exception catching, among other advantages.)

For the echo command, it’s obviously better to use python to write in the file as suggested in @jordanm’s answer.

For the iptables command, maybe python-iptables (PyPi page, GitHub page with description and doc) would provide what you need (I didn’t check your specific command).

Читайте также:  Cmd on kali linux

This would make you depend on an external lib, so you have to weight the benefits. Using subprocess works, but if you want to use the output, you’ll have to parse it yourself, and deal with output changes in future iptables versions.

Источник

How to call a linux command in Python without waiting for the results (Linux) [duplicate]

Is there a way to call a linux shell commands via Python without having to wait for its completion? I have seen threads to do that in a Windows environment, but not for Linux (Raspbian).

2 Answers 2

from subprocess import Popen process = Popen(['sleep', '10']) print 'Returned immediately!' 

@user1688175 — doubtful. The subprocess is likely created as a child of the python process. When a parent gets killed, the child dies with it. You can however, atexit.register(process.wait) — Now python will wait for that process to complete before the python process exits.

I actually would like to start a C application which monitors the python application. For instance I want to capture if the python application is up. Do you have any idea how to start both applications independently and automatically during the boot?

@user1688175 — Nope, that’s beyond my sys-admin skills. It seems like the two should be started together (e.g. via a shell script) rather than having a python script start a C program that monitors the python script. But I’ve not ever set up a shell script to execute during system boot — Although I imagine that it shouldn’t be too hard to find a post somewhere on the internet demonstrating how to do that.

FYI: I found it! In the Raspian,you have to edit the /etc/rc.local file and add both commands followed by a » &» before the instruction «exit 0».

Источник

Оцените статью
Adblock
detector