How to Execute Shell codes and get their output in Python[ with Code ]

In this tutorial, I will be providing you a code snippet with which u can execute shell codes(or commands in terminal and obtain the output of these commands)


Here, I am using the linux command "ls",which is used to list the files in the given directory

So in terminal we have somthing like this


So Now we will see how the same output can be obtained and stored in a variable in python

So here is the Code snippet

import subprocess
output = subprocess.check_output("ls")
print(output)
In the above code, we first import a module called "subprocess"
 Then we are executing a method called "check_output()" and the result is stored in a variable called "output".

Thus , we can execute and retrieve the output of any shell code executed in python

Now, we run the python script and view the same output

Comments

  1. Hi,
    Great tutorial! But when I try this, I get the following output:

    b'bin\nboot\ndev\netc\nhome\ninitrd.img\ninitrd.img.old\nlib\nlib64\nlost+found\nmedia\nmnt\nopt\nproc\nroot\nrun\nsbin\nsrv\nsys\ntmp\nusr\nvar\nvmlinuz\nvmlinuz.old\n'

    I'm using Python 3.4.

    ReplyDelete

Post a Comment

Popular posts from this blog

Hack Wifi with Fern Wifi Cracker

Linux Shell Script to count no of occurrences of a digit in a number

How to Decompile JAR files and View Source Code of Java Programs