设为首页 收藏本站
查看: 1102|回复: 0

[经验分享] python pexpect 学习与探索

[复制链接]

尚未签到

发表于 2015-4-27 07:47:29 | 显示全部楼层 |阅读模式
  
  pexpect是python交互模块,有两种使用方法,一种是函数:run另外一种是spawn类
  1.pexpect  module 安装

  pexpect属于第三方的,所以需要安装,
  目前的版本是 3.3 下载地址 https://pypi.python.org/pypi/pexpect/
  安装步骤:  
  



tar -xzvf  pexpect-3.3.tar.gz
cd pexpect-3.3
python setup install (require root)
  但是 这个安装需要root权限,如果没有root权限在,还能使用吗?
  答案是肯定的,你只需要把lib的路径放入sys.path。这样便可以使用pexpect



#!/usr/bin/env python
import sys
sys.path.append('pexpect-3.3/build/lib')

  确认安装成功:
  



>>> import pexpect
>>> dir(pexpect)
['EOF', 'ExceptionPexpect', 'PY3', 'TIMEOUT', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__', '_run', 'codecs', 'errno', 'fcntl', 'is_executable_file', 'os', 'pty', 're', 'resource', 'run', 'runu', 'searcher_re', 'searcher_string', 'select', 'signal', 'spawn', 'spawnu', 'split_command_line', 'stat', 'struct', 'sys', 'termios', 'time', 'traceback', 'tty', 'types', 'which']
  
  
2.使用方法
  run 函数,run函数和os。system()差不多,所不同的是os.system返回的是整数,而run返回字符串
  



>>> print pexpect.run('ping localhost -c 3')           
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.087 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.088 ms
64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.088 ms
--- localhost ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 0.087/0.087/0.088/0.010 ms
  
spawn 类是通过生成子程序sendline发送命令与expect拿回返回进行交互



import pexpect
child = pexpect.spawn('python',timeout=3)
child.expect(">>>")
child.sendline("exit()")
print child.before   # Print the result of the ls command.
  
timeout是等待时间,如果超过就会抛出exception,可以 使用except关键字捕获
  
  
  设置log
  



fout=file('filename','a') #w write /a append
child = pexpect.spawn('su root')
child.logfile = sys.stdout
child.logfile_send=fout
  
  
  
  



#!/usr/bin/python
'''
this script can batch add user
everytime will add specific usename
user mumber and password
create by Young 2014/08/02
require pexpect module, if you don't have one
please install this module
if you can't install this module please
add  this module path to sys.path
'''
import pexpect
import getopt
import os
import sys
import random
import string
# usage fuction
def usage():
print '''
Usage: python %s  --name user --amount 100 --password [optional]
or python %s  -n user -a 100 -p [optional]
this will create user1~user100 and default password will be random or specific.
make sure when you run this script as root
-n,--name        the username you want create
-a,--amount      the amount of users you want create
-p,--password    the default password of use your create
-h,--help        display this help and exit
-v,--version     output version information and exit
'''  %(sys.argv[0],sys.argv[0])
# get the parameters
# set the default user name
user_name='user'
# generate random password
def set_password():
word=[x for x in 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789']
p=string.join(random.sample(word, 8)).replace(" ","")
return p
# number of users ,set default users number as 10
number_of_users=10
password=set_password()
is_ramdom_password=True
#print password
def get_command():
try:
opts, args = getopt.getopt(sys.argv[1:], "n:a:p:hv", ["name=","amount=","password=","help", "version"])
except getopt.GetoptError as err:
# print help information and exit
print str(err) # will print something like "option -a not recognized"
            usage()
sys.exit(2)
#print opts,args
for option,value in opts:
#print "----------->"+option+' '+value
if option in ["-n","--name"]:
if(len(value)>=4):
global user_name
user_name=value
else:
print "invaild usename,will use user"
elif option in ["-a","--amount"]:
if value.isdigit():
if( int(str(value))>0 and int(str(value))< 1000 ):
global number_of_users
number_of_users=int(str(value))
else:
usage()
sys.exit(2)
else:
print "ValueError: invalid literal for ",value
print "invaild amount,will use defualt"
elif option in ["-p","--password"]:
if(len(value)>=6):
global password
password=value   
global is_ramdom_password
is_ramdom_password=False
else:
print "invaild password,will use random"
elif option in ["-v","--version"]:
print sys.argv[0]+' 1.0.0'
sys.exit(0)
elif option in ("-h", "--help"):
usage()
sys.exit(0)
else :
assert False, "unhandled option"
usage()
sys.exit(2)
def check_root():
if( os.environ['USER']!='root'):
print 'Permission denied,please su root'
sys.exit()
#use pexpect to adduser
def run_add(user,mypassword):
log = file('adduser.log','a')
flag=os.system('adduser '+user)
if(flag!=0):
os.system('userdel '+user)
os.system('adduser '+user)
try:
child=pexpect.spawn('passwd '+user,timeout=5)
child.logfile = log
child.logfile_send=sys.stdout
child.expect("New password:")
child.sendline(mypassword)
child.expect("Retype new password:")
child.sendline(mypassword)
child.expect("passwd: all authentication tokens updated successfully.")
except pexpect.EOF:
pass
except pexpect.TIMEOUT:
pass

def add_user(name,amount,password,is_ramdom_password):
check_root()
for number in range(1,amount+1):
if(is_ramdom_password):
print "%4d: adduser %s%-4d password %s " %(number,name,number,set_password())   
run_add(name+str(number),set_password())
else:
print "%4d: adduser %s%-4d password %s " %(number,name,number,password)
run_add(name+str(number),set_password)

get_command()
add_user(user_name,number_of_users,password,is_ramdom_password)
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-60926-1-1.html 上篇帖子: python gevent 下篇帖子: python logging 模块完整使用示例
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表