Linux Python巡检脚本

简介: Linux Python巡检脚本
# -*- coding: utf-8 -*-
"""
linux 自动化脚本
# @Time: 2022/11/4 10:20
# @Author: lln
# @File: linuxOpsStartUp.py
"""
import json
import os
import platform
import time
def runCommand(command):
    """
    执行命令,将所有读到的数据去除空行
    :param command: 命令
    :return: 去除空行后的命令
    """
    lines = os.popen(command).readlines()
    res = []
    for line in lines:
        res.append(line.replace('\n', ''))
    return res
def getSystemInfo():
    """
    使用内置库获取系统信息
    """
    res = {
        "操作系统名称及版本号": platform.platform(),
        "操作系统版本号": platform.version(),
        "操作系统的位数": platform.architecture(),
        "计算机类型": platform.machine(),
        "网络名称": platform.node(),
        "处理器信息": platform.processor(),
    }
    return res
def getSystemStatus():
    """
    系统信息,仅支持centos进行查询
    """
    # 系统
    OS = runCommand("uname -o")
    # 发行版本
    Release = runCommand("cat /etc/redhat-release 2>/dev/null")
    # 内核
    Kernel = runCommand("uname -r")
    # 主机名
    Hostname = runCommand("uname -n")
    # 当前时间
    LocalTime = runCommand("date +'%F %T'")
    # 最后启动
    LastReboot = runCommand("who -b | awk '{print $3,$4}'")
    # 运行时间
    Uptime = runCommand("date +'%F %T'")
    # 当前时区信息
    time_zone = runCommand("date -R")
    res = {
        "系统": OS,
        "发行版本": Release,
        "内核": Kernel,
        "主机名": Hostname,
        "当前时间": LocalTime,
        "最后启动": LastReboot,
        "运行时间": Uptime,
        "时区信息": time_zone
    }
    return res
def getCpuStatus():
    """
    CPU信息
    """
    # 物理CPU个数
    physical_cpus = runCommand("grep 'physical id' /proc/cpuinfo| sort | uniq | wc -l")
    # 逻辑CPU个数
    virt_cpus = runCommand("grep 'processor' /proc/cpuinfo | wc -l")
    # 每CPU核心数
    cpu_kernels = runCommand("grep 'cores' /proc/cpuinfo|uniq| awk -F ': ' '{print $2}'")
    # CPU型号
    cpu_type = runCommand("grep 'model name' /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq")
    # CPU架构
    cpu_arch = runCommand("uname -m")
    res = {
        '物理CPU个数': physical_cpus,
        '逻辑CPU个数': virt_cpus,
        '每CPU核心数': cpu_kernels,
        'CPU型号': cpu_type,
        'CPU架构': cpu_arch
    }
    return res
def getMemStatus():
    """
    内存信息
    """
    # 总内存
    MemTotal = runCommand("grep MemTotal /proc/meminfo| awk '{print $2}'")
    MemTotal_Num = map(float, MemTotal)[0]
    # 可用内存
    MemFree = runCommand("grep MemFree /proc/meminfo| awk '{print $2}'")
    MemFree_Num = map(float, MemFree)[0]
    # 比例
    Proportion = '{:.4%}'.format(MemFree_Num / MemTotal_Num)
    res = {
        '总内存(GB)': '{:.5}'.format(float(MemTotal_Num / 1024 / 1024)),
        '可用内存(GB)': '{:.5}'.format(float(MemFree_Num / 1024 / 1024)),
        '已用比例(%)': Proportion
    }
    return res
def getMemStatusSimple():
    MemTotal = runCommand("free -h")
    res = {
        '内存总览': MemTotal
    }
    return res
def getDiskStatus():
    """
    磁盘检查
    """
    # 生成临时数据记录文件
    # os.popen("df -TP | sed '1d' | awk '$2!='tmpfs'{print}'")
    # os.popen("df -hTP | sed 's/Mounted on/Mounted/'> /tmp/disk")
    # 硬盘总量
    DiskAllInfo = runCommand("df -h | grep -v docker")
    DiskTotal = runCommand("df -TP | sed '1d' | awk '$2!='tmpfs'{print}'| awk '{total+=$3}END{print total}'")
    DiskTotalNum = int(DiskTotal[0])
    # 硬盘使用量
    DiskUsed = runCommand("df -TP | sed '1d' | awk '$2!='tmpfs'{print}'| awk '{total+=$4}END{print total}'")
    DiskUsedNum = int(DiskUsed[0])
    # 硬盘空余量
    DiskFree = DiskTotalNum - DiskUsedNum
    # 硬盘使用比例
    DiskUsedPercent = '{:.2%}'.format(DiskUsedNum / DiskTotalNum)
    # 索引总量
    InodeTotal = runCommand("df -iTP | sed '1d' | awk '$2!='tmpfs'{print}' | awk '{total+=$3}END{print total}' ")
    InodeTotal_Num = int(InodeTotal[0])
    # 索引使用量
    InodeUsed = runCommand("df -iTP | sed '1d' | awk '$2!='tmpfs'{print}' | awk '{total+=$4}END{print total}' ")
    InodeUsed_Num = int(InodeUsed[0])
    # 索引剩余量
    InodeFree = InodeTotal_Num - InodeUsed_Num
    # 索引使用比例
    InodePercent = '{:.2%}'.format(InodeUsed_Num / InodeTotal_Num)
    res = {
        '磁盘总览': DiskAllInfo,
        '硬盘总量(GB)': int(DiskTotalNum / 1024 / 1024),
        '硬盘使用量(GB)': int(DiskUsedNum / 1024 / 1024),
        '硬盘空余量(GB)': int(DiskFree / 1024 / 1024),
        '硬盘使用比例(%)': DiskUsedPercent,
        '索引总量(MB)': int(InodeTotal_Num / 1021),
        '索引使用量(MB)': int(InodeUsed_Num / 1021),
        '索引剩余量(MB)': int(InodeFree / 1021),
        '索引使用比例(%)': InodePercent,
    }
    return res
def getNetworkStatus():
    """
    网络检查
    """
    GATEWAY = runCommand("ip route | grep default | awk '{print $3}'")
    DNS = runCommand("grep nameserver /etc/resolv.conf| grep -v '#' | awk '{print $2}' | tr '\n' ',' | sed 's/,$//'")
    IP = runCommand(
        "ip -f inet addr | grep -v 127.0.0.1 | grep inet | awk '{print $NF,$2}' | tr '\n' ',' | sed 's/,$//'")
    # TODO 语句有问题会报错,sed的错误,需要检查下执行情况
    # MAC = runCommand("ip link | grep -v 'LOOPBACK\|loopback' | awk '{print $2}' | sed 'N;s/\n//' | tr '\n' ',' | sed 's/,$//'")
    res = {
        'GATEWAY': GATEWAY,
        'DNS': DNS,
        'IP': IP
        # 'MAC': MAC
    }
    return res
def getUserStatus():
    """
    所有用户和空密码用户
    """
    all_user = runCommand("awk -F':' '{ print $1}' /etc/passwd")
    empty_passwd_user = runCommand("getent shadow | grep -Po '^[^:]*(?=::)'")
    res = {
        '所有用户名': all_user,
        '空密码用户': empty_passwd_user
    }
    return res
def getJdkStatus():
    """
    jdk信息
    """
    jdkInfo = runCommand("java -version 2>&1")
    res = {
        'jdk信息': jdkInfo
    }
    return res
def getFirewallStatus():
    """
    防火墙
    """
    firewall = runCommand("firewall-cmd --state 2>&1")
    # 兼容 ubuntu 防火墙命令报错 sh: not found 特殊处理
    for info in firewall:
        if "not found" in info:
            firewall = runCommand("ufw status")
    res = {
        '防火墙状态': firewall
    }
    return res
def sshStatus():
    """
    ssh 检查
    """
    sshActive = runCommand("systemctl is-active sshd.service")
    sshNetstat = runCommand("sudo netstat -atlunp | grep sshd")
    res = {
        'ssh开启状态': sshActive,
        'ssh运行情况': sshNetstat
    }
    return res
def ntpStatus():
    """
    ntp 检查
    """
    ntpActive = runCommand("systemctl is-active ntpd")
    res = {
        'ntp运行情况': ntpActive
    }
    return res
def dockerStatus():
    """
    docker 检查
    """
    dk_version = runCommand("docker -v")
    dk_stats = []
    for info in dk_version:
        if "version" not in info:
            dk_version = "未安装docker"
        else:
            lines = os.popen(
                "docker stats --all --no-stream").readlines()
            for line in lines:
                dk_stats.append(line.replace('\n', ''))
    dp_version = runCommand("docker-compose --version")
    for info in dp_version:
        if "version" not in info:
            dp_version = "未安装docker-compose"
    res = {
        'docker version': dk_version,
        'docker-compose version': dp_version,
        'docker stats': dk_stats
    }
    return res
def createReportFile(name, text):
    """
    创建report的txt文件,并写入数据
    """
    report_dir = os.getcwd() + os.sep + "report" + os.sep
    # 判断当前路径是否存在,没有则创建new文件夹
    if not os.path.exists(report_dir):
        os.makedirs(report_dir)
    # 在当前py文件所在路径下的new文件中创建txt
    report_file = report_dir + name + '.txt'
    # 打开文件,open()函数用于打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。
    file = open(report_file, 'w')
    # 写入内容信息
    file.write(text)
    file.close()
    print('report_file create success', report_file)
def printSinfcloud():
    print("+------------------------------------------------+")
    print("|       欢迎使用SinfCloud自动巡检工具            |")
    print("| ____  _        __  ____ _                 _    |")
    print("|/ ___|(_)_ __  / _|/ ___| | ___  _   _  __| |   |")
    print("|\___ \| |  _ \| |_| |   | |/ _ \| | | |/ _  |   |")
    print("| ___) | | | | |  _| |___| | (_) | |_| | (_| |   |")
    print("||____/|_|_| |_|_|  \____|_|\___/ \__,_|\__,_|   |")
    print("|                                                |")
    print("+------------------------------------------------+")
if __name__ == '__main__':
    printSinfcloud()
    outputFileName = time.strftime('%Y-%m-%d', time.localtime(time.time())) + "_report"
    report = list()
    report.append(getSystemInfo())
    report.append(getSystemStatus())
    report.append(getCpuStatus())
    report.append(getMemStatusSimple())
    report.append(getDiskStatus())
    report.append(getNetworkStatus())
    report.append(getUserStatus())
    report.append(getJdkStatus())
    report.append(getFirewallStatus())
    report.append(sshStatus())
    report.append(ntpStatus())
    report.append(dockerStatus())
    createReportFile(outputFileName,
                     json.dumps(report, sort_keys=True, indent=4, separators=(',', ':'), ensure_ascii=False))


目录
相关文章
|
5天前
|
Shell Linux
【linux】Shell脚本中basename和dirname的详细用法教程
本文详细介绍了Linux Shell脚本中 `basename`和 `dirname`命令的用法,包括去除路径信息、去除后缀、批量处理文件名和路径等。同时,通过文件备份和日志文件分离的实践应用,展示了这两个命令在实际脚本中的应用场景。希望本文能帮助您更好地理解和应用 `basename`和 `dirname`命令,提高Shell脚本编写的效率和灵活性。
60 32
|
15天前
|
存储 Linux 网络安全
linux应急响应检查脚本
通过这个脚本,可以快速收集系统的关键信息,有助于在发生问题时进行及时的应急响应和分析。
74 34
|
25天前
|
安全 Linux 网络安全
利用Python脚本自动备份网络设备配置
通过本文的介绍,我们了解了如何利用Python脚本自动备份网络设备配置。该脚本使用 `paramiko`库通过SSH连接到设备,获取并保存配置文件。通过定时任务调度,可以实现定期自动备份,确保网络设备配置的安全和可用。希望这些内容能够帮助你在实际工作中实现网络设备的自动化备份。
51 14
|
2月前
|
Python
自动化微信朋友圈:Python脚本实现自动发布动态
本文介绍如何使用Python脚本自动化发布微信朋友圈动态,节省手动输入的时间。主要依赖`pyautogui`、`time`、`pyperclip`等库,通过模拟鼠标和键盘操作实现自动发布。代码涵盖打开微信、定位朋友圈、准备输入框、模拟打字等功能。虽然该方法能提高效率,但需注意可能违反微信使用条款,存在风险。定期更新脚本以适应微信界面变化也很重要。
213 61
|
2月前
|
消息中间件 Java Kafka
【手把手教你Linux环境下快速搭建Kafka集群】内含脚本分发教程,实现一键部署多个Kafka节点
本文介绍了Kafka集群的搭建过程,涵盖从虚拟机安装到集群测试的详细步骤。首先规划了集群架构,包括三台Kafka Broker节点,并说明了分布式环境下的服务进程配置。接着,通过VMware导入模板机并克隆出三台虚拟机(kafka-broker1、kafka-broker2、kafka-broker3),分别设置IP地址和主机名。随后,依次安装JDK、ZooKeeper和Kafka,并配置相应的环境变量与启动脚本,确保各组件能正常运行。最后,通过编写启停脚本简化集群的操作流程,并对集群进行测试,验证其功能完整性。整个过程强调了自动化脚本的应用,提高了部署效率。
【手把手教你Linux环境下快速搭建Kafka集群】内含脚本分发教程,实现一键部署多个Kafka节点
|
2月前
|
Linux Python
Linux 安装python3.7.6
本教程介绍在Linux系统上安装Python 3.7.6的步骤。首先使用`yum`安装依赖环境,包括zlib、openssl等开发库。接着通过`wget`下载Python 3.7.6源码包并解压。创建目标文件夹`/usr/local/python3`后,进入解压目录执行配置、编译和安装命令。最后设置软链接,使`python3`和`pip3`命令生效。
|
2月前
|
数据挖掘 vr&ar C++
让UE自动运行Python脚本:实现与实例解析
本文介绍如何配置Unreal Engine(UE)以自动运行Python脚本,提高开发效率。通过安装Python、配置UE环境及使用第三方插件,实现Python与UE的集成。结合蓝图和C++示例,展示自动化任务处理、关卡生成及数据分析等应用场景。
178 5
|
2月前
|
数据采集 存储 监控
21个Python脚本自动执行日常任务(2)
21个Python脚本自动执行日常任务(2)
129 7
21个Python脚本自动执行日常任务(2)
|
2月前
|
Android开发 开发者 Python
通过标签清理微信好友:Python自动化脚本解析
微信已成为日常生活中的重要社交工具,但随着使用时间增长,好友列表可能变得臃肿。本文介绍了一个基于 Python 的自动化脚本,利用 `uiautomator2` 库,通过模拟用户操作实现根据标签批量清理微信好友的功能。脚本包括环境准备、类定义、方法实现等部分,详细解析了如何通过标签筛选并删除好友,适合需要批量管理微信好友的用户。
108 7
|
3月前
|
监控 数据挖掘 数据安全/隐私保护
Python脚本:自动化下载视频的日志记录
Python脚本:自动化下载视频的日志记录

热门文章

最新文章