How to use Python Pexpect to Automate Linux Commands?
Last Updated :
14 Jun, 2022
Pexpect is a Python library for spawning child processes and controlling them automatically. Pexpect can be used to automate interactive applications such as SSH, FTP, password, telnet, etc. Pexpect works by spawning child processes and responding to expected patterns.
Installation:
Pexpect can be installed by using the following command.
pip3 install pexpect
Automating Linux commands:
It can be done in different ways:
- Using run() method
- Using spawn class
- Using sendline() method
After the installation let's see how to automate the Linux commands.
Method 1: Using run() method
The pexpect.run() method can be called to execute a command and return its output. This function can be used as a replacement for os.system.
Example:
Python3
import pexpect
print(pexpect.run('echo hello'))
fig 1
Method 2: Using spawn class
Spawn class is the main interface to start a new child process and control it. The string inside spawn can be replaced by the shell command that needs to be executed.
Syntax: pexpect.spawn("rm ./dev")
The important methods of pexpect.spawn class are expect().
Syntax: expect(pattern, timeout=-1, searchwindowsize=-1, async_= False)
This method waits for the child process to return a given string. The pattern specified in the except method will be matched all through the string. The timeout is used to raise pexpect.TIMEOUT. The searchwindowsize parameter is used to set the maxread attribute of the class. Set async_ = True when creating a non-blocking application.
Example:
Python3
import pexpect
# start a child process with spawn
# It just echos geeksforgeeks
child = pexpect.spawn("echo geeksforgeeks")
# prints he matched index of string.
print(child.expect(["hai", "welcome", "geeksforgeeks"]))
Output:
fig 2
The example prints the index that matches the child process.
Method 3: Using sendline(s = " ")
This method writes the string to the child process and also returns the number of bytes written. It appears to the child process as someone is typing from the terminal.
Example:
Python3
import pexpect
# Start a child process with spawn
# This process waits for the input
# form user
child = pexpect.spawn("cat")
# The input to the cat process is sent
# by the sendline()
child.sendline("hai geek")
# prints the index of matched string
# expressing with child process
print(child.expect(["hello", "hai geek"]))
Output:
fig 3
Let's see a complex example for better understanding. Here where will use the FTP client to login into ftp.us.debian.org and download welcome.msg file and print the file. Here we are going to use an FTP client to login and download files from a remote machine and then print.
Approach:
- Import pexpect.
- spawn a child with pexpect.spawn('ftp ftp.us.debian.or').
- FTP client asks for the user name. Match the pattern with expect('Name .*: ')
- Send the username to the child process with sendline method.
- Then the FTP client asks for the password. Match the pattern with expect('Password: ')
- Then the serve logged in. Then you can download files.
- Detect whether you can send the command to the FTP server by the presence of 'ftp> '.
- Then send the command by sendline('get welcome.msg'), this just downloads the file to the local machine.
- Then close the FTP client by using the 'bye' command.
- Finally, print all the interactions with the child process with the child.before. It returns a byte string, decodes it before printing it.
- Use pexpect.run to print the content of the downloaded file from the FTP server.
Python3
import pexpect
def main():
# spawn a child process.
child = pexpect.spawn('ftp ftp.us.debian.org')
# search for the Name pattern.
child.expect('Name .*: ')
# send the username with sendline
child.sendline('anonymous')
# search for the Password pattern
child.expect('Password:')
# send the password to the childprocess
# by sendline
child.sendline('anonymous@')
# detect ftp accepts command from user
# by 'ftp> ' pattern
child.expect('ftp> ')
# If it accepts command then download the
# welcome.msg file from the ftp server
child.sendline('get welcome.msg')
# again check whether ftp client accepts
# command from user by 'ftp> ' pattern
child.expect('ftp> ')
# close the ftp client.
child.sendline('bye')
# print the interactions with the child
# process.
print(child.before.decode())
child.interact()
# print the downloaded file by executing cat
# command with pexpect.run method
print(pexpect.run('cat ./welcome.msg').decode())
if __name__ == '__main__':
main()
Output:
Fig 4
Similar Reads
Automating some git commands with Python
Git is a powerful version control system that developers widely use to manage their code. However, managing Git repositories can be a tedious task, especially when working with multiple branches and commits. Fortunately, Git's command-line interface can be automated using Python, making it easier to
3 min read
How to Automate VPN to change IP location on Ubuntu using Python?
To Protect Our system from unauthorized users Access you can spoof our system's IP Address using VPN service provided by different organizations. You can set up a VPN on your system for free. Â After you set up and log in to the VPN over the Ubuntu system you need to manually connect with different
3 min read
Python | How to Parse Command-Line Options
In this article, we will discuss how to write a Python program to parse options supplied on the command line (found in sys.argv). Parsing command line arguments using Python argparse module The argparse module can be used to parse command-line options. This module provides a very user-friendly synta
3 min read
How to Automate an Excel Sheet in Python?
Before you read this article and learn automation in Python, let's watch a video of Christian Genco (a talented programmer and an entrepreneur) explaining the importance of coding by taking the example of automation.You might have laughed loudly after watching this video, and you surely might have u
8 min read
Python | Execute and parse Linux commands
Prerequisite: Introduction to Linux Shell and Shell Scripting Linux is one of the most popular operating systems and is a common choice for developers. It is popular because it is open source, it's free and customizable, it is very robust and adaptable. An operating system mainly consists of two par
6 min read
How to Use Pytest for Efficient Testing in Python
Writing, organizing, and running tests is made easier with Pytest, a robust and adaptable testing framework for Python. Developers looking to guarantee code quality and dependability love it for its many capabilities and easy-to-use syntax. A critical component of software development is writing tes
5 min read
Automated SSH bot in Python
In this article, we are going to see how we can use Python to Automate some basic SSH processes. What is SSH? SSH stands for Secure Shell or Secure Socket Shell, in simple terms, it is a network communication protocol used to communicate between two computers and share data among them. The main feat
8 min read
How to Execute Shell Commands in a Remote Machine in Python?
Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be a master machine from which command can be sent and one or more slave machines that execute the received commands. Getting Started We wi
3 min read
How to parse boolean values with `argparse` in Python
Command-line arguments are a powerful feature of many programming languages, including Python. They allow developers to specify options or parameters when running a script, making it more flexible and customizable. However, the process of parsing these arguments can be a tedious and error-prone task
5 min read
How To Embed Python Code In Batch Script
Embedding Python code in a batch script can be very helpful for automating tasks that require both shell commands and Python scripting. In this article, we will discuss how to embed Python code within a batch script. What are Batch Scripts and Python Code?Batch scripts are text files containing a se
4 min read