Basic tutorial on installing and using the command line Interaction module pexpect in Python

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 interactive module pexpect in Python: I. Installation
1. Install the easy_install Tool

wget http://peak.telecommunity.com/dist/ez_setup.py

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

python ez_setup.py -U setuptools

Upgrade easy_install Tool

2. Install pexpect

easy_install Pexpect

Test:

[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.
Example:

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 user@example.com :. ') # 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:     o=child.read()     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()

Usage:

python scripts.py

The content of the host. list file is as follows:

192.168.0.21:22999:root:123456:cat /etc/redhat-release,df -Th,whoami192.168.0.21:22999:root:123456:cat /etc/redhat-release,df -Th,whoami

Returned results:

+++ ++ 192.168.0.21 run: cat/etc/redhat-release ++ Red Hat Enterprise Linux Server release 4 ++ + 192.168.0.21 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 ++ +++ 192.168.0.21 run: whoami ++ root

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: info-contact@alibabacloud.com 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.