python3获取服务器运行状态及进程详细信息

有了这些信息我们就可以对linux服务器做监控了,也可以对所有的项目进行状态监控了
linux 服务器状态

import psutil  # 进程运行情况
import platform  # 包含系统信息查询函数
import os
import logging
#
# # 硬件信息
svmem = psutil.virtual_memory()
mem_total = svmem.total  # 系统内存总数
mem_used = svmem.used  # 内存已使用
mem_free = svmem.free  # 内存空闲大小
mem_per = svmem.percent  # 内存使用率
system_version = platform.linux_distribution()  # 获取linux发行版本详细信息
system_machine = platform.machine()  # 获取操作系统架构
with open('/proc/cpuinfo') as f:  # 获取cpu型号
    for line in f:
        if line.strip():
            if line.rstrip('\n').startswith('model name'):
                cpu_name = line.rstrip('\n').split(':')[1]
                break
cpu_type = cpu_name.split()[0]
cpu_count = psutil.cpu_count()  # cpu核数
host_name = platform.node()  # 电脑名称
stinfo = os.statvfs('/home')
print('CPU使用率', psutil.cpu_percent(1))
print('每个核的cpu使用率', psutil.cpu_percent(percpu=True))
print('硬盘使用', psutil.disk_usage("/home").percent)
# stinfo = os.statvfs('/')
st_info = stinfo.f_bsize * stinfo.f_blocks / 1024 / 1024 / 1024  # 获取磁盘大小
st_free_info = stinfo.f_bavail * stinfo.f_frsize / 1024 / 1024 / 1024  # 磁盘剩余大小
print('系统内存总数', mem_total)
print('内存已使用', mem_used)
print('内存空闲大小', mem_free)
print('内存使用率', mem_per)
print('cpu核数', cpu_count)
print('电脑名称', host_name)
print('获取磁盘大小', st_info)
print('磁盘剩余大小', st_free_info)
# os.system('python3 /home/KL/DigapisKl/mastercontrol/es_search.py')
if mem_per >= 90:
    print(1)
a = '%.2f' % (st_free_info / st_info)
print(a)

当前运行进程数量

from __future__ import print_function
import os


def process_list():
    pids = []
    for subdir in os.listdir('/proc'):
        if subdir.isdigit():
            pids.append(subdir)
    return pids


if __name__ == '__main__':
    pids = process_list()
    print('Total number of running processes:: {0}'.format(len(pids)))

当前运行进程详细信息

import psutil
import csv
def processInfo():
    """
    获取全部进程信息
    :return: list
    """
    filename = open('./进程信息' + '.csv', 'a', newline='', encoding='utf-8')
    csv_write = csv.writer(filename, dialect='excel')
    heard = ['进程编号','进程名称','执行路径','当前路径','启动命令','父进程ID','父进程','状态','进程用户名','进程创建时间','终端','执行时间','内存信息','打开的文件','相关网络连接','线程数','线程','环境变量',]
    csv_write.writerow(heard)
    # 定义一个获取进程属性的方法
    def getProperty(process, pro: str):
        try:
            ret = eval('process.' + pro)()
        except Exception as e:
            return ''
        return ret

    pids = psutil.pids()

    output = {}
    for pid in pids:
        print(pid)
        usar = []
        try:
            process = psutil.Process(pid)
            parent = getProperty(process, 'parent')
            if parent is str or parent is None:
                parentName = ''
            else:
                parentName = parent.name()
            output[pid] = {
                '进程编号': pid,
                '进程名称': process.name(),
                '执行路径': getProperty(process, 'exe'),
                '当前路径': getProperty(process, 'cwd'),
                '启动命令': getProperty(process, 'cmdline'),
                '父进程ID': process.ppid(),
                '父进程': parentName,
                '状态': process.status(),
                '进程用户名': getProperty(process, 'username'),
                '进程创建时间': process.create_time(),
                '终端': getProperty(process, 'terminal'),
                '执行时间': process.cpu_times(),
                '内存信息': process.memory_info(),
                '打开的文件': getProperty(process, 'open_files'),
                '相关网络连接': process.connections(),
                '线程数': process.num_threads(),
                '线程': getProperty(process, 'threads'),
                '环境变量': getProperty(process, 'environ'),
            }
            usar.append(output[pid]['进程编号'])
            usar.append(output[pid]['进程名称'])
            usar.append(output[pid]['执行路径'])
            usar.append(output[pid]['当前路径'])
            usar.append(output[pid]['启动命令'])
            usar.append(output[pid]['父进程ID'])
            usar.append(output[pid]['父进程'])
            usar.append(output[pid]['状态'])
            usar.append(output[pid]['进程用户名'])
            usar.append(output[pid]['进程创建时间'])
            usar.append(output[pid]['终端'])
            usar.append(output[pid]['执行时间'])
            usar.append(output[pid]['内存信息'])
            usar.append(output[pid]['打开的文件'])
            usar.append(output[pid]['相关网络连接'])
            usar.append(output[pid]['线程数'])
            usar.append(output[pid]['线程'])
            usar.append(output[pid]['环境变量'])


            print(output[pid]['进程编号'])
            csv_write.writerow(usar)

        except Exception as result:
            print(result)

    return output
a = processInfo()
print(len(a))
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要让 Python 代码在服务器上永久运行,可以使用一些方法来实现守护进程或后台运行。下面是几种常见的方法: 1. 使用 nohup 命令:可以使用 `nohup` 命令来运行 Python 脚本,并将输出重定向到一个日志文件,这样即使关闭终端或断开 SSH 连接,脚本仍然会继续在后台运行。 ```bash nohup python your_script.py > output.log & ``` 其中,`your_script.py` 是你的 Python 脚本,`output.log` 是输出日志的文件名。 2. 使用 systemd 或 init.d:对于 Linux 系统,你可以将 Python 脚本配置为一个系统服务,使用 systemd(在较新的发行版上)或 init.d(在旧的发行版上)来管理和启动脚本。这样脚本会在系统启动时自动运行,并能够随时监控和管理。 配置 systemd 服务示例: - 创建一个名为 `your_script.service` 的服务文件,内容如下: ``` [Unit] Description=Your Python Script After=network.target [Service] ExecStart=/usr/bin/python /path/to/your_script.py WorkingDirectory=/path/to/script_directory [Install] WantedBy=multi-user.target ``` - 将服务文件复制到 `/etc/systemd/system/` 目录下,并执行以下命令启动服务: ```bash sudo systemctl start your_script ``` 你还可以使用 `systemctl` 命令来停止、重启和查看服务状态。 3. 使用守护进程管理工具:还可以使用一些专门的守护进程管理工具,如 Supervisor 或 PM2。这些工具可以帮助你管理和监控 Python 脚本的运行,并提供了更多的配置选项和功能。 - 使用 Supervisor:安装 Supervisor,并创建一个配置文件,指定要运行Python 脚本和日志文件路径。然后启动 Supervisor,它将会监控并管理脚本的运行。 - 使用 PM2:安装 PM2,并使用 `pm2 start` 命令来启动 Python 脚本。PM2 提供了许多额外的功能,如日志管理、自动重启等。 以上方法中的每一种都有其适用的场景和配置选项。你可以根据自己的需求选择合适的方法来让 Python 代码在服务器上永久运行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值