前段时间写了一篇博文名为《利用Python脚本获取Windows和Linux的系统版本信息》,本篇博文利用这篇文章中的知识提供一个增强版本的获取信息的Python脚本。执行后,看起来就像登录Ubuntu Linux系统时提示的motd信息一样,可以看到:

  1. 系统的类型、发行版本(具体信息)、内核版本等

  2. 当前系统的时间、时区

  3. 系统每一个CPU核心的负载和CPU整体负载

  4. 进程数量

  5. 根分区的磁盘空间,Windows下默认C盘

  6. 登录的用户总数和每一个登录到系统的用户的信息

  7. 内存和交换分区的利用率

  8. 默认网卡的IP地址

  9. 系统启动时间和已运行时间

运行截图如下:

(1)Linux下截图:

(2)Windows下截图:

Python代码如下:

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:               LinuxBashShellScriptForOps:getSystemStatus.py
User:               Guodong
Create Date:        2016/8/18
Create Time:        15:32"""
import platform
import psutil
import subprocess
import os
import sys
import time
import re
import prettytablemswindows = (sys.platform == "win32")  # learning from 'subprocess' module
linux = (sys.platform == "linux2")def getLocalIP():import netifacesroutingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]for interface in netifaces.interfaces():if interface == routingNicName:try:routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']return interface, routingIPAddrexcept KeyError:passdef getUser():if linux:proc_obj = subprocess.Popen(r'tty', shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)tty = proc_obj.communicate()[0]else:tty = []user_object = psutil.users()for login in user_object:username, login_tty, login_host, login_time = [suser for suser in login]print username, login_tty, login_host, time.strftime('%b %d %H:%M:%S', time.localtime(login_time)),if login_tty in tty:print '**current user**'else:printdef getTimeZone():return time.strftime("%Z", time.gmtime())def getTimeNow():now = time.strftime('%a %b %d %H:%M:%S %Y %Z', time.localtime(time.time()))return nowdef printHeader():if linux:try:with open('/etc/issue') as f:content = f.read().strip()output_list = re.split(r' \\', content)linux_type = list(output_list)[0]except IOError:passelse:if linux_type is not None:return "Welcome to %s (%s %s %s)\n  System information as of %s" % (linux_type, platform.system(), platform.release(), platform.machine(), getTimeNow())else:returnif mswindows:def get_system_encoding():import codecsimport locale"""The encoding of the default system locale but falls back to the givenfallback encoding if the encoding is unsupported by python or couldnot be determined.  See tickets #10335 and #5846"""try:encoding = locale.getdefaultlocale()[1] or 'ascii'codecs.lookup(encoding)except Exception:encoding = 'ascii'return encodingDEFAULT_LOCALE_ENCODING = get_system_encoding()import _winregtry:reg_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")if reg_key:ProductName = _winreg.QueryValueEx(reg_key, "ProductName")[0] or NoneEditionId = _winreg.QueryValueEx(reg_key, "EditionId")[0] or NoneReleaseId = _winreg.QueryValueEx(reg_key, "ReleaseId")[0] or NoneBuildLabEx = _winreg.QueryValueEx(reg_key, "BuildLabEx")[0][:9] or Nonereturn "%s, %s [%s]\r\nVersion %s (OS Internal Version %s)" % (ProductName, EditionId, platform.version(), ReleaseId, BuildLabEx)except Exception as e:print e.message.decode(DEFAULT_LOCALE_ENCODING)def getHostname():return platform.node()def getCPU():return [x / 100.0 for x in psutil.cpu_percent(interval=0, percpu=True)]def getLoadAverage():if linux:import multiprocessingk = 1.0k /= multiprocessing.cpu_count()if os.path.exists('/proc/loadavg'):return [float(open('/proc/loadavg').read().split()[x]) * k for x in range(3)]else:tokens = subprocess.check_output(['uptime']).split()return [float(x.strip(',')) * k for x in tokens[-3:]]if mswindows:# print psutil.cpu_percent()# print psutil.cpu_times_percent()# print psutil.cpu_times()# print psutil.cpu_stats()return "%.2f%%" % psutil.cpu_percent()def getMemory():v = psutil.virtual_memory()return {'used': v.total - v.available,'free': v.available,'total': v.total,'percent': v.percent,}def getVirtualMemory():v = psutil.swap_memory()return {'used': v.used,'free': v.free,'total': v.total,'percent': v.percent}def getUptime():uptime_file = "/proc/uptime"if os.path.exists(uptime_file):with open(uptime_file, 'r') as f:return f.read().split(' ')[0].strip("\n")else:return time.time() - psutil.boot_time()def getUptime2():boot_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time()))print "system start at: %s" % boot_time,uptime_total_seconds = time.time() - psutil.boot_time()uptime_days = int(uptime_total_seconds / 24 / 60 / 60)uptime_hours = int(uptime_total_seconds / 60 / 60 % 24)uptime_minutes = int(uptime_total_seconds / 60 % 60)uptime_seconds = int(uptime_total_seconds % 60)print "uptime: %d days %d hours %d minutes %d seconds" % (uptime_days, uptime_hours, uptime_minutes, uptime_seconds)user_number = len(psutil.users())print "%d user:" % user_numberprint "  \\"for user_tuple in psutil.users():user_name = user_tuple[0]user_terminal = user_tuple[1]user_host = user_tuple[2]user_login_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user_tuple[3]))print "  |- user online: %s, login from %s with terminal %s at %s" % (user_name, user_host, user_terminal, user_login_time)cpu_count = psutil.cpu_count()try:with open('/proc/loadavg', 'r') as f:loadavg_c = f.read().split(' ')loadavg = dict()if loadavg_c is not None:loadavg['lavg_1'] = loadavg_c[0]loadavg['lavg_5'] = loadavg_c[1]loadavg['lavg_15'] = loadavg_c[2]loadavg['nr'] = loadavg_c[3]loadavg['last_pid'] = loadavg_c[4]print "load average: %s, %s, %s" % (loadavg['lavg_1'], loadavg['lavg_5'], loadavg['lavg_15'])if float(loadavg['lavg_15']) > cpu_count:print "Note: cpu 15 min load is high!"if float(loadavg['lavg_5']) > cpu_count:print "Note: cpu 5 min load is high!"if float(loadavg['lavg_1']) > cpu_count:print "Note: cpu 1 min load is high!"except IOError:passif __name__ == '__main__':header = printHeader()print headerprintsystem_load = str(getLoadAverage()).strip("[]")user_logged_in = len(psutil.users())info_of_root_partition = psutil.disk_usage("/")percent_of_root_partition_usage = "%.2f%%" % (float(info_of_root_partition.used) * 100 / float(info_of_root_partition.total))total_size_of_root_partition = "%.2f" % (float(psutil.disk_usage("/").total / 1024) / 1024 / 1024)memory_info = getMemory()memory_usage = "%.2f%%" % (float(memory_info['used']) * 100 / float(memory_info['total']))swap_info = getVirtualMemory()swap_usage = "%.2f%%" % (float(swap_info['used']) * 100 / float(swap_info['total']))local_ip_address = getLocalIP()table = prettytable.PrettyTable(border=False, header=False, left_padding_width=2)table.field_names = ["key1", "value1", "key2", "value2"]table.add_row(["System load:", system_load, "Processes:", len(list(psutil.process_iter()))])table.add_row(["Usage of /:", "%s of %sGB" % (percent_of_root_partition_usage, total_size_of_root_partition),"Users logged in:", user_logged_in])table.add_row(["Memory usage:", memory_usage, "IP address for %s:" % local_ip_address[0], local_ip_address[1]])table.add_row(["Swap usage:", swap_usage, "", ""])for field in table.field_names:table.align[field] = "l"print table.get_string()printgetUser()printgetUptime2()

注:脚本内容可以通过GitHub获取,https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/system/getSystemStatus.py,欢迎star、fork。

已知存在问题:

  1. 暂时未实现获取Windows下网卡的中文可视名称

  2. Windows下的tty名称默认为None,暂时没有设置对用户友好的显示

  3. Ubuntu Linux上motd信息的用户登录数量显示为同一用户同一个IP的多个用户视为同一用户,脚本中视为不同用户

  4. 首次运行可能需要安装依赖的地方库,如psutil、platform、prettytable、netifaces等,请使用easy_install、pip、conda等安装。

  5. 其他的因为时间原因未指出和未实现的问题,欢迎在文章下面评论留言和在GitHub上提issue

tag:Python、Linux系统信息、Windows系统信息

--end--

Python获取Linux或Windows系统的基本信息相关推荐

  1. 使用Python获取Linux系统的各种信息

    From: http://www.jb51.net/article/52058.htm 这篇文章主要介绍了使用Python获取Linux系统的各种信息,例如系统类型.CPU信息.内存信息.块设备等,需 ...

  2. DAY28:Linux、Windows 系统提权

    DAY28:Linux.Windows 系统提权 1.Linux 系统提权 1.1.Linux 系统版本 linux发行版本: • centos • redhat • ubuntu • kali 1. ...

  3. 使用 Python 获取 Linux 系统信息的代码

    From: http://www.jb51.net/article/52107.htm 在本文中,我们将会探索使用Python编程语言工具来检索Linux系统各种信息,需要的朋友可以参考下 哪个Pyt ...

  4. Python获取Win7,Win10系统缩放大小

    Python获取Win7,Win10系统缩放大小 使用pywin32调用windows系统接口. 利用GetDeviceCaps获取指定设备的设备信息. 具体参考[https://docs.micro ...

  5. python动态捕捉屏幕_如何使用Python实现自动化截取Windows系统屏幕

    今天小编要跟大家分享的文章是关于如何使用Python实现自动化截取windows系统屏幕.估计很多人都想问:自动化截屏有什么用?为什么要实现自动化截屏呢? 那么Python入门新手的小伙伴就快来看一看 ...

  6. linux下备份windows系统版本,使用BackupPC备份Linux和Windows系统

    使用BackupPC备份Linux和Windows系统 版本1.0 作者:Falko Timme 本教程将介绍如何使用BackupPC备份Linux和Windows系统. BackupPC充当服务器, ...

  7. Linux和Windows系统下:安装Anaconda、Paddle、tensorflow、pytorch,GPU[cuda、cudnn]、CPU安装教学,以及查看CPU、GPU内存使用情况

    Linux和Windows系统下安装深度学习框架所需支持:Anaconda.Paddlepaddle.Paddlenlp.pytorch,含GPU.CPU版本详细安装过程 1.下载 Anaconda ...

  8. spring mvc学习(48):java判断系统是linux还是windows系统

    java判断系统是linux还是windows系统 判断一个系统是windows还是linux? import org.junit.jupiter.api.Test;/*** @program: ut ...

  9. linux远程打开windows程序,为新手讲解Linux和Windows系统的远程桌面访问知识

    很多新手都是使用Linux和Windows双系统的,它们之间的远程桌面访问是如何连接的,我们就为新手讲解Linux和Windows系统的远程桌面访问知识,包括所使用的软件及方法.本文所使用的Linux ...

最新文章

  1. python36安装numpy_安装numpy
  2. Java代理模式——静态代理动态代理
  3. 树状数组维护区间和的模型及其拓广的简单总结
  4. ppt计算机控制系统实例,第部分计算机控制系统的应用实例.ppt
  5. java steam 去重_Java中对List去重 Stream去重的解决方法
  6. 深入理解Plasma(一)Plasma 框架
  7. 机器学习编程接口(api)设计(oop 设计)
  8. 如何使用 Font Book 在 Mac 上添加或删除字体?
  9. 给你的站点添加 DNS CAA 保护
  10. 电脑更新重启后黑屏_电脑黑屏重启还是黑屏的解决方法教程
  11. 什么是云?云里雾里——最流行的云时代
  12. 在登录页面中输入正确的信息还是显示用户名或密码错误
  13. oracle现金流量表逻辑,现金流量表之附表逻辑分析
  14. 2020仙气十足的女生个性网名
  15. Java+控制台 商城销售系统
  16. 小白学NLP学习笔记-入门
  17. 几个强大到没朋友的资源网站 个个都是精品
  18. unity中RectTransform的各个值得获取
  19. ie9 不执行js,打开控制台就好了
  20. CSDN的博客怎么了?

热门文章

  1. pcl 使用gpu计算法向量_异构计算系列文章(一):定义、场景及局限性
  2. PHP百度收录量查询接口源码,百度收录量API查询PHP源码
  3. parted如何将磁盘所有空间格式化_linux文件系统及磁盘格式化
  4. 如何使用Intellij IDEA工具导入SVN项目
  5. flink读取不到文件_flink批处理从0到1
  6. 大数据与商业地理分析
  7. 用matlab画声偶级辐射,matlab结题报告(电偶极子的辐射场)
  8. 系统学习深度学习(三十)--Deep Q-Learning
  9. bootstrap拖动div_BootStrap modal实现拖拽功能
  10. 计算机逻辑运算进位,二进位数进行逻辑运算1010AND1001的运算结果