Python uses pexpect for automated interaction examples

Source: Internet
Author: User


Pexpect is a Python module used to start subroutines and automatically control them, which can be used to interact with command-line programs like SSH, FTP, passwd, Telnet, and so on.

Shell command expect using http://blog.51cto.com/superleedo/1931418

Installing Pexpect

Open https://pypi.org/project/pexpect/#files

Download wget https://files.pythonhosted.org/packages/09/0e/ 75f0c093654988b8f17416afb80f7621bcf7d36bbd6afb4f823acdb4bcdc/pexpect-4.5.0.tar.gz

Tar zxf pexpect-4.5.0.tar.gz

CD pexpect-4.5.0/

Python setup.py Install


SSH telnet, execute command ' LS-LH ' example after successful login

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Pexpect
Import Sys
#通过spawn类启动和控制子应用程序
Child = Pexpect.spawn (' ssh [email protected] ')
#将pexpect的输入输出信息写到mylog. txt files
Fout = File (' Mylog.txt ', ' W ')
Child.logfile = Fout
#将pexpect的输入输出信息输出到标准输出
#child. LogFile = sys.stdout
#expect方法用来判断子程序产生的输出 to determine if the corresponding string is matched
Child.expect (' Password: ')
#字符串匹配则使用sendline进行回应-----Send: Send command, do not enter, Sendline: Send command, enter, Sendcontrol: Send control, such as: Sendctrol (' C ') equivalent to ' CTRL + C ', Sendeof: Send EOF
Child.sendline (' 123456 ')
Child.expect (' # ')
Child.sendline (' Ls-lh ')
Child.expect (' # ')


SSH login can also be implemented using Pexpect's Run function

Pexpect.run (' ssh [email protected] ', events={' password: ', ' 123456 '})


For SSH remote login, Pexpect also derived the Pxssh class, in the SSH session operation on another layer of encapsulation

From Pexpect import pxssh
Import Getpass

Try
s = pxssh.pxssh () #创建pxssh对象
hostname = raw_input (' hostname: ')
Username = raw_input (' username: ')
Password = getpass.getpass (' Password: ') #接收密码输入
S.login (Server=hostname,username=username,password=password) #建立ssh连接
S.sendline (' uptime ') #运行uptime命令
S.prompt () #匹配系统提示符
Print S.before #打印出现系统提示符前的命令输出
S.sendline (' Ls-lh ') #运行命令
S.prompt () #匹配系统提示符
Print S.before #打印出现系统提示符前的命令输出
S.sendline (' df-h ') #运行命令
S.prompt () #匹配系统提示符
Print S.before #打印出现系统提示符前的命令输出
S.logout () #断开ssh连接
Except Pxssh. Exceptionpxssh as E:
print ' Pxssh failed on login '
Print str (e)



Automated FTP Example

#!/usr/bin/env python
#-*-Coding:utf-8-*-

Form __future__ Import unicode_literals# using Unicode encoding
Import Pexpect
Import Sys

Child=pexpect.spawnu (' ftp ftp.openbsd.org ')
Child.expect (' (? i) name. *: ') # (? i) Ignore case
Child.sendline (' anonymous ')
Child.expect (' (? i) password ')
Child.sendline (' mima123456 ')
Child.expect (' ftp> ')
Child.sendline (' bin ') #开启二进制传输
Child.expect (' ftp> ')
Child.sendline (' Get Test.txt ')
Child.expect (' ftp> ')
Sys.stdout.write (Child.before)
Print ("Escape character is ' ^] '. \ n")
Sys.stdout.write (Child.after)
Sys.stdout.flush ()
Child.interact ()
Child.sendline (' Bye ')
Child.close ()



remote file package and download sample

#!/usr/bin/env python 
#-*-coding:utf-8-*-

Import pexpect
Import SYS

ip= "192.168.1.124"
user= "root"
passwd= "kkl123456"
target_file= "/data/logs/nginx.log"

Child=pexpect.spawn ('/usr/bin/ssh ', [user+ ' @ ' +ip])
Fout=file (' Mylog.txt ', ' W ')
Child.logfile=fout

Try:
Child.expect (' (? i) password ')
Child.sendline (passwd)
Child.expect (' # ')
Child.sendline (' Tar -zcf/data/logs/nginx.tar.gz ' +target_file)
Child.expect (' # ')
Print Child.before
child.sendline (' exit ')
Fout.close ()
except EOF:
print "expect EOF"
except TIMEOUT:
print "expect TIMEOUT"

child= Pexpect.spawn ('/USR/BIN/SCP ', [user+ ' @ ' +ip+ ':/data/logs/nginx.tar.gz ', '/Home '])
Fout=file (' mylog.txt ', ' a ')
Child.logfile=fout

Try:
Child.expect (' (? i) password ')
Child.sendline (passwd)
Child.expect ( Pexpect. EOF)
except EOF:
print "expect EOF"
except TIMEOUT:
print "expect TIMEOUT"





Python uses pexpect for automated interaction examples

Related Article

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.