pexpect模块的学习
来源:互联网 发布:我要表白网整站源码 编辑:程序博客网 时间:2024/05/22 16:00
转载:http://www.52harry.com/program/python/2011-11-29/655.html
关于pexpect模块的相关介绍,google一下就有很多。而且在它的安装包example目录下有很多例子可供参考。网上有很多用它来实现 ssh,ftp的例子,好像scp的例子很少,在此我就贴一个用它来实现scp自动交互的例子,由于时间关系,我就不费话,直接贴代码了。不过代码还不够 完善,有些bug没搞定, 例如:在调用spawn()方法时,传递timeout参数会报异常等,后面在继续完善吧:
- import sys
- from optparse import OptionParser
- import pexpect as pp
- parse = OptionParser()
- parse.add_option( '-t', '--timeout', dest = 'timeout', help = "set session timeout" )
- ( options, args ) = parse.parse_args()
- timeout = None
- if options.timeout:
- timeout = options.timeout
- argstr = ""
- for arg in args[ 0:-1 ]:
- argstr += arg + ' '
- password = args[ -1 ] ## 参数最后一位是密码
- keys = [ 'authenticity', '[Pp]assword:', pp.EOF, pp.TIMEOUT ] ## 用于匹配输出的列表
- command = 'scp -r %s' % ( argstr ) ## 包装scp命令
- try:
- ## child = pp.spawn( command,timeout = timeout) ##不知道为什么在这个地方为timeout设置时会抛异常
- child = pp.spawn( command ) ##发送命令
- except Exception,e:
- print e
- sys.exit( 1 )
- index = child.expect( keys ) ##匹配命令的输出,index 为匹配到的 keys 元素的索引
- if index == 0:
- child.sendline( 'yes' ) ## 第一次连接时,会弹出一个确认生成rsa密钥的提示,直接输入 yes
- index = child.expect( keys )
- elif index == 2:
- child.sendline( password ) ## 输入密码
- index = child.expect( keys )
- elif index == 2 or index == 3:
- print child.before.strip()
- sys.exit( 2 )
- if index == 1:
- child.sendline( password )
- index = child.expect( keys )
- elif index == 2:
- print 'end...'
- sys.exit( 0 )
- elif index == 3:
- print 'session timeout'
- sys.exit( 4 )
- elif index == 1:
- print 'wrong password' ## 如果再次匹配到 [Pp]assword: 说明可能是密码有误
- sys.exit( 3 )
- if index == 2:
- print 'end...'
- sys.exit( 0 )
- else:
- print 'unknown error'
- sys.exit( 5 )
调用方法,假如这个脚本的文件名为pscp : python pscp -t500 ... ... root@192.168.100.22:/tmp password 其中省略号(...) 表示要copy的文件的路径, passowrd 为192.168.100.22主机root用户的密码, -t500为超时时间(还没完善)。
- pexpect模块的学习
- pexpect模块的学习
- Pexpect 模块的学习
- python 的 pexpect模块
- Python的Pexpect模块详解
- 【pexpect模块】第 2 部分:Pexpect 的实例分析
- pexpect模块
- Python学习笔记4-pexpect模块,pxssh
- Pexpect学习
- Python模块之---Pexpect
- Python模块之pexpect
- Python模块之---Pexpect
- Python模块之---Pexpect
- python模块之pexpect
- Python Pexpect 模块使用说明
- 【pexpect模块】第 1 部分:剖析 Pexpect
- python的PEXPECT模块进行交换机配置文件的自动备份
- 利用python的pexpect模块,自动登陆服务器
- sql语句-批量替换
- windows下emacs中cedet的配置
- 十佳影片大全
- Python建立SSH连接的方法
- 使用事件同步线程
- pexpect模块的学习
- 返回vector对象与引用的区别
- origin8.1中文乱码设置方法
- 全排列 总结
- 当爱已成往事
- TCP/IP协议
- pymssql的安装
- Linux 2.6下SPI设备模型(转)
- vc 实现打印功能