一、安装
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

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

WebStorm Mac版
好用的JavaScript开发工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)