文档章节

sw_tools_check.py

xxjbs001
 xxjbs001
发布于 2014/06/09 15:35
字数 1227
阅读 14
收藏 0
点赞 0
评论 0
#!/usr/bin/env python
#coding=utf-8
import csv
import csvtodic
from csvtodic import csvtodictlist,dictlisttocsv
from optparse import OptionParser
from optparse import OptionGroup
import logging
from pprint import pprint
from pprint import pformat
import syslog
import subprocess
import signal
import time
import select
import commands
import os
import sys


def subproc(cmd, timeout=3600,mute=True) :
        """
        subprogress to run command
        """
        rc = None
        output = ''
        #
        #print('subproc : ' + cmd)
        if not mute : print('timout : ' + str(timeout))
        try :
            #
            p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, shell=True)
            pi, po, pe = p.stdin, p.stdout, p.stderr
            while_begin = time.time()
            while True :
                to = 600
                fs = select.select([p.stdout, p.stderr], [], [], to)
                #if p.poll() : break
                #print '.....',
                if p.stdout in fs[0]:
                    #print '---xxxifs0:',fs[0]
                    tmp = p.stdout.readline()
                    if tmp :
                        output += tmp
                        #print(tmp)
                        #if not mute : print(tmp)
                    else :
                        #print '---end'
                        #print time.time()
                        while None == p.poll() : pass
                        break
                elif p.stderr in fs[0]:
                    #print "!!!!!!!!!!!!!!!"
                    tmp = p.stderr.readline()
                    if tmp :
                        output += tmp
                        #plogger.error(tmp)
                    else :
                        #print 'end'
                        #print time.time()
                        while None == p.poll() : pass
                        break
                else:
                    #print 'Timeout'
                    #os.system('ps -f')
                    s = os.popen('ps -f| grep -v grep |grep sleep').read()

                    if len(s.strip()) :
                        print('No output in sleep : ' + s)
                        continue

                    print('Timeout ' + str(to) + ' seconds without any output!')
                    print(os.popen('ps -p ' + str(p.pid)).read())
                    p.kill()

                    #os.kill(p.pid, signal.SIGKILL)
                    break
                #timeout = timeout - (time.time() - while_begin)
                # Check the total timeout
                dur = time.time() - while_begin
                if dur > timeout :
                    print('The subprocess is timeout more than ' + str(timeout))
                    break
            # return
            rc = p.poll()
            # close all fds
            p.stdin.close()
            p.stdout.close()
            p.stderr.close()
            #print('return value : ' + str(rc))

        except Exception, e :
            print('Exception : ' + str(e))
            #rc = False
        return rc, output


 
def sw_online(dic, online_flag ) : 
    if online_flag == 'online':
       if dic["cmd_install_online"] == '':
          print( '%s have no online install command' % (str(dic["description"])))
       else:   
          cmd_install = dic["cmd_install_online"].splitlines()
          #print ('%s installing latest version online !!' % (str(dic["description"])))
          i = 0 
          for h in cmd_install:
              install_code,install_output =  subproc(h)
              if install_code != 0: 
                     print ('%s install failed:%s' % (str(dic["description"]),str (install_output)))
                     i+=1
          if i == 0 :               
             print( '%s online install success!!' % (str(dic["description"])))

def sw_offline(dic, online_flag, pk_path, cmdlist ) : 
    if online_flag == 'offline':
       if dic["cmd_install_offline"] == '':
          print( '%s have no offline install command' % (str(dic["description"])))
          cmdlist.append(dic["description"]) 
       elif pk_path == '':
          print( '%s have no offline packet dir! ' % (str(dic["description"])))
       else:   
            #pk_path = 'cd ' + pk_path
           # print'pk_path is: ', pk_path
            if 'all' not in pk_path :
                pk_path = pk_path+'/'+'all'
            os.chdir(pk_path)
            dir = os.getcwd()
            #print 'dir1 is :',dir
            if dir != pk_path :
               print( '%s cd  packet dir error : %s! ' % ((str(dic["description"]), str(pk_path))))
            cmd_install = dic["cmd_install_offline"].splitlines()
           # print ('%s installing offline !!' % (str(dic["description"])))
            j = 0 
            #s = 'already installed'
            str_cd = 'cd'
            for h in cmd_install:
                  new_str = str(h)
                  if str_cd in new_str:
                   # print 'dir is :',dir  
                    new_path = dir + '/'+new_str[3:] 
                    #print "new_path is:", new_path     
                    os.chdir(new_path)  
                    new_dir = os.getcwd()
                    #print 'new_dir is :',new_dir  
                  else:
                    install_code,install_output =  subproc(h)
                    #print 'install code is :' ,install_code
                    #stri = str (install_output)
                    if install_code != 0: 
                       #if s not in stri :
                          print ('%s install failed:%s' % (str(dic["description"]),str (install_output)))
                          j +=1
            if j == 0 :
               print( '%s offline install success!!' % (str(dic["description"])))
               os.chdir(pk_path)
               dir = os.getcwd()
               #print 'dir2 is :',dir

def main() :
    """
    """
    lie = []
    sys_argv = len(sys.argv)
    #print 'sys_argv:',sys_argv
    if sys_argv==1:
       path = 'software_checking.csv'
       online = None
       pk_path = None
       check_flag = 'check'     
       print 'checking software ,wait a moment!'
       
    elif sys.argv[1] =='--with-version':
       path = 'software_checking.csv'
       online = None
       pk_path = None
       check_flag ='version'
    elif sys.argv[1] =='--force-install-online':
       path = 'software_checking.csv'
       online = 'online'
       pk_path = None
       check_flag ='version'
    elif sys.argv[1] =='--force-install-offline':
       path = 'software_checking.csv'
       online = 'offline'
       pk_path = os.getcwd()
       check_flag ='version'
    elif sys.argv[1] =='--install-online':
       path = 'software_checking.csv'
       online = None
       pk_path = None
       check_flag ='not_version'
    elif sys.argv[1] =='--install-offline':
       path = 'software_checking.csv'
       online = None
       pk_path = None
       #pk_path = os.getcwd()
       check_flag ='not_version'
    elif sys.argv[1] !='':
         
       print 'need add parameter!\none of them: \n--with-version:check tools verison \n--force-install-online: not check tools force install online\n--force-install-offline:not check tools force install offline\n--install-online: check tools ,if not exist, install online\n--install-offline:check tools ,if not exist, install offline\n if have no parameter , check tools not exits'
       return 0
    csvtodictlist(lie,path)
    #READ_ONLY = (select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR)
    #p=select.poll()
    #p.register(li,READ_ONLY)
    #result = p.poll()
    #if result == 0:
     #  print'...',
        
    #copy file to need dir cp -r i386/* /var/cache/yum/i386/
    copy_cmd ='cp -r all/i386/* /var/cache/yum/i386/'
    copy_code, copy_output =  subproc(copy_cmd)
    if copy_code !=0 :
       print 'copy dir error!!!:',copy_output
       return 0
    m = 0
    error =0
    warnning = 0
    disable  = 0
    errorlist = []
    warnninglist = []
    offcmdlist = []
    disablelist = []
    rtype = []
    otype = []
    dtype = []
    while m<len(lie):
          if lie[m]["status"] == 'required':
             sw_online(lie[m], online )
             sw_offline(lie[m], online, pk_path,offcmdlist) 
             #print lie[m]["status"]
             #print ".....",
             check_code, check_output =  subproc(lie[m]["cmd_check"])
 	     if lie[m]["cmd_version"] != '' and lie[m]["description"] != '' and check_code == 0 :	  
                 version_code,version_output =  subproc(lie[m]["cmd_version"])
                 if version_code != 0:
                    print lie[m]["description"],
                    print 'Version get error!'
                    print 'version_code is :',version_code
                    print 'version_output is :', version_output
                 elif version_code == 0:
                        # if version_output == lie[m]["expect_version"]:
                          if check_flag != 'check' and check_flag != 'not_version':
                            print lie[m]["description"],
                            print ('type:%s ,version:%s' % (str(lie[m]["type"]),str(version_output)))
             if lie[m]["cmd_version"] == '':
                if check_flag != 'check' and check_flag != 'not_version':
                   print lie[m]["description"],
                   print ('type:%s, Not find version command!\n' %(str(lie[m]["type"])))     
             if check_code != 0:
                               
               if  sys_argv != 1 and sys.argv[1] =='--install-online':
                  print('%s not exist , install online'% (str(lie[m]["description"])))
                  str_online = 'online'
                  sw_online(lie[m], str_online )
               elif sys_argv != 1 and sys.argv[1] =='--install-offline':
                  print('%s not exist , install offline'% (str(lie[m]["description"])))
                  str_online = 'offline'
                  pk_path = os.getcwd()
                  sw_offline(lie[m], str_online, pk_path,offcmdlist)
               else :    
                  error+=1
                  errorlist.append(lie[m]["description"])
                  rtype.append(lie[m]["type"])

          if lie[m]["status"] == 'optional':
             sw_online(lie[m], online )
             sw_offline(lie[m], online, pk_path, offcmdlist ) 
             #print ".....",
             check_code, check_output =  subproc(lie[m]["cmd_check"])
 	     if lie[m]["cmd_version"] != '' and lie[m]["description"] != '' and check_code == 0 :	  
                 version_code,version_output =  subproc(lie[m]["cmd_version"])
                 if version_code != 0:
                    print lie[m]["description"],
                    print 'Version get error!'
                 elif version_code == 0:
                           if check_flag != 'check' and check_flag != 'not_version':
                               print lie[m]["description"],
                               print ('type:%s , version:%s' % (str(lie[m]["type"]),str(version_output)))
                               #print 'current version is:', version_output
                            #print 'version_code is :',version_code
             if lie[m]["cmd_version"] == '':
                if check_flag != 'check' and check_flag != 'not_version' :
                   print lie[m]["description"],
                   print ('type:%s , Not find  version command!\n' %(str(lie[m]["type"])))     
                   #print 'not find get Version command'      
             if check_code != 0:
               if sys_argv != 1 and  sys.argv[1] =='--install-online':
                  print('%s not exist , install online'% (str( lie[m]["cmd_version"])))
                  str_online = 'online'
                  sw_online(lie[m], str_online )
               elif sys_argv !=1 and  sys.argv[1] =='--install-offline':
                  print('%s not exist , install offline'% (str(lie[m]["cmd_version"])))
                  str_online = 'offline'
                  pk_path = os.getcwd()
                  sw_offline(lie[m], str_online, pk_path,offcmdlist)
               else :    
                  warnning+=1
                  warnninglist.append(lie[m]["description"])
                  otype.append(lie[m]["type"])

          if lie[m]["status"] == 'disabled':
              sw_online(lie[m], online )
              disable+=1
              disablelist.append(lie[m]["description"])
              dtype.append(lie[m]["type"])
          m+=1
    if check_flag == 'check':
      l = 0     
      print '\nRequired software not find:' ,error
      if len(errorlist)==0 :
          print ('All required software are installed')
      while l<len(errorlist): 
           print ('Type:%s  Name:%s'% (str(rtype[l]),str( errorlist[l])))
           l+=1
      k = 0
      print 'Optional software not find  :' ,warnning
      if len(warnninglist)==0 :
	  print ('All optional software are installed')
      while k<len(warnninglist): 
           print ('Type:%s Name: %s'% (str(otype[k]),str( warnninglist[k])))
           k+=1
      n = 0
      print 'Disabled software :' ,disable
      if len(disablelist)==0 :
          print ('There is no disabled tools')
      while n<len(disablelist):
           print ('Type:%s  Name:%s'% (str(dtype[n]),str( disablelist[n])))
           #print disablelist[n],                           
           n+=1
    else :
       return 0    

							
if __name__=="__main__":
    main()




© 著作权归作者所有

共有 人打赏支持
xxjbs001
粉丝 55
博文 749
码字总数 215621
作品 0
浦东
QA/测试工程师
服务端测试环境hosts配置检查脚本

[本文出自天外归云的博客园] 问题 由于A测试环境和B测试环境相互耦合,B测试环境切换导致我方测试环境需要更改后台服务器的响应配置。若多台服务器中有一台服务器没有更改配置,则在测试过程...

天外归云
2017/09/14
0
0
何朝威/zscat_sw

springboot dubbo redis solr mq kafka 商城 blog cms 单机版商城 http://git.oschina.net/JiaGou-XiaoGe/payshop jeeplus单机版商城 https://gitee.com/JiaGou-XiaoGe/jeeplusBanDuoShangJi......

何朝威
2017/10/23
0
0
triaquae 启动失败

python tri_service.py status ultiprocessing_snmpMonitor.py monitor service is running... hoststatuscheck.py monitor service is running... shellinaboxd monitor service is running......

jerryyang84
2015/11/03
377
0
机器学习分析Web攻击请求之XSS

结果: [root@kali xiaokui]# python3 check.py [1 0 1] 关键点: 使用正则处理所有请求。 regex = re.compile(r"w+W") tok = lambda x: regex.findall(x) 本打算把正样本"" 处理为 "['<', '......

xi4okv
2017/12/19
0
0
ksc/raspi_router

#把树莓派打造成智能无线路由器 ###使用方法 你可以 用git检出一份 apt-get install gitgit clone http://git.oschina.net/ksc/raspi_router 或者直接下载zip压缩包 wget http://git.oschin...

ksc
2015/02/10
0
0
Mac下appium-doctor提示错误汇总

一、 提示 [Error: Could not detect Mac OS X Version from sw_vers output: '10.12'] 解决方法: 1、终端执行下面指令 grep -rl "Could not detect Mac OS X Version from sw_vers output:......

niedongri
2017/09/19
0
0
VIM配置文件vimrc

VIM配置文件vimrc .vimrc 下载 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Author: sunboy_2050" Version: 1.0" Last Change: 2011-11-11 11:11:11" http://blog.c......

长平狐
2013/01/06
201
0
VIM配置文件vimrc

VIM配置文件vimrc """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Author: sunboy_2050" Version: 1.0" Last Change: 2011-11-11 11:11:11" http://blog.csdn.net/sun......

晨曦之光
2012/03/02
1K
0
LibreSSL 2.3.3 发布,安全套接字库

LibreSSL 2.3.3 发布了。LibreSSL 是一个免费版本的 SSL/TLS 协议,来自于 OpenSSL。 LibreSSL是由四个部分组成: The openssl(1) utility, which provides tools for managing keys, certif......

oschina
2016/03/23
1K
3
交换机的端口安全

拓扑图: 静态安全的MAC地址: SW1上的配置: SW1(config)#int SW1(config)#interface f SW1(config)#interface fastEthernet 0/1 SW1(config-if)#sh SW1(config-if)#shutdown //关闭f0/1接口......

一颗成长树
2017/04/18
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

ndarray花式索引

花式索引 花式索引(Fancy indexing)是一个NumPy术语,它指的是利用整数数组进行索引。假设我们有一个8×4数组: In [117]: arr = np.empty((8, 4))In [118]: for i in range(8): ....

火力全開
1分钟前
0
0
Mybaties报错Error querying database

Mybaties我们经常用到动态SQL,如下我们利用动态去做判断,这样写当然没问题,但是当我们不是去判断orgCode(本文中orgCode一直为String类型)是否为空而是判断orgCode是否是一个值的时候该怎...

王子城
3分钟前
0
0
Android 调用手机自带的下载器下载

亲测有用,原文下载地址: 原文地址:https://blog.csdn.net/weixin_36554045/article/details/79108796 下面是原文: 创建一个广播类 public class UpdataBroadcastReceiver extends Broad...

她叫我小渝
7分钟前
0
0
idea工具debug断点红色变成灰色,断点无效

来自:idea工具debug断点红色变成灰色 没事别瞎点,禁用了断点当然不走了 看这篇博客底下的评论笑死我了 真香警告!

不开心的时候不要学习
9分钟前
0
0
知识点总结

jq如何拿到data-info的自定义属性 1.1 原生可以获取到所有属性el.attrbutes 1.2 jq的$(el).attr('属性名称') 继承的几种方式,原型链 2.1 扩展原型对象实现继承 2.2 替换原型对象实现继承 2....

litCabbage
12分钟前
0
0
python语言规范

http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/...

ghou-靠墙哭
16分钟前
0
0
istio 监控,遥测 (理论)

Istio提供了一种灵活的模型来强制执行授权策略并收集网格中服务的遥测。 基础架构后端旨在提供用于构建服务的支持功能。它们包括诸如访问控制系统,遥测捕获系统,配额执行系统,计费系统等之...

xiaomin0322
18分钟前
0
0
阿里资深专家面试问题收集

corejava hashcode相等的两个对象一定相等吗?equals呢?反过来相等吗? 介绍一下集合框架? hashtable,hashmap底层实现是什么?hashtable和concurrenthashmap底层实现的区别? hashmap和treemap的...

undefine
19分钟前
8
0
alpine安装软件指定安装源

linux-alpine安装软件指定安装源 一、永久修改apk下载源地址 vi etc/apk/repositories 替换成阿里源 http://mirrors.aliyun.com/alpine/v3.8/main/http://mirrors.aliyun.com/alpine/v3...

我心中有猛狗
20分钟前
0
0
Centos7通过yum安装nginx

添加源地址(直接install可能不是最新版本的) sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm 安装 sudo yum install -y ng......

iplusx
21分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部