Python采集主机信息

# -*- coding: utf-8 -*-
import subprocess
import socket
import re
import json
from datetime import datetime, timedelta

def get_hostname():
    return socket.gethostname()

def get_machine_type():
    try:
        output = subprocess.check_output("dmesg | grep -i virtual", shell=True)
        if 'virtual' in output.lower():
            return "virtual_machine"
    except subprocess.CalledProcessError:
        return "physical_machine"

def get_os_version():
    try:
        with open("/etc/os-release") as f:
            for line in f:
                if line.startswith("PRETTY_NAME"):
                    return line.split('=')[1].strip().replace('"', '')
    except IOError:
        return "Unknown"

def get_system_uptime():
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        uptime_date = datetime.now() - timedelta(seconds=uptime_seconds)
        return uptime_date.strftime('%Y-%m-%d')

def get_private_ips():
    try:
        # 使用 'ip addr' 命令获取所有网络接口的详细信息
        output = subprocess.check_output("ip addr", shell=True)
    except subprocess.CalledProcessError as e:
        print("Failed to execute command: {}".format(e))
        return []

    # 解析 'ip addr' 命令的输出来找到 IPv4 地址
    ip_list = []
    for line in output.splitlines():
        # 搜索包含 'inet' 但不是 'inet6' 的行
        if 'inet ' in line and not 'inet6' in line:
            # 使用正则表达式提取 IP 地址
            match = re.search(r'inet (\d+\.\d+\.\d+\.\d+)/', line)
            if match:
                ip_list.append(match.group(1))

    return ip_list




def get_public_ip():
    try:
        return subprocess.check_output('curl http://ipecho.net/plain -s', shell=True).strip()
    except subprocess.CalledProcessError:
        return "Unavailable"

def get_cpu_info():
    output = subprocess.check_output('cat /proc/cpuinfo', shell=True)
    cores = len(re.findall(r'^processor', output, re.MULTILINE))
    model = re.search(r'^model name\s+: (.+)$', output, re.MULTILINE).group(1)
    return cores, model

def get_memory():
    with open('/proc/meminfo') as f:
        meminfo = f.read()
    mem_total = [int(s.split()[1]) for s in meminfo.split('\n') if 'MemTotal:' in s][0]
    return '{} MB'.format(mem_total // 1024)

def get_disks():
    disks = []
    output = subprocess.check_output('lsblk -nb -o NAME,SIZE,TYPE', shell=True)
    for line in output.strip().split('\n'):
        name, size, type = line.split()
        if type == 'disk':
            disks.append({'device': '/dev/' + name, 'size': '{} GB'.format(int(size) // 10**9)})
    return disks

if __name__ == "__main__":
    system_info = {
        'hostname': get_hostname(),
        'machine_type': get_machine_type(),
        'os_version': get_os_version(),
        'system_uptime': get_system_uptime(),
        'private_ips': get_private_ips(),
        'public_ip': get_public_ip(),
        'cpu_cores': get_cpu_info()[0],
        'cpu_model': get_cpu_info()[1],
        'memory': get_memory(),
        'disks': get_disks()
    }
    print(json.dumps(system_info, indent=4))

执行结果

[root@iZ0jlebny5dv69fhu19311Z ~]# python2 host1.py 
{
    "public_ip": "8.130.**", 
    "os_version": "CentOS Linux 7 (Core)", 
    "disks": [
        {
            "device": "/dev/vda", 
            "size": "42 GB"
        }
    ], 
    "private_ips": [
        "127.0.0.1", 
        "172.27.38.109"
    ], 
    "machine_type": "virtual_machine", 
    "memory": "1756 MB", 
    "hostname": "iZ0jlebny5dv69fhu19311Z", 
    "cpu_model": "Intel(R) Xeon(R) Platinum", 
    "cpu_cores": 2, 
    "system_uptime": "2023-11-20"
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值