Python installation using 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, Telnet, and is especially useful under Linux systems. Here's a look at the basics of Python installation using the command-line interaction module Pexpect:

First, installation
1. Installing Easy_install Tools

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

Python ez_setup.py Install Easy_install tool (this script will automatically go to the official website to download and install)

Python ez_setup.py-u Setuptools

Upgrade Easy_install Tools

2, Installation Pexpect

Easy_install Pexpect

Test it:

[Root@oms python]# Pythonpython 2.7.3rc1 (default, Nov 7, 15:03:45) [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2t Ype "Help", "copyright", "credits" or "license" for more information.>>> import pexpect>>> import pxssh& Gt;>>

OK has been installed to complete.


Ii. Basic Usage
1.run () function
The run function is relatively simple and can only be implemented with simple interaction


Copy the Code code as follows:


Run (Command,timeout=-1,withexitstatus=false,events=none,extra_args=none, Logfile=none, Cwd=None, Env=None)



Run runs the command and then returns the result, 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
The Spawn feature is more powerful than run and allows for more complex interactions

Class Spawn   __init__ (self, command, args=[], timeout=30, maxread=2000, Searchwindowsize=none, Logfile=none, cwd= None, Env=none)

timeout Specifies that the interaction is a waiting time-out value;
Maxread set the read buffer size. The maximum number of bytes read from the TTY (Teletype terminal) per Pexpect attempt;

SEARCHWINDOWSIZE Specifies the position of the pattern match from the input buffer, and the default is to match from the beginning;

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

# The first step is to establish a connection with the terminal child = Pexpect.spawn (' SCP foo user@example.com:. ') # The second step waits for the terminal to return a specific content child.expect (' Password: ') # The third step is to interact Child.sendline (MyPassword) based on the return content Send command

3.pxssh class
Pxssh is a derived class of pexpect that is used to establish an SSH connection that is more useful than pexpect.

Login () establishes an SSH connection to the target machine;
Logout () releases the connection;
Prompt () Waits for a prompt, which is typically used to wait for the command execution to finish.


Third, examples
Write a script to send a command to the remote server and return the result.
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 ()

How to use:

Python scripts.py

The contents of the Host.list file are 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

return Result:

+++++++++++++++ 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%//d Ev/cciss/c0d0p7ext3  426G 362G  43G 90%/opt/dev/cciss/c0d0p5ext3  5.9G 540M 5.0G 10%/var/dev/cciss/ C0d0p3ext3  5.9G 4.1G 1.5G 74%/usr/dev/cciss/c0d0p1ext3  487M  17M 445M  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.