• 跨平台信息获取小工具第五版本(增加了工厂模式)


    # coding=utf-8

    import threading
    import paramiko
    import os
    import time
    import xlrd
    import xlwt
    import openpyxl
    import logging


    all_row = []
    threads = []

    class Logger:
    def __init__(self,loggername):
    #创建一个logger
    self.logger = logging.getLogger(loggername)
    self.logger.setLevel(logging.DEBUG)

    cwd = os.getcwd()
    print("cwd:", cwd)
    #创建一个handler,用于写入日志文件
    log_path = os.path.dirname(os.getcwd())+"excellog" # 指定文件输出路径,注意logs是个文件夹,一定要加上/,不然会导致输出路径错误,把logs变成文件名的一部分了
    print("log_path:", log_path)
    logname = log_path + 'out.log' #指定输出的日志文件名
    print("logname: {0}",format(logname))
    fh = logging.FileHandler(logname,encoding = 'utf-8') # 指定utf-8格式编码,避免输出的日志文本乱码
    fh.setLevel(logging.DEBUG)

    #创建一个handler,用于将日志输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # 定义handler的输出格式
    formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # 给logger添加handler
    self.logger.addHandler(fh)
    self.logger.addHandler(ch)


    def get_log(self):
    """定义一个函数,回调logger实例"""
    return self.logger


    class read_excel(object):
    def __init__(self, num):
    #threading.Thread.__init__(self)
    #self.threadID = threadID
    self.num = num
    def read_excel(self):
    filePath = os.path.join(os.getcwd(), 'D:浙商银行IP.xlsx')

    wb = openpyxl.load_workbook(filePath) # 打开excel文件
    ws = wb['Sheet1']
    res = ws.cell(row=1, column=1).value # 获取单元格的内容
    # print(res)
    # print(wb.sheetnames) # 显示excel文件的所有sheet名字
    print(ws.min_row, ws.max_row, ws.max_column, ws.min_column) # 单元格的行数、列数; max_row:最大行、max_column:最大列
    print('*******************************************************')
    #all_row = []
    for row in ws.rows: # 按行获取单元格(Cell对象) - 生成器
    ev_row = []
    for cell in row:
    value = cell.value
    value.strip()
    print("value.strip():{0}".format(value.strip()))
    ev_row.append(value.strip())
    all_row.append(ev_row)
    #print("ev_row:", ev_row)
    #print('*******************************************************')
    #print(all_row)
    #print(len(all_row))
    #print("all_row[0][0]:", all_row[0][0])

    class acquisition_of_information(read_excel, threading.Thread):

    def __init__(self, num, threadID, name):
    self.logger = Logger(__name__)
    #super().__init__(self, num)
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.num = num
    print("threadID:{0} name:{1}".format(threadID, name))
    def run(self):
    # 创建SSHClient实例对象
    ssh = paramiko.SSHClient()
    # 调用方法,标识没有远程机器的公钥,允许访问
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    len1 = len(all_row)
    print("len1:", len1)
    # 连接远程机器 地址端口用户名密码
    for num in range(0, len1):
    fo = open(all_row[num][0] + ".log", "wb+")
    fo.truncate() # 清空文件内容
    all_row[num][0].strip() # 去除excel表格内容头和尾的空格
    print("all_row{0}[0]:{1}".format(num, all_row[num][0].strip()))
    all_row[num][1].strip() # 去除excel表格内容头和尾的空格
    print("all_row{0}[1]:{1}".format(num, all_row[num][1].strip()))
    all_row[num][2].strip() # 去除excel表格内容头和尾的空格
    print("all_row{0}[2]:{1}".format(num, all_row[num][2].strip()))
    try:
    ssh.connect(all_row[num][0].strip(), 22, all_row[num][1].strip(), all_row[num][2].strip())
    except IOError:
    #print ("连接服务器失败,IP:{0}".format(all_row[num][0]))
    self.logger.get_log().debug("连接服务器失败,IP:{0}".format(all_row[num][0]))
    else:
    #print ("连接服务器成功,IP:{0}".format(all_row[num][0]))
    self.logger.get_log().debug("连接服务器成功,IP:{0}".format(all_row[num][0]))
    print("num:", num)
    # 创建目录
    stdin, stdout, stderr = ssh.exec_command("ip a | grep 192 | awk '{print $2}'")
    fo.write(stdout.read())
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("uname -a | grep -i 'linux' | wc -l")
    res = stdout.read()
    print("res:", res)
    if res == b'1 ':
    str = "df -Ph "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("df -Ph")
    fo.write(stdout.read())
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)
    else:
    str = "df -Pg "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("df -Pg")
    fo.write(stdout.read())
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)
    str = "cat .profile "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("cd /root && cat .profile")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)
    str = "arp -a "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("arp -a")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)

    str = "netstat -rn "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("netstat -rn")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)

    str = "cat /etc/rc.local "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("cat /etc/rc.local")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)

    str = "cat /etc/hosts "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("cat /etc/hosts")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)

    str = "netstat -an|grep LISTEN* "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("netstat -an|grep LISTEN*")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)

    str = "ps -ef | grep java "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("ps -ef | grep java")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)

    str = "ps -ef | grep zabbix "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("ps -ef | grep zabbix")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)

    str = "ps -ef | grep ctm "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("ps -ef | grep ctm")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "***************************"
    "*************************** "
    str = str.encode()
    fo.write(str)
    str = "crontab -l "
    str = str.encode()
    fo.write(str)
    stdin, stdout, stderr = ssh.exec_command("crontab -l")
    res, err = stdout.read(), stderr.read()
    fo.write(res)
    str = "--------------------------"
    "***************************"
    "***************************"
    "--------------------------- "
    str = str.encode()
    fo.write(str)
    ssh.close()
    fo.close()
    self.logger.get_log().debug("服务器信息获取完成,IP:{0}".format(all_row[num][0]))
    num = num + 1

    def __del___(self, num):
    self.num = num


    class print_all_row(read_excel, threading.Thread):
    def __init__(self, num, threadID, name):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.num = num
    print("print_all_row name:", name)

    def run(self):
    print("all_row[0][0]:", all_row[0][0])
    print("all_row[0][1]:", all_row[0][1])
    print("all_row[0][2]:", all_row[0][2])

    class Person:
    def __init__(self):
    self.name = None
    self.gender = None

    def getName(self):
    return self.name

    def getGender(self):
    return self.gender

    class Factory:
    def getPerson(self, name, gender):
    if gender == 'M':
    return acquisition_of_information(0, "Thread-2", "zhouhaiwu")
    if gender == 'F':
    return print_all_row(0, "Thread-4", "zhouhaiwu")

    def main():
    factory = Factory()
    thread1 = factory.getPerson("zhouhaiwu", "M")
    t = Logger("small tool").get_log().debug("User %s is loging" % 'zhouhaiwu')
    start = time.time()
    excel = read_excel(0)
    excel.read_excel()
    #thread1 = acquisition_of_information(0, "Thread-2", "zhouhaiwu")
    #thread2 = acquisition_of_information(1, "Thread-3", "zhouhaiwu")
    thread3 = print_all_row(0, "Thread-4", "zhouhaiwu")
    # 开启新线程
    #thread1.start()
    thread1.start()
    #thread2.start()
    thread3.start()
    # 添加线程到线程列表
    #threads.append(thread1)
    threads.append(thread1)
    #threads.append(thread2)
    threads.append(thread3)
    # 等待所有线程完成
    for t in threads:
    t.join()
    print ("Exiting Main Thread")
    end = time.time()
    print (str(end))

    if __name__ == '__main__':
    main()
  • 相关阅读:
    JQuery文档插件
    MVC3下使用Jquery异步提交数据!
    不错的在线客服插件~
    让火狐和chorme浏览器支持uploadify带Cookie上传
    Socket服务器代码
    Winform控件加载时闪烁的解决方案!
    MVC3 无刷新验证码
    网络时间同步
    关于多线程委托的控件操作
    c# 利用反射动态给实体类对象赋值
  • 原文地址:https://www.cnblogs.com/niaocaizhou/p/11110821.html
Copyright © 2020-2023  润新知