What Command to Use in Command Prompt to Run Python Script

Linux is one of the about popular operating systems used by software developers and system administrators. Information technology is open-source, free, customizable, very robust, and adaptable. Making information technology an ideal choice for servers, virtual machines (VMs), and many other employ cases.

Therefore, it is essential for anyone working in the tech manufacture to know how to work with Linux because it is used almost everywhere. In this tutorial, nosotros are going to expect at how we can automate and run Linux commands in Python.

Table of contents

  • Prerequisites
  • Introduction
  • Building An Application to Ping Servers
  • Lawmaking
  • Conclusion

Prerequisites

  • Basic understanding of Linux and crush scripting.
  • Basic programming skills in Python.

Introduction

Python has a rich set of libraries that allow us to execute crush commands.

A naive approach would be to use the os library:

                          import              os cmd              =              'ls -l'              bone.system(cmd)                      

The bone.system() function allows users to execute commands in Python. The programme in a higher place lists all the files inside a directory. Nonetheless, we can't read and parse the output of the command.

In some commands, it is imperative to read the output and clarify it. The subprocess library provides a ameliorate, safer, and faster approach for this and allows us to view and parse the output of the commands.

OS subprocess
os.system role has been deprecated. In other words, this function has been replaced. The subprocess module serves as a replacement to this and Python officially recommends using subprocess for shell commands.
os.system direct executes trounce commands and is susceptible to vulnerabilities. The subprocess module overcomes these vulnerabilities and is more secure.
The os.system office simply runs the beat out command and but returns the status code of that command. The subprocess module returns an object that can be used to get more information on the output of the command and kill or terminate the command if necessary. This cannot be done in the os module.

Although y'all can execute commands using the OS module, the subprocess library provides a better and newer approach and is officially recommended. Therefore, we are going to use subprocess in this tutorial. This documentation explores the motivation behind creating this module.

Building an application to ping servers

Allow's apply the subprocess library to write a script that pings multiple servers to see whether they are reachable or not. This would be a good use case when you have multiple hosts, servers, or VMs(AWS ec2 instances) and desire to bank check if they are up and running without any problems.

A simple solution is to merely ping these servers and encounter if they respond to the request. However, when you take a considerable amount of machines, it will be extremely tedious and time-consuming to manually ping them. A improve approach is to use Python to automate this procedure.

Code

Co-ordinate to the official documentation, the subprocess module allows you lot to spawn new processes, connect to their input/output/mistake pipes, and obtain their return codes.

This module intends to replace several older modules and functions. The subprocess library has a class chosen Popen() that allows us to execute shell commands and get the output of the command.

Create a Python file and add together the following lawmaking. We also demand to create a file chosen "servers.txt", where we tin can add a list of all the servers nosotros need to ping. The Python script will read from this file and ping each server listed in it.

Servers

I accept added iv servers, out of which 2 exist and the other 2 do non. Merely the servers that exist can be "pinged".

                          import              subprocess              def              ping(servers):              # The command you desire to execute                            cmd              =              'ping'              # send one packet of data to the host                            # this is specified by '-c 1' in the statement list                            outputlist              =              []              # Iterate over all the servers in the list and ping each server              for              server              in              servers:         temp              =              subprocess.Popen([cmd,              '-c ane', server], stdout              =              subprocess.PIPE)              # get the output as a string              output              =              str(temp.communicate())              # shop the output in the listing              outputlist.append(output)              return              outputlist              if              __name__              ==              '__main__':              # Get the list of servers from the text file              servers              =              list(open up('servers.txt'))              # Iterate over all the servers that nosotros read from the text file              # and remove all the extra lines. This is just a preprocessing stride              # to make sure there aren't any unnecessary lines.              for              i              in              range(len(servers)):         servers[i]              =              servers[i].strip('              \n              ')     outputlist              =              ping(servers)              # Uncomment the following lines to print the output of successful servers              # print(outputlist)                      

Output

As you can run into in the output, we go the message "name or service not known" for the two servers that did not exist.

In the programme above, the ping() part takes a list of servers and returns the output of each running ping control on each server. If a server is unreachable, it displays an output saying "ping: somethingthatdoesntexist: Name or service non known".

The Popen() is a constructor method of the Popen class and takes in the following arguments:

  • A list of commands and whatever additional options these commands might require. For instance, the ls command tin can be used with '-l' option. To execute the ls -50 command, the statement list would look like this: ['ls', '-l']. The commands are specified as strings. In the instance higher up, we employ the ping control with the choice -c ane then that it simply sends one packet of data, and the server replies with a single packet. Without this limit, the command would run forever until an external process stops information technology.

  • The stdout argument is optional and can exist used to gear up where y'all want the subprocess to display the output. By default, the output is sent to the final. All the same, if you don't desire to dump a large output onto the last, you tin can use subprocess.PIPE to send the output of one command to the next. This corresponds to the | option in Linux.

  • The stderr statement is also optional and is used to set where you want the errors to be displayed. By default, it sends the errors to the terminal. Since nosotros need to get a list of servers that cannot be reached, nosotros don't need to change this. The servers that cannot exist reached (error) will be displayed to united states of america on the concluding.

The output of the control is stored in a variable called temp. The communicate() office allows u.s. to read the output and the str part can be used to catechumen it to a cord. Once we get the output, nosotros can parse information technology to extract only the essential details or just display information technology as it is. In this example, I am storing the output in a list for future apply.

Conclusion

In conclusion, automation is one of the hottest topics in the industry, and almost every company is investing huge amounts of money to automate various manual tasks. In this tutorial, we explored the process of automatically running and analyzing Linux commands on multiple hosts using Python.

An one-time way of doing this is by using vanquish scripts. However, using Python gives developers more power and command over the execution and output of the commands. At present that you have understood the basics of executing Linux commands, yous can become ahead and experiment with dissimilar commands and build more complex and robust applications.


Peer Review Contributions by: Saiharsha Balasubramaniam

millenhorwill.blogspot.com

Source: https://www.section.io/engineering-education/how-to-execute-linux-commands-in-python/

0 Response to "What Command to Use in Command Prompt to Run Python Script"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel