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)

python pexpect 学习与探索的更多相关文章

  1. 好书推荐计划:Keras之父作品《Python 深度学习》

    大家好,我禅师的助理兼人工智能排版住手助手条子.可能非常多人都不知道我.由于我真的难得露面一次,天天给禅师做底层工作. wx_fmt=jpeg" alt="640? wx_fmt= ...

  2. 7大python 深度学习框架的描述及优缺点绍

    Theano https://github.com/Theano/Theano 描述: Theano 是一个python库, 允许你定义, 优化并且有效地评估涉及到多维数组的数学表达式. 它与GPUs ...

  3. Python深度学习 deep learning with Python

    内容简介 本书由Keras之父.现任Google人工智能研究员的弗朗索瓦•肖莱(François Chollet)执笔,详尽介绍了用Python和Keras进行深度学习的探索实践,涉及计算机视觉.自然 ...

  4. Python入门学习指南

    对于初学者,入门至关重要,这关系到初学者是从入门到精通还是从入门到放弃.以下是结合Python的学习经验,整理出的一条学习路径,主要有四个阶段 NO.1 新手入门阶段,学习基础知识 总体来讲,找一本靠 ...

  5. 【原】Learning Spark (Python版) 学习笔记(三)----工作原理、调优与Spark SQL

    周末的任务是更新Learning Spark系列第三篇,以为自己写不完了,但为了改正拖延症,还是得完成给自己定的任务啊 = =.这三章主要讲Spark的运行过程(本地+集群),性能调优以及Spark ...

  6. 60分钟Python快速学习(给发哥一个交代)

    60分钟Python快速学习 之前和同事谈到Python,每次下班后跑步都是在听他说,例如Python属于“胶水语言啦”,属于“解释型语言啦!”,是“面向对象的语言啦!”,另外没有数据类型,逻辑全靠空 ...

  7. python爬虫学习(1) —— 从urllib说起

    0. 前言 如果你从来没有接触过爬虫,刚开始的时候可能会有些许吃力 因为我不会从头到尾把所有知识点都说一遍,很多文章主要是记录我自己写的一些爬虫 所以建议先学习一下cuiqingcai大神的 Pyth ...

  8. python爬虫学习 —— 总目录

    开篇 作为一个C党,接触python之后学习了爬虫. 和AC算法题的快感类似,从网络上爬取各种数据也很有意思. 准备写一系列文章,整理一下学习历程,也给后来者提供一点便利. 我是目录 听说你叫爬虫 - ...

  9. Python正则表达式学习摘要及资料

    摘要 在正则表达式中,如果直接给出字符,就是精确匹配. {m,n}? 对于前一个字符重复 m 到 n 次,并且取尽可能少的情况 在字符串'aaaaaa'中,a{2,4} 会匹配 4 个 a,但 a{2 ...

随机推荐

  1. gradle 默认属性

    Properties(未翻译) Property Description allprojects 包含该项目及其子项目的属性 ant The AntBuilder for this project. ...

  2. [转] 安装DotNetCore.1.0.1-VS2015Tools.Preview2.0.2出现0x80072f8a未指定的错误

    原文地址:安装DotNetCore.1.0.1-VS2015Tools.Preview2.0.2出现0x80072f8a未指定的错误 最近DotNetCore更新到了1.0.1,Azure tools ...

  3. jquery判断checkbox是否选中及改变checkbox状态

    转自:http://blog.csdn.net/limingchuan123456789/article/details/11499665 jquery判断checked的三种方法:.attr('ch ...

  4. 我常用的eclipse快捷键

    重写父类方法:右键点击, 进source,进override/implement 单行注释(或多行注释) Ctrl+/ 文档注释:shift+alt+J 整块注释: Ctrl+shift+/ 取消整块 ...

  5. linux下安装python环境

    1.linux下安装python3 a. 准备编译环境(环境如果不对的话,可能遇到各种问题,比如wget无法下载https链接的文件) yum groupinstall 'Development To ...

  6. Linux程序编写shell script的格式

    #!/bin/bash #program # 在此处写下此程序的作用 #History: #此处写下写此程序的时间 作者 版本号 PATH=/bin:/sbin:/usr/bin:/usr/sbin: ...

  7. bug--java访问hdfs (Server IPC version 9 cannot communicate with client version 4 错误)

    1. 今天想做一个hdfs的java工具类,但是在连接hdfs的时候,报如下错误: Exception in thread "main" org.apache.hadoop.ipc ...

  8. 常用开源镜像站整理android sdk manager

    http://www.cocoachina.com/programmer/20151023/13852.html http://android-mirror.bugly.qq.com:8080/inc ...

  9. Android内存性能优化(内部资料总结) eoe转载

    刚入门的童鞋肯能都会有一个疑问,Java不是有虚拟机了么,内存会自动化管理,我们就不必要手动的释放资源了,反正系统会给我们完成.其实Java中没有指针的概念,但是指针的使用方式依然存在,一味的依赖系统 ...

  10. Java多线程文件下载

    一. 多线程下载文件考虑处理步骤: 1. 如何获取文件的长度 2. 合理的创建线程数量,并计算每一个线程下载的长度 3. 如何将多个线程下载的字节写入到文件中 二. 代码实现如下: package c ...