Shell commands in python linux

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.

Читайте также:  Каким процессом занята папка 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.

Источник

How to Execute Shell Commands in Linux with Python: A Comprehensive Guide

Learn how to automate repetitive tasks in system administration by executing shell commands in Linux with Python. Explore different methods and get examples.

  • Using the ’os’ module to run shell commands in Python
  • Using the ‘subprocess’ module to run external commands in Python
  • Running Shell Commands using Python (Detailed Explanation)
  • Running Unix external programs with Python
  • Running shell commands in Python over SSH
  • Executing shell commands in IPython terminal
  • Other simple code samples for executing shell commands in Python on Linux
  • Conclusion
  • How do I run a Python command in Linux terminal?
  • How do I run a Python command in shell?
  • How to use Linux commands in Python?
  • Can I use shell commands in Python?
Читайте также:  Смонтировать файловую систему linux

Python is a popular language for automation, particularly in system administration. It can be used to execute shell commands in Linux, which is particularly useful for automating repetitive tasks. In this blog post, we will explore the different ways to execute shell commands in Linux using Python.

Using the ’os’ module to run shell commands in Python

The ’os’ module in Python provides functions to run shell commands and get the output. This module is included in Python’s standard library and doesn’t require any external installation.

The os.system() method

One of the simplest ways to execute shell commands in python is to use the os.system() method. This method runs the command as a sub-process and returns the exit status of the process.

import os# executing ls command os.system('ls') 

However, the os.system() method doesn’t allow capturing the output of the command.

The os.popen() method

The os.popen() method is another way to execute shell commands in Python. This method runs the command as a sub-process and returns a file object that can be used to read the output of the command.

import os# executing ls command output = os.popen('ls').read() print(output) 

This method allows capturing the output of the command, but it has some limitations, such as buffering issues and security vulnerabilities.

Using the ‘subprocess’ module to run external commands in Python

The subprocess module is a more effective way to run external commands in Python. It provides more control over the execution of the command and allows capturing the output of the command.

The subprocess.Popen() method

The subprocess.Popen() method can be used to execute shell commands in Python. This method creates a new process and returns a Popen object that can be used to interact with the process.

import subprocess# executing ls command process = subprocess.Popen(['ls'], stdout=subprocess.PIPE) output, error = process.communicate() print(output.decode('utf-8')) 

This method allows capturing the output of the command and even passing arguments to the command.

Running Shell Commands using Python (Detailed Explanation)

In this video, learn how to run shell commands using Python. This is useful when your python Duration: 29:42

Running Unix external programs with Python

The system() method in the os module can also be used to run Unix external programs. This method runs the command as a sub-process and returns the exit status of the process.

import os# executing grep command os.system('grep -r "pattern" /path/to/directory') 

We can pass arguments to the program and capture its output using the os.popen() method.

Читайте также:  Linux mint grub repair

Running shell commands in Python over SSH

The system() method in the os module can be used to execute shell commands with python over SSH. This method runs the command as a sub-process on the remote machine and returns the exit status of the process.

import os# executing ls command on remote machine os.system('ssh user@remote_machine "ls"') 

We can also use the paramiko module to access the remote machine and execute shell commands.

import paramikossh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('remote_machine', username='user', password='password')stdin, stdout, stderr = ssh.exec_command('ls') output = stdout.readlines() print(output)ssh.close() 

Executing shell commands in IPython terminal

IPython allows executing shell commands directly from within its terminal. This is particularly useful for executing Linux commands and shell scripts.

Other simple code samples for executing shell commands in Python on Linux

In Python case in point, os run shell command python code example

In Python as proof, python run shell command code sample

import subprocess process = subprocess.Popen(['echo', 'More output'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() stdout, stderr 

In Python , for example, run linux command using python code sample

import subprocess subprocess.call("command1") subprocess.call(["command1", "arg1", "arg2"])

In Python case in point, how to run linux command in python code example

import os cmd = 'your command here' os.system(cmd) 

In Python , for instance, how to run shell command in python code example

import subprocessprocess = subprocess.Popen(['echo', 'hi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() print(out) # hi print(err) # None

In Python , for example, command for python shell code sample

write python and press enter in terminal. A Python Prompt comprising of three greater-than symbols >>> appears.

In Shell , in particular, python run shell command code example

# First, install python or python3. sudo apt-get install python #or sudo apt-get install python3# Then, run your python file. python /path-to-file/pyfile.py #or python3 /path-to-file/pyfile.py #Example python /home/person/randomfile.py #or python3 /home/person/randomfile.py# Hope this helped :)

Conclusion

Python can be used to execute shell commands in Linux using the os and subprocess modules. These modules offer more functionality and control than traditional methods such as os.system() . Python is a popular language for automation and can be used to automate repetitive tasks in system administration. A cheatsheet or reference guide can be helpful for beginners and advanced users.

Источник

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