关于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为超时时间(还没完善)。