python pexpect 学习与探索

 

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 pexpectchild = 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 appendchild = pexpect.spawn(‘su root‘)
child.logfile = sys.stdoutchild.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 学习与探索

时间: 2024-08-02 03:51:28

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

Python深度学习该怎么学?

Python想必对我们来说已经很熟悉了,Python的发展带来了一股学习Python的浪潮,聪明的人早已看准这个发展的好时机开始学习Python,那么我想问你知道Python深度学习是什么吗?不懂了吧,那让小编给你普及一下这方面的知识吧. 深度学习目前已经成为了人工智能领域的突出话题.它在"计算机视觉"和游戏(AlphaGo)等领域的突出表现而闻名,甚至超越了人类的能力.近几年对深度学习的关注度也在不断上升. 在这篇文章中,我们的目标是为所有Python深度学习的人提供一条学习之路,同

Python开发学习路线

Python , 是一种面向对象的解释型计算机程序设计语言,具有丰富和强大的库,Python 已经成为继JAVA,C++之后的的第三大语言. 特点:简单易学.免费开源.高层语言.可移植性强.面向对象.可扩展性.可嵌入型.丰富的库.规范的代码.大这里给家列出从Python入门到实战学习路线. 一.入门教程 1.Python 面向对象编程 2.jquery入门 3.HTML+CSS基础入门 4.Javascript初步 5.Python语言编程基础 二.初级教程 1.Git 与 GitHub 2.P

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

大家好,我禅师的助理兼人工智能排版住手助手条子.可能非常多人都不知道我.由于我真的难得露面一次,天天给禅师做底层工作. wx_fmt=jpeg" alt="640? wx_fmt=jpeg" /> 今天条子最终也熬到这一天! 最终也有机会来为大家写文章了! 激动的我啊.都忘了9月17号中午和禅师在我厂门口兰州料理吃饭.禅师要了一碗牛拉+一瓶可乐+一碟凉菜,总共30元.让我结账至今还没还钱的事儿了.真的,激动的我一点儿都想不起来了. 国庆长假就要開始了,作为人工智能头条的

Python入门学习指南--内附学习框架

Python入门学习指南 最近开始整理python的资料,博主建立了一个qq群,希望给大家提供一个交流的同平台: 78486745 ,欢迎大家加入共同交流学习. 对于初学者,入门至关重要,这关系到初学者是从入门到精通还是从入门到放弃.以下是结合Python的学习经验,整理出的一条学习路径,主要有四个阶段 NO.1 新手入门阶段,学习基础知识 总体来讲,找一本靠谱的书,由浅入深,边看边练. 网上的学习教程有很多,多到不知道如何选择.所有教程在基础知识介绍方面都差不多,区别在于讲的是否足够细(例如运

Python深度学习(高清版)PDF

Python深度学习(高清版)PDF百度网盘链接:https://pan.baidu.com/s/1WOAfraS5Y56247A8oDUPgg 提取码:pfo3 复制这段内容后打开百度网盘手机App,操作更方便哦内容简介 · · · · · · 本书由Keras之父.现任Google人工智能研究员的弗朗索瓦?肖莱(Fran?ois Chollet)执笔,详尽介绍了用Python和Keras进行深度学习的探索实践,涉及计算机视觉.自然语言处理.生成式模型等应用.书中包含30多个代码示例,步骤讲解

机器学习《Python深度学习》介绍及下载

本书由Keras之父.现任Google人工智能研究员的弗朗索瓦•肖莱(François Chollet)执笔,详尽介绍了用Python和Keras进行深度学习的探索实践,涉及计算机视觉.自然语言处理.生成式模型等应用.书中包含30多个代码示例,步骤讲解详细透彻.由于本书立足于人工智能的可达性和大众化,读者无须具备机器学习相关背景知识即可展开阅读.在学习完本书后,读者将具备搭建自己的深度学习环境.建立图像识别模型.生成图像和文字等能力. 链接:https://pan.baidu.com/s/1O2

Python深度学习 deep learning with Python 人民邮电出版社

内容简介 本书由Keras之父.现任Google人工智能研究员的弗朗索瓦?肖莱(Fran?ois Chollet)执笔,详尽介绍了用Python和Keras进行深度学习的探索实践,涉及计算机视觉.自然语言处理.生成式模型等应用.书中包含30多个代码示例,步骤讲解详细透彻.由于本书立足于人工智能的可达性和大众化,读者无须具备机器学习相关背景知识即可展开阅读.在学习完本书后,读者将具备搭建自己的深度学习环境.建立图像识别模型.生成图像和文字等能力. 作者简介 [作者简介] 弗朗索瓦?肖莱(Fran?

在python下学习libsvm

1.下载libsvm,python,gnuplot(链接网上全有,压缩包自己保留着) 2.在python上的实现(主要用截图的形式展现) (1)输入命令寻求最优参数 (2) 参数c,g输出结果 gnuplot输出图像 (3)最后输入训练数据,训练数据,通过建立模型进行预测 大概也就这样了,grid.py里面需要改下gnuplot的路径 在python下学习libsvm,布布扣,bubuko.com

python的学习内容

Python的学习路线 掌握基本的语法 这个入门的东西很多,最好的当然是去看官方的文档,如果英语不好那就另当别论,其次看一些优秀的书籍,当然这个也是耗费时间的,但是如果你要是速成,速度的速,那通过一些博客.视频其实也不失为好的方式,起码上手更容易一些了,尤其是你真正的第一门语言. 掌握常用的库 使用成熟可靠的第三方库是多么的高效,尤其是你就几个人小打小闹的时候,重复造轮子是多么的没有必要,但是你必须理解人家的机制,等你用第三方库多了,有能力写自己的库的时候,那我就是真正的恭喜你了. 自动化运维相