Python installation and use the command line interaction module pexpect

Source: Internet
Author: User
Pexpect is a pure Python module that can be used to interact with command line commands such as ssh, ftp, passwd, and telnet. it is particularly useful in Linux systems, next, let's take a look at the basic tutorial of installing and using the command line interaction module pexpect in Python: Pexpect is a pure Python module, it can be used to interact with command line commands such as ssh, ftp, passwd, and telnet. it is particularly useful in Linux systems, next, let's take a look at the basic tutorial of installing and using the command line interactive module pexpect in Python:

I. Installation
1. install the easy_install tool


Python install the easy_install tool (this script will be automatically searched and downloaded from the official website)

python -U setuptools

Upgrade easy_install tool

2. install pexpect

easy_install Pexpect


[root@OMS python]# pythonPython 2.7.3rc1 (default, Nov 7 2012, 15:03:45)[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import pexpect>>> import pxssh>>>

OK has been installed.

II. Basic usage
1. run () function
The run function is relatively simple and can only implement simple interaction.

The code is as follows:

Run (command, timeout =-1, withexitstatus = False, events = None, extra_args = None, logfile = None, cwd = None, env = None)

Run the command and return the result, which is similar to OS. system.

Pexpect. run ('ls-LA') # Return value (output, exit status) (command_output, exitstatus) = pexpect. run ('ls-l/bin', withexitstatus = 1)

2. spawn class
Spawn is more powerful than run to achieve more complex interaction

class spawn   __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None)

Timeout specifies the timeout value for interaction;
Maxread sets the read buffer size. The maximum number of bytes that pexpect tries to read from the TTY (Teletype terminal) each time;

Searchwindowsize specifies the position where pattern matching is performed from the input buffer. by default, pattern matching is performed from the start;

The logfile parameter specifies the log record location.
Working process:

# Step 1 establish a connection with the terminal child = pexpect. spawn (the 'scp foo :. ') # Step 2: wait for the terminal to return specific content child. keep CT ('password: ') # Step 3 send commands based on the returned content to interact with child. sendline (mypassword)

3. pxssh class
Pxssh is a derived class of pexpect and is used to establish an ssh connection, which is better than pexpect.

Login () establishes an ssh connection to the target machine;
Logout () releases the connection;
Prompt () is usually used to wait for the end of command execution.

III. instances
Write a script to send commands to the remote server and return results.
Script content:

#!/usr/bin/python #2013-01-16 by larry import pexpect def login(port,user,passwd,ip,command):   child=pexpect.spawn('ssh -p%s %s@%s "%s"' %(port,user,ip,command))   o=''   try:     i=child.expect(['[Pp]assword:','continue connecting (yes/no)?'])     if i == 0:       child.sendline(passwd)     elif i == 1:       child.sendline('yes')     else:       pass   except pexpect.EOF:     child.close()   else:     child.expect(pexpect.EOF)     child.close()   return o  hosts=file('hosts.list','r') for line in hosts.readlines():   host=line.strip("\n")   if host:     ip,port,user,passwd,commands= host.split(":")     for command in commands.split(","):       print "+++++++++++++++ %s run:%s ++++++++++++" % (ip,command),       print login(port,user,passwd,ip,command)  hosts.close()



The content of the host. list file is as follows: /etc/redhat-release,df -Th,whoami192.168.0.21:22999:root:123456:cat /etc/redhat-release,df -Th,whoami

Returned results:

+++ ++ run: cat/etc/redhat-release ++ Red Hat Enterprise Linux Server release 4 ++ + run: df-Th ++ file system type capacity used available % mount point/dev/cciss/c0d0p6ext3 5.9G 4.4G 1.2G 80% // dev/cciss/c0d0p7ext3 426G 362G 43G 90%/opt/dev/cciss/c0d0p5ext3 5.9G 540 M 5.0G 10%/var/dev/cciss/c0d0p3ext3 5.9G 4.1G 1.5G 74%/usr/dev/cciss/c0d0p1ext3 487 M 17 M 445 M 4%/boottmpfs tmpfs 4.0G 0 4.0G 0%/dev/shm ++ +++ run: whoami ++ root

For more Python installation and use of the command line interaction module pexpect, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.