Python安装使用命令行交互模块pexpect的基础教程
一、安装
1、安装easy_install工具
wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py 安装easy_install工具(这个脚本会自动去官网搜索下载并安装)
python ez_setup.py -U setuptools
升级easy_install工具
2、安装pexpect
easy_install Pexpect
测试一下:
[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 >>>
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)
spawn功能比run强大,可以实现更复杂交互
class spawn __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None)
maxread设置read buffer大小. 每次pexpect尝试从TTY(Teletype终端)从读取的最大字节数;
工作过程:
# 第一步与终端建立连接 child = pexpect.spawn('scp foo user@example.com:.') # 第二步等待终端返回特定内容 child.expect('Password:') # 第三步根据返回内容发送命令进行交互 child.sendline(mypassword)
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()
使用方法:
python scripts.py
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
返回结果:
+++++++++++++++ 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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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.

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.

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.

<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>

"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.

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.
