Home Backend Development Python Tutorial Python安装使用命令行交互模块pexpect的基础教程

Python安装使用命令行交互模块pexpect的基础教程

Jun 10, 2016 pm 03:04 PM
linux python shell Command Line

一、安装
1、安装easy_install工具

wget http://peak.telecommunity.com/dist/ez_setup.py
Copy after login

python ez_setup.py 安装easy_install工具(这个脚本会自动去官网搜索下载并安装)

python ez_setup.py -U setuptools
Copy after login

升级easy_install工具

2、安装pexpect

easy_install Pexpect
Copy after login

测试一下:

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

ok已经安装完成。


二、基本用法
1.run()函数
run功能相对简单,只能实现简单交互

复制代码 代码如下:

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


run运行命令,然后返回结果,与os.system类似.
示例:

pexpect.run('ls -la')
# 返回值(输出,退出状态)
(command_output, exitstatus) = pexpect.run('ls -l /bin', withexitstatus=1)
Copy after login

2.spawn类
spawn功能比run强大,可以实现更复杂交互

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

timeout指定交互是等待的超时值;
maxread设置read buffer大小. 每次pexpect尝试从TTY(Teletype终端)从读取的最大字节数;

searchwindowsize 指定了从输入缓冲区中进行模式匹配的位置,默认从开始匹配;

logfile 参数指定日志的记录位置。
工作过程:

# 第一步与终端建立连接
child = pexpect.spawn('scp foo user@example.com:.')
# 第二步等待终端返回特定内容
child.expect('Password:')
# 第三步根据返回内容发送命令进行交互
child.sendline(mypassword)
Copy after login

3.pxssh类
pxssh是pexpect的派生类,用于建立ssh连接,比pexpect好用。

login() 建立到目标机器的ssh连接;
logout() 释放该连接;
prompt() 等待提示符,通常用于等待命令执行结束。


三、实例
写一个脚本给远程服务器发送命令,并返回结果。
脚本内容:

#!/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()
Copy after login

使用方法:

python scripts.py
Copy after login

host.list文件内容如下:

192.168.0.21:22999:root:123456:cat /etc/redhat-release,df -Th,whoami
192.168.0.21:22999:root:123456:cat /etc/redhat-release,df -Th,whoami
Copy after login

返回结果:

+++++++++++++++ 192.168.0.21 run:cat /etc/redhat-release ++++++++++++
Red Hat Enterprise Linux Server release 4
+++++++++++++++ 192.168.0.21 run:df -Th ++++++++++++
文件系统   类型  容量 已用 可用 已用% 挂载点
/dev/cciss/c0d0p6
ext3  5.9G 4.4G 1.2G 80% /
/dev/cciss/c0d0p7
ext3  426G 362G  43G 90% /opt
/dev/cciss/c0d0p5
ext3  5.9G 540M 5.0G 10% /var
/dev/cciss/c0d0p3
ext3  5.9G 4.1G 1.5G 74% /usr
/dev/cciss/c0d0p1
ext3  487M  17M 445M  4% /boot
tmpfs    tmpfs  4.0G   0 4.0G  0% /dev/shm
+++++++++++++++ 192.168.0.21 run:whoami ++++++++++++
root
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the reason why PS keeps showing loading? What is the reason why PS keeps showing loading? Apr 06, 2025 pm 06:39 PM

PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

How to speed up the loading speed of PS? How to speed up the loading speed of PS? Apr 06, 2025 pm 06:27 PM

Solving the problem of slow Photoshop startup requires a multi-pronged approach, including: upgrading hardware (memory, solid-state drive, CPU); uninstalling outdated or incompatible plug-ins; cleaning up system garbage and excessive background programs regularly; closing irrelevant programs with caution; avoiding opening a large number of files during startup.

How to solve the problem of loading when PS is started? How to solve the problem of loading when PS is started? Apr 06, 2025 pm 06:36 PM

A PS stuck on "Loading" when booting can be caused by various reasons: Disable corrupt or conflicting plugins. Delete or rename a corrupted configuration file. Close unnecessary programs or upgrade memory to avoid insufficient memory. Upgrade to a solid-state drive to speed up hard drive reading. Reinstalling PS to repair corrupt system files or installation package issues. View error information during the startup process of error log analysis.

Is slow PS loading related to computer configuration? Is slow PS loading related to computer configuration? Apr 06, 2025 pm 06:24 PM

The reason for slow PS loading is the combined impact of hardware (CPU, memory, hard disk, graphics card) and software (system, background program). Solutions include: upgrading hardware (especially replacing solid-state drives), optimizing software (cleaning up system garbage, updating drivers, checking PS settings), and processing PS files. Regular computer maintenance can also help improve PS running speed.

How to solve the problem of loading when PS is always showing that it is loading? How to solve the problem of loading when PS is always showing that it is loading? Apr 06, 2025 pm 06:30 PM

PS card is "Loading"? Solutions include: checking the computer configuration (memory, hard disk, processor), cleaning hard disk fragmentation, updating the graphics card driver, adjusting PS settings, reinstalling PS, and developing good programming habits.

html next page function html next page function Apr 06, 2025 am 11:45 AM

<p>The next page function can be created through HTML. The steps include: creating container elements, splitting content, adding navigation links, hiding other pages, and adding scripts. This feature allows users to browse segmented content, displaying only one page at a time, and is suitable for displaying large amounts of data or content. </p>

How to solve the problem of loading when the PS opens the file? How to solve the problem of loading when the PS opens the file? Apr 06, 2025 pm 06:33 PM

"Loading" stuttering occurs when opening a file on PS. The reasons may include: too large or corrupted file, insufficient memory, slow hard disk speed, graphics card driver problems, PS version or plug-in conflicts. The solutions are: check file size and integrity, increase memory, upgrade hard disk, update graphics card driver, uninstall or disable suspicious plug-ins, and reinstall PS. This problem can be effectively solved by gradually checking and making good use of PS performance settings and developing good file management habits.

Can PDF export be exported in batches by PS? Can PDF export be exported in batches by PS? Apr 06, 2025 pm 04:54 PM

There are three ways to export PDFs in batches on PS: use PS action functions: record and open files and export PDF actions, and execute actions in a loop. With the help of third-party software: use file management software or automation tools to specify the input and output folders and set the file name format. Use scripts: Write scripts to customize batch export logic, but programming knowledge is required.

See all articles