`
垂直的微笑
  • 浏览: 45278 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

利用Pexpect模拟人机互动实现自动LOG取得

 
阅读更多
#!/usr/bin/python
#-*- coding: utf-8 -*-
import pexpect
import re
import os
import sys, getopt
import threading
import string
from time import strftime,time,strptime,localtime,sleep

hostlist=''
module=''

def get_logpath(date):
    global hostlist
    global module
    logpath=''
    f = open(r'logrule') 
    lines = f.readlines()
    for line in lines:
        pattern = re.compile(r'.*host=(.*)\]')
        match = pattern.match(line)
        if match:
            hostlist=match.group(1) 
        pattern = re.compile(r'(.*%s.*)=(.*)'%module,re.I)
        match = pattern.match(line)
        if match:
            module=match.group(1)
            print 'Module:%s'%(module)
            logpath=match.group(2)
            break;
    f.close()
    
    if logpath!='':
        logdate=strptime(date,'%Y%m%d')
        logpath = logpath.replace("YYYY",'%s'%(logdate.tm_year))
        logpath = logpath.replace("MM",'%02d'%(logdate.tm_mon))
        logpath = logpath.replace("M",'%s'%(logdate.tm_mon))
        logpath = logpath.replace("DD",'%02d'%(logdate.tm_mday))
        logpath = logpath.replace("D",'%s'%(logdate.tm_mday))
    else:
        print "can't find the path of module!"
        os._exit(1)
        
    #print hostlist+logpath
    return logpath

def login_command(user, host, password):
    print 'ssh %s@%s'%(user, host)
    ssh_newkey = 'Are you sure you want to continue connecting'
    child = pexpect.spawn('ssh %s@%s'%(user, host),timeout=900,maxread=5000)
    i = child.expect([pexpect.TIMEOUT,ssh_newkey,".*password:.*"])
    if(i == 0): 
        print 'ERROR!'
        print 'SSH could not login. Here is what SSH said:'
        print child.before, child.after
    elif(i == 1): 
        child.sendline("yes")
        i = child.expect ('password: ')
    child.sendline(password)
    return child

def scp_command(child, user, host, password, frompath ,tofolder):
    command='scp %s@%s:%s %s'%(user, host, frompath, tofolder)
    print command
    child.sendline(command)
    ssh_newkey = 'Are you sure you want to continue connecting'
    i=child.expect([pexpect.TIMEOUT,ssh_newkey, ".*password:.*"],timeout=30)
    if(i == 0):
        print 'ERROR!'
        print 'SSH could not login. Here is what SSH said:'
        print child.before, child.after
    elif(i == 1): 
        child.sendline("yes")
    child.sendline(password)
    i = child.expect([pexpect.TIMEOUT, ".*"],timeout=300)
    if(i == 0): 
        print '--------------------------------------SCP timeout!'
        print child.before, child.after
    return child

def getlog_command(user, host, password,user2, password2, date):
    
    #登录138
    child=login_command(user, host, password)
    basefolder="/home/pset_user/pset/log_%s"%(date)
    child.sendline('mkdir -p %s'%(basefolder))
    
    #取得log
    logpath=get_logpath(date)
    hostarray=hostlist.split(';')
    icnt=1
    for ip in hostarray:
        child.sendline('mkdir -p %s/%s_%s'%(basefolder,module,icnt))
        child=scp_command(child,user2,ip,password2,logpath,'%s/%s_%s/'%(basefolder,module,icnt))
        icnt+=1
        
    #打包
    child.sendline('cd %s'%(basefolder))
    tarname='%s_%s.tar.gz'%(module,strftime('%Y%m%d%H%M%S',localtime(time())))
    print 'tar czvf %s %s_?'%(tarname,module)
    child.sendline('tar czvf %s %s_?'%(tarname,module))
    child.sendline('exit')
    child.expect(pexpect.EOF)
    #print child.before
    
    #登录221
    child=login_command('#', '#', '#')
    
    #scp日志到221
    toBaseFolder='/home/cms/pio_test'
    child.sendline('cd %s'%(toBaseFolder))
    #today=strftime('%Y%m%d',localtime(time()))
    child.sendline('mkdir -p %s'%(date))

    #进度监视
    prothread=pthread(user, host, password,'%s/%s'%(basefolder,tarname),'%s/%s/%s'%(toBaseFolder,date,tarname))
    prothread.start()
    child=scp_command(child,user,host,password,'%s/%s'%(basefolder,tarname),'%s/'%(date))
    prothread.join()
    child.sendline('exit')
    child.expect(pexpect.EOF)
    #print child.before
    
    #登录138
    child=login_command(user, host, password)
    child.sendline('rm -rf %s'%(basefolder))
    #child.sendline('rm -f %s/%s'%(basefolder,tarname))
    
    child.sendline('exit')
    return child



def ssh_command (user, host, password, command):
    ssh_newkey = 'Are you sure you want to continue connecting'
    child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
    i = child.expect([pexpect.TIMEOUT, ssh_newkey, '.*password:.*'])
    if i == 0:
        print 'ERROR!'
        print 'SSH could not login. Here is what SSH said:'
        print child.before, child.after
        return None
    if i == 1:
        child.sendline ('yes')
        i = child.expect([pexpect.TIMEOUT, 'password: '])
        if i == 0:
            print 'ERROR!'
            print 'SSH could not login. Here is what SSH said:'
            print child.before, child.after
            return None
    # 输入密码.
    child.sendline(password)
    child.expect(pexpect.EOF)
    size= child.before.strip().split()[0]
    return size

class pthread(threading.Thread):
    def __init__(self,user, host, password,command,command2):
        self.user = user
        self.user = user
        self.host = host
        self.password = password
        self.command = command
        self.command2 = command2
        threading.Thread.__init__(self)
        
    def run (self):
        size=0
        totalsize=ssh_command(self.user, self.host, self.password,"du -s %s"%(self.command))
        pattern = re.compile(r'[0-9]+')
        match = pattern.match(totalsize)
        if match:
            while totalsize!=size:
               sleep(5)
               size=ssh_command('cms', '#', '#', "du -s %s"%(self.command2))
               sleep(5)
               print 'downloading(%d%s)…… size:%sk/total:%sk'%(string.atoi(size)*100/string.atoi(totalsize),'%',size,totalsize)
            else:
               print "get the module'logruleg finished!"

def main ():
    global module
    host = "#"
    user = "#"
    password = "#"
    user2 = "#"
    password2 = "#"
    modulelist = ''
    # 获得用户指定模块名及指定日期
    opts, args = getopt.getopt(sys.argv[1:], "hm:d:",["help"])
    for op, value in opts:
        if op == "-m":
            modulelist = value
        elif op == "-d":
            date = value
        elif op in ("-h","--help"):
            sys.exit()
    #module = raw_input('Module: ')
    #date = raw_input('Date(YYYYMMDD): ')
    pattern = re.compile(r'^\d{8}$')
    match = pattern.match(date)
    if match:
        #调用scp命令取得log并打包传送
        for module in modulelist.split(','):
            child = getlog_command (user, host, password,user2, password2, date)
            child.expect(pexpect.EOF)
            print child.before
    else:
        print 'invalid date format!'

if __name__ == '__main__':
    try:
        main()
    except Exception, e:
        print str(e)
        #traceback.print_exc()
        os._exit(1)

分享到:
评论

相关推荐

    python之pexpect实现自动交互的例子

    Pexpect 是 Expect 语言的一个 Python 实现,是一个用来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的 Python 模块。 Pexpect 的使用范围很广,可以用来实现与 ssh、ftp 、telnet 等...

    pexpect-2.3.tar.gz

    Pexpect makes Python a better tool for controlling other applications. Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their ...

    pexpect-3.3.tar.gz

    Python 模块的代码,pexpect3.3.tar.gz ...........

    python Pexpect 实现输密码 scp 拷贝的方法

    本想直接在bash文件中使用Pexpect 来实现自动输入密码,并scp拷贝文件,但是权限的限制导致不能安装使用Pexpect 。 最后考虑使用python实现。 环境: python2.7 centos from pexpect import * import os cwd = os....

    Python:pexpect模块下载

    Python中的pexpect模块下载Python中的pexpect模块下载

    pexpect-4.0.1

    Pexpect是一个用来启动子程序并对其进行自动控制的Python模块,它可以用来和像ssh,ftp,passwd,telnet等命令行程序进行自动交互。

    python自动化运维框架封装paramiko和pexpect

    python自动化运维框架,同时封装paramiko和pexpect

    pexpect模块

    很好的工具包

    使用python的pexpect模块,实现远程免密登录的示例

    当我们需要用脚本实现,远程登录或者远程操作的时候,都要去解决如何自动输入密码的问题,一般来说有3种实现方式: 1).配置公钥私钥 2).使用shell下的命令,expect 3).使用python的pexpect模块 下面介绍的代码,是...

    pexpect-2.3-11.el7.noarch.rpm

    离线安装包,亲测可用

    Python Pexpect库的简单使用方法

    Pexpect使用在自动交互的应用,例如SSH、SFTP、PASSWD、TELNET。它可以被应用在使用自动设置脚本为不同的服务器自动地重复的安装软件包。也可以被应用在自动的软件测试。 Pexpect的主要特点是需要Python的基本库pty...

    python pexpect实践

    python pexpect实践

    python2-pexpect-4.6-1.el7.noarch.rpm

    官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装

    Python库 | pexpect-4.4.0-py2.py3-none-any.whl

    资源分类:Python库 所属语言:Python 资源全名:pexpect-4.4.0-py2.py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    python pexpect ssh 远程登录服务器的方法

    如果没有,linux系统输入 easy_install pexpect便可自动安装。 测试代码,连接127.0.0.1 下面是我手动连接127.0.0.1, 发现只有在首次使用ssh连接127.0.0.1时,需要输入yes or no ,而后再次使用ssh ,则不需要再次...

    python3-pexpect-4.3.1-3.el8.noarch.rpm

    官方离线安装包,亲测可用

    pexpect-4.3.0.tar.gz

    ipython_genutils-0.2.0.tar.gz是linux下支持ipython的tar包。

    对Python Pexpect 模块的使用说明详解

    Expect 程序主要用于人机对话的模拟,就是那种系统提问,人来回答 yes/no ,或者账号登录输入用户名和密码等等的情况。因为这种情况特别多而且繁琐,所以很多语言都有各种自己的实现。最初的第一个 Expect 是由 TCL ...

Global site tag (gtag.js) - Google Analytics