题目需求:
1.获取当前主机信息(操作系统名、主机名、内核版本、硬件架构)
2.获取开机时间和开机时长
3.获取当前登录用户
代码如下:
#! /usr/bin/python3
import time
import os
import psutil
from datetime import datetime
print("主机信息".center(50,'*'))
info = os.uname()
# print(info)
print(
"""
操作系统名: %s
主机名: %s
内核版本: %s
硬件架构: %s
""" %(info.sysname, info.nodename, info.release, info.machine))
print("开机信息".center(50,'*'))
# 开机时间,返回时间戳
boot_time = psutil.boot_time()
# 将时间戳转换为字符串
boot_time_obj = datetime.fromtimestamp(boot_time)
# print(boot_time_obj)
# 当前时间
now_time = datetime.now()
delta_time = datetime.now()
# 开机时长
delta_time1 = now_time - boot_time_obj
print("开机时间: ", str(boot_time_obj).split('.')[0])
print("当前时间: ", str(now_time).split('.')[0])
print("开机时长: ", str(delta_time1).split('.')[0])
print("当前登录用户".center(50,'*'))
login_user = psutil.users()[0]
print("当前登录用户: ", login_user)
linux中的运行结果:
***********************主机信息***********************
操作系统名: Linux
主机名: devops03
内核版本: 3.10.0-957.1.3.el7.x86_64
硬件架构: x86_64
***********************开机信息***********************
开机时间: 2019-12-03 11:01:38
当前时间: 2022-06-27 15:18:24
开机时长: 937 days, 4:16:46
**********************当前登录用户**********************
当前登录用户: suser(name='root', terminal='pts/1', host='172.16.31.18', started=1656298240.0, pid=5153)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析