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参数会报异常等,后面在继续完善吧:

 

view plain
  1. import sys  
  2. from optparse import OptionParser  
  3. import pexpect as pp  
  4.   
  5. parse = OptionParser()  
  6. parse.add_option( '-t''--timeout', dest = 'timeout', help = "set session timeout" )  
  7.   
  8. ( options, args ) = parse.parse_args()   
  9.   
  10. timeout = None  
  11. if options.timeout:  
  12.     timeout = options.timeout  
  13.   
  14. argstr = ""  
  15. for arg in args[ 0:-1 ]:  
  16.     argstr += arg + ' '  
  17.   
  18. password = args[ -1 ] ## 参数最后一位是密码  
  19. keys = [ 'authenticity''[Pp]assword:', pp.EOF, pp.TIMEOUT ] ## 用于匹配输出的列表  
  20. command = 'scp -r %s' % ( argstr )  ## 包装scp命令  
  21. try:  
  22. ##    child = pp.spawn( command,timeout = timeout) ##不知道为什么在这个地方为timeout设置时会抛异常  
  23.        child = pp.spawn( command )   ##发送命令  
  24. except Exception,e:  
  25.     print e  
  26.     sys.exit( 1 )  
  27.   
  28. index = child.expect( keys )  ##匹配命令的输出,index 为匹配到的 keys 元素的索引   
  29.   
  30. if index == 0:  
  31.     child.sendline( 'yes' )   ## 第一次连接时,会弹出一个确认生成rsa密钥的提示,直接输入 yes  
  32.     index = child.expect( keys )    
  33.   
  34. elif index == 2:  
  35.     child.sendline( password )  ## 输入密码  
  36.     index = child.expect( keys )  
  37.   
  38. elif index == 2 or index == 3:  
  39.     print child.before.strip()  
  40.     sys.exit( 2 )  
  41.   
  42. if index == 1:  
  43.     child.sendline( password )  
  44.     index = child.expect( keys )  
  45.   
  46. elif index == 2:  
  47.     print 'end...'  
  48.     sys.exit( 0 )  
  49.   
  50. elif index == 3:  
  51.     print 'session timeout'  
  52.     sys.exit( 4 )  
  53.   
  54. elif index == 1:  
  55.     print 'wrong password'   ## 如果再次匹配到 [Pp]assword: 说明可能是密码有误  
  56.     sys.exit( 3 )  
  57.   
  58. if index == 2:  
  59.     print 'end...'  
  60.     sys.exit( 0 )  
  61. else:  
  62.     print 'unknown error'  
  63.     sys.exit( 5 )  

 

 

调用方法,假如这个脚本的文件名为pscp :  python pscp -t500 ... ... root@192.168.100.22:/tmp  password    其中省略号(...) 表示要copy的文件的路径, passowrd 为192.168.100.22主机root用户的密码, -t500为超时时间(还没完善)。

原创粉丝点击