Python运维——系统模块

本文介绍了psutil模块,这是一个跨平台的库,用于获取系统各项参数。文章详细展示了如何使用该库来获取CPU逻辑个数、CPU使用率、内存信息、磁盘分区信息以及用户登录信息等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

psutil模块

psutil 是一个跨平台的库,提供了查看系统各项参数的接口。
常用方法:

方法解释
cpu-count()cpu逻辑个数
cpu_count(logical=False)
cpu_percent()CPU的使用率
virtual_memory()内存完整信息
disk_partitions()磁盘完整信息
user()用户登录信息

Windows环境下

In [1]: import psutil

In [2]: psutil.cpu_count()
Out[2]: 4

In [3]: psutil.cpu_count(logical=False)
Out[3]: 2

In [4]: psutil.cpu_percent()
Out[4]: 5.7

In [5]: psutil.virtual_memory()
Out[5]: svmem(total=4205264896, available=1154924544, percent=72.5, used=3050340352, free=1154924544)

In [6]: psutil.disk_partitions()
Out[6]:
[sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'),
 sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed'),
 sdiskpart(device='E:\\', mountpoint='E:\\', fstype='NTFS', opts='rw,fixed'),
 sdiskpart(device='F:\\', mountpoint='F:\\', fstype='NTFS', opts='rw,fixed'),
 sdiskpart(device='G:\\', mountpoint='G:\\', fstype='NTFS', opts='rw,fixed')]

In [7]: psutil.users()
Out[7]: [suser(name='Administrator', terminal=None, host='0.4.0.0', started=2471218119.0, pid=None)]

Linux环境下

In [1]: import psutil

In [2]: psutil.cpu_count()
Out[2]: 1

In [3]: psutil.cpu_count(logical=False)
Out[3]: 1

In [4]: psutil.cpu_percent()
Out[4]: 1.2

In [5]: psutil.virtual_memory()
Out[5]: svmem(total=1966563328, available=1713328128, percent=12.9, used=120455168, free=1523695616, active=164339712, inactive=198082560, buffers=45314048, cached=277098496, shared=167936, slab=54685696)

In [6]: psutil.disk_partitions()
Out[6]: [sdiskpart(device='/dev/xvda1', mountpoint='/', fstype='ext4', opts='rw')]

In [7]: psutil.users()
Out[7]: [suser(name='root', terminal='pts/0', host='218.26.55.15', started=1524530688.0, pid=9479)]
### Python 运维工具和实践 #### 使用Python进行网络设备管理 为了简化日常的运维工作,《Python自动化运维实战》一书提供了详细的指导,说明了怎样利用Python来进行服务器配置与管理的任务自动化[^1]。书中不仅涵盖了基础的操作系统层面的工作,比如用户管理、数据管理和进程控制;也深入探讨了更复杂的场景下如何借助特定模块和工具实现高效运作。 #### 自动化测试执行 除了常规的维护活动外,在开发环境中自动运行单元测试也是提高效率的重要手段之一。通过编写简单的Python脚本来触发持续集成管道中的构建过程并收集反馈信息,可以显著减少人为错误的发生几率,并加快迭代速度[^3]。 #### 日志记录的重要性 当涉及到实际生产环境时,良好的日志机制对于排查问题至关重要。下面是一个示例函数`execute_command()`,它展示了如何在每次调用期间向指定位置写入操作详情: ```python def execute_command(server, command): log(f"在 {server['name']} 执行命令: {command}") conn = Connection( host=server['host'], user=server['user'], connect_kwargs={"key_filename": server['key_path']} ) try: result = conn.run(command, hide=True) log(result.stdout.strip()) except Exception as e: log(f"命令执行失败: {e}", level="error") raise ``` 这段代码片段强调了即使是最基本的功能也应该考虑异常处理逻辑以及适当的信息输出方式。 #### 文件批量处理能力 针对大量文件或者目录结构下的资源清理需求,《python运维脚本实践》给出了一个多线程解决方案用于加速这一流程。这里有一个名为`delete_files()`的方法实现了并发删除多个目标对象而不影响主线程继续其他作业的能力: ```python import os from concurrent.futures import ThreadPoolExecutor def delete_file(file_path): try: os.remove(file_path) print(f"Deleted file: {file_path}") except OSError as e: print(f"Error deleting file: {file_path} - {e}") def delete_files(file_list): with ThreadPoolExecutor(max_workers=5) as executor: list(executor.map(delete_file, file_list)) ``` 此版本改进了原始单线程模式,提高了性能表现的同时保持了清晰易懂的设计思路[^4]。 #### 配置文件编辑技巧 最后值得一提的是关于文本替换方面的应用案例——修改Nginx配置参数。给定源路径后,可以通过正则表达式匹配旧值替换成新定义的内容,从而达到更新设置的目的而无需手动逐行查找更改[^5]: ```python import os import re def alter_nginx_conf(filePath, old_str, new_str): print('开始修改文件 {}'.format(filePath)) with open(filePath, 'r', encoding='utf-8') as f1, \ open("%s.bak" % filePath, 'w', encoding='utf-8') as f2: for line in f1: f2.write(re.sub(old_str, new_str, line)) os.remove(filePath) os.rename("%s.bak" % filePath, filePath) ``` 上述例子充分体现了Python作为一种强大灵活的语言特性及其广泛应用于各种规模企业级项目当中所带来的便利之处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值