欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)Linux服務(wù)器自動(dòng)巡檢腳本

 更新時(shí)間:2025年06月06日 10:39:08   作者:小碼哥  
這篇文章主要為大家介紹了一個(gè)使用Python語(yǔ)言實(shí)現(xiàn)的Linux服務(wù)器自動(dòng)巡檢腳本,只需配置服務(wù)器ip、用戶名、密碼即可實(shí)現(xiàn)服務(wù)器自動(dòng)巡檢,巡檢日志以txt文件輸出,免去了挨個(gè)敲命令巡檢的麻煩

概述

最近抽時(shí)間寫了一個(gè)自動(dòng)巡檢腳本,只需配置服務(wù)器ip、用戶名、密碼即可實(shí)現(xiàn)服務(wù)器自動(dòng)巡檢,巡檢日志以txt文件輸出,免去了挨個(gè)敲命令巡檢的麻煩,腳本比較簡(jiǎn)單可拉去代碼進(jìn)行二次開發(fā)。可以加上定時(shí)任務(wù)和巡檢報(bào)告發(fā)送郵箱功能,實(shí)現(xiàn)完全托管。

源碼

以下是完整代碼:

#!/usr/bin/python3
from netmiko.huawei.huawei import HuaweiSSH
import os
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

CMD_STR = 'cmd_str'
CMD_NAME = 'name'
IP = 'ip'
USER_NAME = 'username'
PASSWORD = 'password'

# email config
smtp_host = '你的郵箱發(fā)送付服務(wù)地址'
smtp_port = 25
smtp_email = '你的發(fā)送郵箱號(hào)'
# 用戶名,默認(rèn)為發(fā)件人郵箱前綴
smtp_user ='你的發(fā)送郵箱號(hào)'
# 密碼(注意,某些郵箱需要為SMTP服務(wù)單獨(dú)設(shè)置授權(quán)碼,詳情查看相關(guān)幫助)
smtp_password = '你的發(fā)送郵箱密碼'

class ServerMaintenance:
    net_connect = None
    curr_dir = os.getcwd()
    fo = None
    file_name = None
    email_files = []

    # 建立服務(wù)器連接
    def Connect_HuaweiSSH(self, _ip, _user_name, _pw):
        try:
            S5720 = {
                'device_type': 'huawei',
                'ip': _ip,
                'username': _user_name,
                'password': _pw,
            }
            # 實(shí)例化HuaweiSSH
            net_connect = HuaweiSSH(**S5720)
            self.net_connect = net_connect
        except:
            print("連接" + _ip + "錯(cuò)誤")

    # 運(yùn)行指令
    def execute(self, cmd_str, cmd_name):
        result = self.net_connect.send_command(cmd_str)
        print(result)
        self.printFile('\n-------------------------任務(wù)【' + cmd_name + '】開始巡查 -------------------------\n')
        self.printFile(result)
        self.printFile('\n-------------------------任務(wù)【' + cmd_name + '】結(jié)束巡查 -------------------------\n')
        return result

    # 關(guān)閉連接
    def disconnect(self):
        self.net_connect.disconnect()
        print("連接斷開" + self.net_connect)

    # 文件寫入
    def printFile(self, txt):
        self.fo.write(txt)
    # 發(fā)送郵箱
    def sendEmail(self):
        msg = MIMEMultipart()
        msg['From'] = Header("master", 'utf-8')
        msg['To'] = Header('13693567027@163.com', 'utf-8')
        subject = 'Test Email'
        msg['Subject'] = Header(subject, 'utf-8')
        # 郵件正文內(nèi)容
        content = ''


        for filename in self.email_files:
            content+=filename+'\n'
            # 郵件附件
            att = MIMEText(open(filename+'.txt', 'rb').read(), 'base64', 'utf-8')
            att['Content-Type'] = 'application/octet-stream'  # 指定文件格式
            att["Content-Disposition"] = 'attachment; filename="服務(wù)器巡檢報(bào)告.txt"'
            msg.attach(att)

        msg.attach(MIMEText(content, 'plain', 'utf-8'))
        try:
            # # 創(chuàng)建安全連接,使用SMTP_SSL連接SMTP服務(wù)器
            smtp_client = smtplib.SMTP(smtp_host)  # 實(shí)例化對(duì)象
            smtp_client.connect(smtp_host, smtp_port)  # 連接163郵箱服務(wù)器,端口號(hào)為25
            # # 向服務(wù)器標(biāo)識(shí)用戶身份
            smtp_client.login(smtp_user, smtp_password)
            # 發(fā)送郵件
            smtp_client.sendmail(smtp_user, '13693567027@163.com', msg.as_string())
            print("郵件發(fā)送成功")
        except smtplib.SMTPException as e:
            print("Error: 無(wú)法發(fā)送郵件 ", e)

        # 關(guān)閉SMTP連接
        smtp_client.quit()

    def run(self,commands,hosts):
        for host in hosts:
            self.file_name = "服務(wù)器巡查_" + host[IP] + '_' + datetime.now().strftime(format="%Y年%m月%d日%H時(shí)%M分%S秒")
            self.email_files.append(self.file_name)
            self.fo = open(self.file_name + ".txt", 'w+', encoding='utf-8')
            self.Connect_HuaweiSSH(host[IP], host[USER_NAME], host[PASSWORD])
            self.printFile(
                '\n================================主機(jī)開始巡檢: ' + host[IP] + '================================\n')
            for command in commands:
                self.execute(command[CMD_STR], command[CMD_NAME])
            self.printFile(
                '\n================================主機(jī)巡檢結(jié)束: ' + host[IP] + '================================\n')



commands = [
    {CMD_STR: "ps -ef |grep java", CMD_NAME: "運(yùn)行中的應(yīng)用"},
    {CMD_STR: "docker ps", CMD_NAME: "運(yùn)行中的容器"},
    {CMD_STR: "df -TH", CMD_NAME: "磁盤空間"},
    {CMD_STR: "free -h", CMD_NAME: "內(nèi)存"},
    {CMD_STR: "ps -ef", CMD_NAME: "進(jìn)程"},
    {CMD_STR: "crontab  -l", CMD_NAME: "定時(shí)任務(wù)"},
    {CMD_STR: "cat /var/log/messages|grep ERROR && dmesg |grep ERROR", CMD_NAME: "操作系統(tǒng)日志"},
    {CMD_STR: "date", CMD_NAME: "操作系統(tǒng)時(shí)間"},
    {CMD_STR: "firewall-cmd --list-all", CMD_NAME: "防火墻"},
    {CMD_STR: "dmidecode -t system", CMD_NAME: "服務(wù)器型號(hào)"},
    {CMD_STR: "uname -a && uname -r", CMD_NAME: "操作系統(tǒng)與內(nèi)核"},
    {CMD_STR: "last", CMD_NAME: "用戶登錄日志"},
]

hosts = [
    {IP: '你的服務(wù)器ip', USER_NAME: '你的服務(wù)器賬號(hào)', PASSWORD: '你的服務(wù)器密碼'}
]

serverMain = ServerMaintenance()
serverMain.run(commands,hosts)
serverMain.sendEmail()

Linux系統(tǒng)巡檢常用命令

1、查看服務(wù)器型號(hào): dmidecode  grep Product Name 或者 dmidecode -t system 或者 dmidecode -t1 或者dmidecodegrep“Product"

2、查看主板的序列號(hào): dmidecode grep Serial Number 或者 dmidecode -t system|grep Serial Number

3、統(tǒng)-查看服務(wù)器SN序列號(hào)和型號(hào): dmidecode grep “System lnformation” -A9 egrepManufacturer/Product Serial!

4、查看內(nèi)核/操作系統(tǒng): uname-a/r

5、查看操作系統(tǒng)版本: head -n ]/etc/issue #是數(shù)字1不是字母L查看centos操作系統(tǒng)版本: cat /etc/centos-release
查看版本: cat /proc/version #類似uname -r

6、查看CPU信息 (型號(hào)): cat/proc/cpuinfolgrep namelcut-f2 -d:|unig -c

7、查看物理CPU個(gè)數(shù): cat /proc/cpuinfol grep“physicalid” sort uniql wc -l

8、查看每個(gè)物理CPU中core的個(gè)數(shù)(即核數(shù)): cat /proc/cpuinfo grep “cpu cores”|uniq

9、查看邏輯CPU的個(gè)數(shù): cat /proc/cpuinfolgrep“processor”]wc-

10、查看內(nèi)存信息: cat /proc/meminfo或者free 命令 或者cat /proc/meminfo grep MemTota查看內(nèi)存信息: dmidecode -t memory 或者dmidecode -t memory|grep     

  • 查看內(nèi)存總量: grep MemTotal /proc/meminfo
  • 查看空閑內(nèi)存量: grep MemFree /proc/meminfo

11、查看所有swap分區(qū)的信息: cat /proc/swaps

查看內(nèi)存使用量和交換區(qū)使用量: free-m

12、查看磁盤信息: fdisk - 或者fdisk -grep Disk

查看各分區(qū)使用情況: df -h

13、列出所有啟動(dòng)的系統(tǒng)服務(wù): chkconfig - list|grep on

14、查看磁盤IO的性能:iostat -x 10

15、列出所有PCI設(shè)備: Ispci -tv

  • 列出所有USB設(shè)備: lsusb -tv
  • 列出加載的內(nèi)核模塊: lsmod
  • 查看pci設(shè)備的信息: cat /proc/pci

16、列出所有USB設(shè)備的linux系統(tǒng)信息命令:Isusb -tv

17、查看計(jì)算機(jī)名: hostname

18、查看指定目錄的大小: du -sh< 目錄名>

19、查看系統(tǒng)運(yùn)行時(shí)間、用戶數(shù)、負(fù)載: uptime

查看系統(tǒng)負(fù)載: cat /proc/loadavg

20、查看所有用戶的定時(shí)任務(wù): crontab -

21、查看掛接的分區(qū)狀態(tài): mount|column -t

22、查看所有網(wǎng)絡(luò)接口的屬性: ifconfig

23、查看防火墻設(shè)置:iptables -L

24、查看路由表: route -n

25、查看所有監(jiān)聽(tīng)端口: netstat -Intp

26、查看所有已經(jīng)建立的連接: netstat -antp

查看網(wǎng)絡(luò)統(tǒng)計(jì)信息: netstat -s

27、查看設(shè)備io端口: cat /proc/ioports

29、查看中斷: cat /proc/interrupts

30、查看環(huán)境變量:env

31、查看所有進(jìn)程:ps -ef

實(shí)時(shí)顯示進(jìn)程狀態(tài): top

32、查看活動(dòng)用戶: who

33、查看看磁盤參數(shù)(僅適用于IDE設(shè)備): hdparm -i/dev/hda

查看啟動(dòng)時(shí)IDE設(shè)備檢測(cè)狀況: dmesg|grepIDE

34、查看指定用戶信息: id< 用戶名>

35、查看用戶登錄日志: last

36、查看系統(tǒng)所有用戶: cut -d:f1 /etc/passwd

37、查看系統(tǒng)所有組: cut -d: -f1 /etc/group

38、安全檢查: cat /etc/passwd cat /etc/group

39、查看DB2數(shù)據(jù)庫(kù)的表空間詳情: db2 list tablespaces show detail

40、日志查看:

  • dmesg<目錄/日志文件>
  • cat /var <目錄/日志文件>
  • tail -f <目錄/日志文件>/var/log/message 系統(tǒng)啟動(dòng)后的信息和錯(cuò)誤日志,是Red Hat Linux中最常用的日志之-/var/log/secure 與安全相關(guān)的日志信息
  • /var/log/maillog 與郵件相關(guān)的日志信息
  • /var/log/cron 與定時(shí)任務(wù)相關(guān)的日志信息
  • /var/log/spooler 與UUCP和news設(shè)備相關(guān)的日志信息
  • /var/log/boot.log 守護(hù)進(jìn)程啟動(dòng)和停止相關(guān)的日志消息

方法補(bǔ)充

Linux-Python運(yùn)維自動(dòng)巡檢腳本

1.使用說(shuō)明

createTime: 2022-12-21

createBy: lln

createInfo: 

檢查服務(wù)器磁盤、內(nèi)存、網(wǎng)絡(luò)、docker容器等信息,以json格式輸出至同目錄下的report文件夾中,便于運(yùn)維人員查看。

環(huán)境說(shuō)明

Centos版本 >=7

Python2版本 >=2.6 (兼容python3)

使用步驟

1、將腳本文件linuxOpsStartUp.py放入任意目錄下

2、執(zhí)行 python linuxOpsStartUp.py 命令,進(jìn)行服務(wù)器信息檢查,檢查結(jié)果輸出至同目錄下report文件夾中。

檢查結(jié)果示例

[
    {
        "最后啟動(dòng)": [
            "15:08 "
        ],
        "發(fā)行版本": [
            "CentOS Linux release 7.9.2009 (Core)"
        ],
        "當(dāng)前時(shí)間": [
            "2022-12-20 17:50:13"
        ],
        "系統(tǒng)": [
            "GNU/Linux"
        ],
        "時(shí)區(qū)信息": [
            "Tue, 20 Dec 2022 17:50:13 +0800"
        ],
        "運(yùn)行時(shí)間": [
            "2022-12-20 17:50:13"
        ],
        "內(nèi)核": [
            "3.10.0-1160.6.1.el7.x86_64"
        ],
        "主機(jī)名": [
            "localhost.localdomain"
        ]
    },
    {
        "物理CPU個(gè)數(shù)": [
            "1"
        ],
        "CPU架構(gòu)": [
            "x86_64"
        ],
        "每CPU核心數(shù)": [
            "4"
        ],
        "CPU型號(hào)": [
            "Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz"
        ],
        "邏輯CPU個(gè)數(shù)": [
            "4"
        ]
    },
    {
        "內(nèi)存總覽": [
            "              total        used        free      shared  buff/cache   available",
            "Mem:            15G        9.2G        307M        783M        5.9G        5.1G",
            "Swap:          7.8G        237M        7.6G"
        ]
    },
    {
        "索引總量(MB)": 1125058,
        "硬盤使用量(GB)": 1060,
        "磁盤總覽": [
            "文件系統(tǒng)                 容量  已用  可用 已用% 掛載點(diǎn)",
            "devtmpfs                 7.8G     0  7.8G    0% /dev",
            "tmpfs                    7.8G     0  7.8G    0% /dev/shm",
            "tmpfs                    7.8G  732M  7.1G   10% /run",
            "tmpfs                    7.8G     0  7.8G    0% /sys/fs/cgroup",
            "/dev/mapper/centos-root   50G   31G   20G   62% /",
            "/dev/sda2               1014M  188M  827M   19% /boot",
            "/dev/sda1                200M   12M  189M    6% /boot/efi",
            "/dev/mapper/centos-home  2.0T   38G  2.0T    2% /home",
            "tmpfs                    1.6G     0  1.6G    0% /run/user/0"
        ],
        "硬盤總量(GB)": 3726,
        "硬盤使用比例(%)": "28.46%",
        "索引剩余量(MB)": 1095859,
        "索引使用量(MB)": 29198,
        "硬盤空余量(GB)": 2665,
        "索引使用比例(%)": "2.60%"
    },
    {
        "IP": [
            "enp3s0 192.168.11.127/24,br-1849b047c9dd 172.19.0.1/16,docker0 172.17.0.1/16,br-7e3fcfcbbbdf 172.18.0.1/16,br-e9753d63540c 172.20.0.1/16"
        ],
        "GATEWAY": [
            "192.168.11.1"
        ],
        "DNS": [
            "223.5.5.5"
        ]
    },
    {
        "空密碼用戶": [
            "test"
        ],
        "所有用戶名": [
            "root",
            "bin",
            "daemon",
            "ntp"
        ]
    },
    {
        "jdk信息": [
            "openjdk version \"1.8.0_275\"",
            "OpenJDK Runtime Environment (build 1.8.0_275-b01)",
            "OpenJDK 64-Bit Server VM (build 25.275-b01, mixed mode)"
        ]
    },
    {
        "防火墻狀態(tài)": [
            "not running"
        ]
    },
    {
        "ssh開啟狀態(tài)": [
            "active"
        ],
        "ssh運(yùn)行情況": [
            "tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1062/sshd           ",
            "tcp        0      0 192.168.11.127:22       192.168.11.194:50779    ESTABLISHED 10513/sshd: root@pt ",
            "tcp        0      0 192.168.11.127:22       192.168.11.194:52458    ESTABLISHED 17626/sshd: root@no ",
            "tcp6       0      0 :::22                   :::*                    LISTEN      1062/sshd           "
        ]
    },
    {
        "ntp運(yùn)行情況": [
            "active"
        ]
    },
    {
        "docker-compose version": [
            "docker-compose version 1.29.2, build unknown"
        ],
        "docker version": [
            "Docker version 20.10.0, build 7287ab3"
        ],
        "docket stats": [
            "CONTAINER ID   NAME                                       CPU %     MEM USAGE / LIMIT     MEM %     NET I/O           BLOCK I/O         PIDS",
            "d36c48b5c621   sinfcloud-rabbitmq                         1.31%     122.7MiB / 15.47GiB   0.77%     3.78GB / 4.09GB   63.2MB / 2.58MB   29",
            "40db1a93ec2d   linux-command                              0.00%     144KiB / 15.47GiB     0.00%     62.1kB / 1.3MB    1.44MB / 0B       1"
        ]
    }
]

腳本完整代碼

# -*- coding: utf-8 -*-
"""
linux 自動(dòng)化腳本
# @Time: 2022/11/4 10:20
# @Author: lln
# @File: linuxOpsStartUp.py
"""
import json
import os
import platform
import time


def runCommand(command):
    """
    執(zhí)行命令,將所有讀到的數(shù)據(jù)去除空行
    :param command: 命令
    :return: 去除空行后的命令
    """
    lines = os.popen(command).readlines()
    res = []
    for line in lines:
        res.append(line.replace('\n', ''))
    return res


def getSystemInfo():
    """
    使用內(nèi)置庫(kù)獲取系統(tǒng)信息
    """
    res = {
        "操作系統(tǒng)名稱及版本號(hào)": platform.platform(),
        "操作系統(tǒng)版本號(hào)": platform.version(),
        "操作系統(tǒng)的位數(shù)": platform.architecture(),
        "計(jì)算機(jī)類型": platform.machine(),
        "網(wǎng)絡(luò)名稱": platform.node(),
        "處理器信息": platform.processor(),
    }
    return res


def getSystemStatus():
    """
    系統(tǒng)信息,僅支持centos進(jìn)行查詢
    """
    # 系統(tǒng)
    OS = runCommand("uname -o")
    # 發(fā)行版本
    Release = runCommand("cat /etc/redhat-release 2>/dev/null")
    # 內(nèi)核
    Kernel = runCommand("uname -r")
    # 主機(jī)名
    Hostname = runCommand("uname -n")
    # 當(dāng)前時(shí)間
    LocalTime = runCommand("date +'%F %T'")
    # 最后啟動(dòng)
    LastReboot = runCommand("who -b | awk '{print $3,$4}'")
    # 運(yùn)行時(shí)間
    Uptime = runCommand("date +'%F %T'")
    # 當(dāng)前時(shí)區(qū)信息
    time_zone = runCommand("date -R")
    res = {
        "系統(tǒng)": OS,
        "發(fā)行版本": Release,
        "內(nèi)核": Kernel,
        "主機(jī)名": Hostname,
        "當(dāng)前時(shí)間": LocalTime,
        "最后啟動(dòng)": LastReboot,
        "運(yùn)行時(shí)間": Uptime,
        "時(shí)區(qū)信息": time_zone
    }
    return res


def getCpuStatus():
    """
    CPU信息
    """
    # 物理CPU個(gè)數(shù)
    physical_cpus = runCommand("grep 'physical id' /proc/cpuinfo| sort | uniq | wc -l")
    # 邏輯CPU個(gè)數(shù)
    virt_cpus = runCommand("grep 'processor' /proc/cpuinfo | wc -l")
    # 每CPU核心數(shù)
    cpu_kernels = runCommand("grep 'cores' /proc/cpuinfo|uniq| awk -F ': ' '{print $2}'")
    # CPU型號(hào)
    cpu_type = runCommand("grep 'model name' /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq")
    # CPU架構(gòu)
    cpu_arch = runCommand("uname -m")
    res = {
        '物理CPU個(gè)數(shù)': physical_cpus,
        '邏輯CPU個(gè)數(shù)': virt_cpus,
        '每CPU核心數(shù)': cpu_kernels,
        'CPU型號(hào)': cpu_type,
        'CPU架構(gòu)': cpu_arch
    }
    return res


def getMemStatus():
    """
    內(nèi)存信息
    """
    # 總內(nèi)存
    MemTotal = runCommand("grep MemTotal /proc/meminfo| awk '{print $2}'")
    MemTotal_Num = map(float, MemTotal)[0]
    # 可用內(nèi)存
    MemFree = runCommand("grep MemFree /proc/meminfo| awk '{print $2}'")
    MemFree_Num = map(float, MemFree)[0]
    # 比例
    Proportion = '{:.4%}'.format(MemFree_Num / MemTotal_Num)
    res = {
        '總內(nèi)存(GB)': '{:.5}'.format(float(MemTotal_Num / 1024 / 1024)),
        '可用內(nèi)存(GB)': '{:.5}'.format(float(MemFree_Num / 1024 / 1024)),
        '已用比例(%)': Proportion
    }
    return res


def getMemStatusSimple():
    MemTotal = runCommand("free -h")
    res = {
        '內(nèi)存總覽': MemTotal
    }
    return res


def getDiskStatus():
    """
    磁盤檢查
    """
    # 生成臨時(shí)數(shù)據(jù)記錄文件
    # 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():
    """
    網(wǎng)絡(luò)檢查
    """
    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 語(yǔ)句有問(wèn)題會(huì)報(bào)錯(cuò),sed的錯(cuò)誤,需要檢查下執(zhí)行情況
    # 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 防火墻命令報(bào)錯(cuò) sh: not found 特殊處理
    for info in firewall:
        if "not found" in info:
            firewall = runCommand("ufw status")
    res = {
        '防火墻狀態(tài)': firewall
    }
    return res


def sshStatus():
    """
    ssh 檢查
    """
    sshActive = runCommand("systemctl is-active sshd.service")
    sshNetstat = runCommand("sudo netstat -atlunp | grep sshd")
    res = {
        'ssh開啟狀態(tài)': sshActive,
        'ssh運(yùn)行情況': sshNetstat
    }
    return res


def ntpStatus():
    """
    ntp 檢查
    """
    ntpActive = runCommand("systemctl is-active ntpd")
    res = {
        'ntp運(yùn)行情況': 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):
    """
    創(chuàng)建report的txt文件,并寫入數(shù)據(jù)
    """
    report_dir = os.getcwd() + os.sep + "report" + os.sep
    # 判斷當(dāng)前路徑是否存在,沒(méi)有則創(chuàng)建new文件夾
    if not os.path.exists(report_dir):
        os.makedirs(report_dir)
    # 在當(dāng)前py文件所在路徑下的new文件中創(chuàng)建txt
    report_file = report_dir + name + '.txt'
    # 打開文件,open()函數(shù)用于打開一個(gè)文件,創(chuàng)建一個(gè)file對(duì)象,相關(guān)的方法才可以調(diào)用它進(jìn)行讀寫。
    file = open(report_file, 'w')
    # 寫入內(nèi)容信息
    file.write(text)
    file.close()
    print('report_file create success', report_file)


def printSinfcloud():
    print("+------------------------------------------------+")
    print("|       歡迎使用SinfCloud自動(dòng)巡檢工具            |")
    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))

到此這篇關(guān)于Python實(shí)現(xiàn)Linux服務(wù)器自動(dòng)巡檢腳本的文章就介紹到這了,更多相關(guān)Python Linux自動(dòng)巡檢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python輸出決策樹圖形的例子

    python輸出決策樹圖形的例子

    今天小編就為大家分享一篇python輸出決策樹圖形的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-08-08
  • python openvc 裁剪、剪切圖片 提取圖片的行和列

    python openvc 裁剪、剪切圖片 提取圖片的行和列

    這篇文章主要介紹了python openvc 裁剪、剪切圖片 提取圖片的行和列,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-09-09
  • python實(shí)現(xiàn)多進(jìn)程按序號(hào)批量修改文件名的方法示例

    python實(shí)現(xiàn)多進(jìn)程按序號(hào)批量修改文件名的方法示例

    這篇文章主要介紹了python實(shí)現(xiàn)多進(jìn)程按序號(hào)批量修改文件名的方法,涉及Python多進(jìn)程與文件相關(guān)操作技巧,需要的朋友可以參考下
    2019-12-12
  • Python強(qiáng)化練習(xí)之PyTorch opp算法實(shí)現(xiàn)月球登陸器

    Python強(qiáng)化練習(xí)之PyTorch opp算法實(shí)現(xiàn)月球登陸器

    在面向?qū)ο蟪霈F(xiàn)之前,我們采用的開發(fā)方法都是面向過(guò)程的編程(OPP)。面向過(guò)程的編程中最常用的一個(gè)分析方法是“功能分解”。我們會(huì)把用戶需求先分解成模塊,然后把模塊分解成大的功能,再把大的功能分解成小的功能,整個(gè)需求就是按照這樣的方式,最終分解成一個(gè)一個(gè)的函數(shù)
    2021-10-10
  • Win10+GPU版Pytorch1.1安裝的安裝步驟

    Win10+GPU版Pytorch1.1安裝的安裝步驟

    這篇文章主要介紹了Win10+GPU版Pytorch1.1安裝的安裝步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • 構(gòu)建Python包的五個(gè)簡(jiǎn)單準(zhǔn)則簡(jiǎn)介

    構(gòu)建Python包的五個(gè)簡(jiǎn)單準(zhǔn)則簡(jiǎn)介

    這篇文章主要介紹了構(gòu)建Python包的五個(gè)簡(jiǎn)單準(zhǔn)則簡(jiǎn)介,在Github開源合作日趨主流的今天,健壯的Python包的構(gòu)建成為開發(fā)者必須要考慮到的問(wèn)題,本文提出了五項(xiàng)建議,需要的朋友可以參考下
    2015-06-06
  • python退出命令是什么?詳解python退出方法

    python退出命令是什么?詳解python退出方法

    在本篇內(nèi)容中我們給學(xué)習(xí)python編程的朋友們整理了關(guān)于python退出的命令和方法,需要的學(xué)習(xí)下。
    2018-12-12
  • Python光學(xué)仿真學(xué)習(xí)Gauss高斯光束在空間中的分布

    Python光學(xué)仿真學(xué)習(xí)Gauss高斯光束在空間中的分布

    這篇文章主要介紹了Python光學(xué)仿真學(xué)習(xí)中Gauss高斯光束在空間中的分布理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2021-10-10
  • Python學(xué)習(xí)筆記之變量、自定義函數(shù)用法示例

    Python學(xué)習(xí)筆記之變量、自定義函數(shù)用法示例

    這篇文章主要介紹了Python學(xué)習(xí)筆記之變量、自定義函數(shù)用法,結(jié)合實(shí)例形式分析了Python變量、自定義函數(shù)的概念、功能、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2019-05-05
  • Python中的google authenticator認(rèn)證過(guò)程

    Python中的google authenticator認(rèn)證過(guò)程

    文章介紹了使用Python 3.7生成Google Authenticator所需密鑰的步驟,包括使用pyotp模塊生成密鑰、生成二維碼圖片以及通過(guò)客戶端掃描二維碼進(jìn)行二次認(rèn)證的實(shí)現(xiàn)原理
    2024-11-11

最新評(píng)論