Example of pexpect of python to realize automatic interaction

  • 2021-07-26 08:25:46
  • OfStack

Pexpect is an Python implementation of Expect language. It is an Python module used to start subroutines and make specific responses to program output by using regular expressions, so as to realize automatic interaction with them. Pexpect has a wide range of applications, which can be used to realize automatic interaction with ssh, ftp, telnet and other programs. It can be used to automatically copy software installation packages and install them automatically on different machines; It can also be used to automate the interaction with command line in software testing.

Overall, the general process includes:

Run program

Procedure requires human judgment and input

Expect matches by keyword

Send matching characters to the program according to keywords

Basic usage process

To put it bluntly, the use of pexpect is to operate around three key commands:

First, execute a program with spawn

Then use expect to wait for the specified keyword, which is printed on the standard output by the executed program

Finally, when this keyword is found, the send method is used to send a string to this program according to the keyword

Step 1 only needs to be done once, but in the program, step 2. 3 will be repeated to complete the whole work step by step. After mastering this concept, it is easy to use pexpect. Of course, pexpect will not only have these three methods, but actually there are many other peripheral methods.

spawn ()-Executor

The spawn () method is used to execute a program. It returns an action handle for that program, which you can later manipulate, such as:


process = pexpect.spawn('ftp sw-tftp')

The string in spawn () above is the program to be executed, where we open an ftp connection to the sw-tftp server. The first element in spawn () is the command to be executed, and one other parameter can be specified, such as: pexpect. spawn ('ftp sw-tftp', timeout=60) specifies the timeout, which will be explained later.

process is the program operation handle of spawn (), and all subsequent operations on this program are based on this handle, so it can be said to be the most important part.

Note: spawn (), or pexpect does not translate any special characters. For example, * characters have special meanings in shell of Linux, but they are not translated in pexpect. If you want to use the correct meanings of these symbols in linux system, you must add shell to run, which is an easy mistake.

The right way:


process = pexpect.spawn('/bin/bash  In fact, in fact, the c "ls  In fact, in fact, the l | grep LOG > log_list.txt"')

expect ()-Keyword Matching

When spawn () starts a program and returns the program control handle, you can use the expect () method to wait for the specified keyword. It will return 0 to indicate that the required keyword is matched. If the next matching keyword is a list, it will return 1 number to indicate which keyword in the list is matched, starting from 0.

send ()-Send keyword

send () is used as one of three key actions to send the specified string to the program, and there is nothing special about its use, such as:


process.expect("ftp>")
process.send("by\n")

This method returns the number of characters sent.

sendline ()-Sends a string with a car character

The only difference between sendline () and send () is that a carriage return character is added after the string sent, which makes them used in different places:

If you only need to send characters, use send ()

If you want a carriage return after sending the character, use sendline ()

It also returns the number of characters sent

sendcontrol ()-Send control signal

sendcontrol () sends control characters to subroutines, such as < kbd > ctrl+C < /kbd > Or < kbd > ctrl+D < /kbd > Something like, for example, if you want to send a subroutine < kbd > ctrl+G < /kbd > , so write it like this:


process.sendcontrol('g')

Simple example:


command = 'ssh '+username+'@'+host 
child = pexpect.spawn(command) 
ret = child.expect([pexpect.TIMEOUT,'Are you sure you want to continue connecting','[P|p]assword']+PROMPT) 
if ret == 0: 
  print('[-] Error Connecting') 
  return 
if ret == 1: 
  child.sendline('yes') 
  ret = child.expect([pexpect.TIMEOUT,'[p|P]assword']) 
  if ret == 0: 
    print('[-] Error Connecting') 
    return 
  if ret == 1: 
    send_command(password) 
    return 
if ret == 2: 
  send_command(password) 
  return 
return child

Note: For ssh remote login, pxssh class is derived from pexpect, and ssh session operation is encapsulated in layer 1

The common methods are:

login () # Establish an ssh connection

logout () # Disconnect ssh

prompt () # Waits for the system prompt to wait for command execution to end

For details, please stamp: https://www.ofstack.com/article/156232. htm


Related articles: