Python how to execute linux command

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.

@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.

Читайте также:  Linux загрузочная флешка win

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).

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 execute a UNIX command in Python script

I have a simple python scripts like the above. When I attempt to execute it I get a syntax error when trying to output the name variable.

Why did you expect a generic unix command ( echo ) to be supported just like that in Python as if it was a recognized Python statement?

@C2H5OH It just yields a generic “syntax error”, as echo is not a keyword and it expects something else to happen after a possible variable name (for example an assignment).

@poke: Thanks, I already knew that. I was only trying to improve the OP’s manners when asking questions.

@C2H5OH Already thought you did, but to be fair, “syntax error” is as exact as possible in this case ^^

2 Answers 2

You cannot use UNIX commands in your Python script as if they were Python code, echo name is causing a syntax error because echo is not a built-in statement or function in Python. Instead, use print name .

To run UNIX commands you will need to create a subprocess that runs the command. The simplest way to do this is using os.system() , but the subprocess module is preferable.

you can also use subprocess module.

import subprocess proc = subprocess.Popen(['echo', name], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) (out, err) = proc.communicate() print out 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Shutdown oracle on linux

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Executing Shell Commands with Python

A sysadmin would need to execute shell commands in Python scripts. Learn how to execute shell commands in Python.

Python is an excellent scripting language. More and more sysadmins are using Python scripts to automate their work.

Since the sysadmin tasks involve Linux commands all the time, running Linux commands from the Python script is a great help.

In this tutorial, I’ll show you a couple of ways you can run shell commands and get its output in your Python program.

Execute Shell command in Python with os module

Let me create a simple python program that executes a shell command with the os module.

import os myCmd = 'ls -la' os.system(myCmd)

Now, if I run this program, here’s what I see in the output.

python prog.py total 40 drwxr-xr-x 3 abhishek abhishek 4096 Jan 17 15:58 . drwxr-xr-x 49 abhishek abhishek 4096 Jan 17 15:05 .. -r--r--r-- 1 abhishek abhishek 456 Dec 11 21:29 agatha.txt -rw-r--r-- 1 abhishek abhishek 0 Jan 17 12:11 count -rw-r--r-- 1 abhishek abhishek 14 Jan 10 16:12 count1.txt -rw-r--r-- 1 abhishek abhishek 14 Jan 10 16:12 count2.txt --w-r--r-- 1 abhishek abhishek 356 Jan 17 12:10 file1.txt -rw-r--r-- 1 abhishek abhishek 356 Dec 17 09:59 file2.txt -rw-r--r-- 1 abhishek abhishek 44 Jan 17 15:58 prog.py -rw-r--r-- 1 abhishek abhishek 356 Dec 11 21:35 sherlock.txt drwxr-xr-x 3 abhishek abhishek 4096 Jan 4 20:10 target

That’s the content of the directory where prog.py is stored.

If you want to use the output of the shell command, you can store it in a file directly from the shell command:

import os myCmd = 'ls -la > out.txt' os.system(myCmd)

You can also store the output of the shell command in a variable in this way:

import os myCmd = os.popen('ls -la').read() print(myCmd)

If you run the above program, it will print the content of the variable myCmd and it will be the same as the output of the ls command we saw earlier.

Читайте также:  Executable files extension in linux

Now let’s see another way of running Linux command in Python.

Execute shell command in Python with subprocess module

A slightly better way of running shell commands in Python is using the subprocess module.

If you want to run a shell command without any options and arguments, you can call subprocess like this:

import subprocess subprocess.call("ls")

The call method will execute the shell command. You’ll see the content of the current working directory when you run the program:

python prog.py agatha.txt count1.txt file1.txt prog.py target count count2.txt file2.txt sherlock.txt

If you want to provide the options and the arguments along with the shell command, you’ll have to provide them in a list.

import subprocess subprocess.call(["ls", "-l", "."])

When you run the program, you’ll see the content of the current directory in the list format.

Now that you know how to run shell command with subprocess, the question arises about storing the output of the shell command.

For this, you’ll have to use the Popen function. It outputs to the Popen object which has a communicate() method that can be used to get the standard output and error as a tuple. You can learn more about the subprocess module here.

import subprocess MyOut = subprocess.Popen(['ls', '-l', '.'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout,stderr = MyOut.communicate() print(stdout) print(stderr)

When you run the program, you’ll see the stdout and stderr (which is none in this case).

python prog.py total 32 -r--r--r-- 1 abhishek abhishek 456 Dec 11 21:29 agatha.txt -rw-r--r-- 1 abhishek abhishek 0 Jan 17 12:11 count -rw-r--r-- 1 abhishek abhishek 14 Jan 10 16:12 count1.txt -rw-r--r-- 1 abhishek abhishek 14 Jan 10 16:12 count2.txt --w-r--r-- 1 abhishek abhishek 356 Jan 17 12:10 file1.txt -rw-r--r-- 1 abhishek abhishek 356 Dec 17 09:59 file2.txt -rw-r--r-- 1 abhishek abhishek 212 Jan 17 16:54 prog.py -rw-r--r-- 1 abhishek abhishek 356 Dec 11 21:35 sherlock.txt drwxr-xr-x 3 abhishek abhishek 4096 Jan 4 20:10 target None

I hope this quick tip helped you to execute shell command in Python programs. In a related quick tip, you can learn to write list to file in Python.

If you have questions or suggestions, please feel free to drop a comment below.

Источник

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