How to Use pexpect in Python

pexpect is a popular Python module for doing different types of automated tasks. Different types of interactive applications such as telnet, ssh, ftp, etc., can be automated using this module. It is a pure Python module, and it does not require a C compiler or TCL or Expect extensions like others expect modules. It can work easily by using a Python interpreter only.  This module can be used in two ways. One way is to use the run() function, and another way is to use spawn class. The run() function is easy to use than the spawn class and performs the automated tasks quickly. The particular command or a program can be executed by the run() function that returns the output. This function can be used as the alternative to the os.system() function. The spawn class is more powerful than the run() function that can spawn a child program, interact with it by sending input, and waiting for the response. This module is installed in python3 by default. The two ways of using this module have shown in this tutorial.

Using run() function


The syntax of the run() function is given below.  It has many arguments for various purposes. But the first 3 or 4 arguments are mostly used. The first argument of this function is mandatory that takes the command that this function will execute. It can return multiple outputs. If the withexitstatus argument is used with the False value, it will only return the command’s output.

run(command, timeout=30, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, **kwargs)

Example-1: Different uses of run() function

Three different uses of the run() function have shown in the following script. The `pwd` command’s output is executed in the first run() function that will display the current working directory path. Next, the run() function is used to determine the details of a particular file, and the filename will be taken from the user. The third run() function is used to make the ssh connection and retrieve all files and folders from the web folder.

# Import pexpect module

import pexpect

import os

# Run simple command

print("The current working directory: \n%s"'pwd').decode("utf-8"))

# Retrieve the information of a particular file

filename = input("Enter an existing filename: ")

# Check the file exists or not

if os.path.exists(filename):

    output ="ls -l "+filename, withexitstatus=0)

    print("Information of a particular file: \n%s" %output.decode("utf-8"))


    print("File does not exist.")

# Retrieve the files and folder of a particular directory using ssh command

output ="ssh [email protected] 'ls web/'", events={'(?i)password':'12345\n'})

print("\nThe output of ssh command: \n%s" %output.decode("utf-8"))


The following output will appear after executing the above script. In the output, has given as the filename, and the details of this file have shown. Next, the list of all files of the web folder has shown using ssh connection.

Using spawn class

The syntax of the spawn class is given below. The constructor of this class can take many arguments for many purposes. The first argument is mandatory that will take the command for execution.

class spawn  __init __ (self, command, args=[], timeout=30, maxread=2000, search window size=none, logfile=none, cwd=none, env=none)

Example-2: Simple use of spawn class

The simple use of the spawn class has shown in the following script. The `date` command has been executed here by using the spawn class. The output of the command will be retrieved by creating the object of the spawn class, and the output is printed in human-readable format by using the decode() method.

# Import pexpect module

import pexpect

# Run the date command using spawn

child = pexpect.spawn('date')

# Read the child output without generating EOF


# Store the text that is expected by the string pattern

output = child.before

# Print the output

print("Today is :", output.decode("utf-8"))


The following output will appear after executing the above script.

Example-3: Read the content of the directory using ssh connection

Creating ssh connection and reading the list of all files and folders of a particular directory have shown in the following script.  Here, the password of the defined user will be taken from the user to make ssh connection using the spawn class. If the given password is incorrect, then the script will be terminated by showing an error message.  If the given password is correct, but the terminal is not defined, then the script will show the success message for the connection, send the terminal type, and define the command prompt’s expected pattern. If the password is correct and the terminal is defined, the script will show the success message and the shell command prompt.

# Import pexpect module

import pexpect

# Set the username for ssh connection

username = '[email protected]'

# Take a valid password from the user

Password = input("Enter the login password of %s: " %username)

# Run ssh command using spawn

child = pexpect.spawn('ssh ' + username)

# Wait for the password


# Send the password taken from the user


# Expected three output

i = child.expect (['Permission denied', 'Terminal type', '[#\$] '])

# i will be 0 if ssh is unable to connect

if i == 0:

    print("Permission denied by host. Unable to login")


# i will be 1 if ssh is able to connect but terminal is not set

elif i == 1:

    print('Connected Successfully.\nTerminal type is not set.')



# i will be 2 if ssh is able to connect and terminal is set

elif i == 2:

    print('Connected Successfully.')

    prompt = child.after

    print('Shell Command Prompt:', prompt.decode("utf-8"))


The following output will appear when the above script is executed with the wrong password.

The following output will appear when the above script is executed with the correct password.


pexpect is a very helpful module for Python users that helps them to do their regular tasks automatically. The very basic uses of the pexpect module of Python have been described in this tutorial by using easy examples to help the users to start working with this module.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.