Python获取Linux或Windows系统的基本信息

简介:

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

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

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

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

  4. 进程数量

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

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

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

  8. 默认网卡的IP地址

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

运行截图如下:

(1)Linux下截图:

wKiom1h3O5PC0kNHAAST-VfrqOQ700.jpg-wh_50

(2)Windows下截图:

wKiom1h3O5TTnWReAAFqVnYsZjA784.jpg-wh_50

Python代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/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  prettytable
 
mswindows  =  (sys.platform  = =  "win32" )   # learning from 'subprocess' module
linux  =  (sys.platform  = =  "linux2" )
 
 
def  getLocalIP():
     import  netifaces
     routingNicName  =  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, routingIPAddr
             except  KeyError:
                 pass
 
 
def  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 :
             print
 
 
def  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  now
 
 
def  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:
             pass
         else :
             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 :
                 return
     if  mswindows:
         def  get_system_encoding():
             import  codecs
             import  locale
             """
             The encoding of the default system locale but falls back to the given
             fallback encoding if the encoding is unsupported by python or could
             not be determined.  See tickets #10335 and #5846
             """
             try :
                 encoding  =  locale.getdefaultlocale()[ 1 or  'ascii'
                 codecs.lookup(encoding)
             except  Exception:
                 encoding  =  'ascii'
             return  encoding
 
         DEFAULT_LOCALE_ENCODING  =  get_system_encoding()
 
         import  _winreg
         try :
             reg_key  =  _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,  "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" )
             if  reg_key:
                 ProductName  =  _winreg.QueryValueEx(reg_key,  "ProductName" )[ 0 or  None
                 EditionId  =  _winreg.QueryValueEx(reg_key,  "EditionId" )[ 0 or  None
                 ReleaseId  =  _winreg.QueryValueEx(reg_key,  "ReleaseId" )[ 0 or  None
                 BuildLabEx  =  _winreg.QueryValueEx(reg_key,  "BuildLabEx" )[ 0 ][: 9 or  None
                 return  "%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  in  psutil.cpu_percent(interval = 0 , percpu = True )]
 
 
def  getLoadAverage():
     if  linux:
         import  multiprocessing
         =  1.0
         / =  multiprocessing.cpu_count()
         if  os.path.exists( '/proc/loadavg' ):
             return  [ float ( open ( '/proc/loadavg' ).read().split()[x])  *  for  in  range ( 3 )]
         else :
             tokens  =  subprocess.check_output([ 'uptime' ]).split()
             return  [ float (x.strip( ',' ))  *  for  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():
     =  psutil.virtual_memory()
     return  {
         'used' : v.total  -  v.available,
         'free' : v.available,
         'total' : v.total,
         'percent' : v.percent,
     }
 
 
def  getVirtualMemory():
     =  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_number
     print  "  \\"
     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:
         pass
 
 
if  __name__  = =  '__main__' :
     header  =  printHeader()
     print  header
     print
 
     system_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()
     print
     getUser()
     print
     getUptime2()


注:脚本内容可以通过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--






本文转自 urey_pp 51CTO博客,原文链接:http://blog.51cto.com/dgd2010/1891468,如需转载请自行联系原作者


相关文章
|
20天前
|
存储 人工智能 搜索推荐
【python】python用户管理系统[简易版](源码+报告)【独一无二】
【python】python用户管理系统[简易版](源码+报告)【独一无二】
|
15天前
|
人工智能 机器人 C++
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
|
6天前
|
数据采集 NoSQL 搜索推荐
五一假期畅游指南:Python技术构建的热门景点分析系统解读
五一假期畅游指南:Python技术构建的热门景点分析系统解读
|
7天前
|
SQL 监控 安全
Linux&Windows 日志分析 陇剑杯 CTF
Linux&Windows 日志分析 陇剑杯 CTF
33 0
|
10天前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
|
11天前
|
Linux Windows
Windows、Mac、Linux解决端口被占用的问题
Windows、Mac、Linux解决端口被占用的问题
18 1
|
11天前
|
机器学习/深度学习 数据可视化 数据挖掘
用Python进行健康数据分析:挖掘医疗统计中的信息
【4月更文挑战第12天】Python在医疗健康数据分析中扮演重要角色,具备数据处理、机器学习、可视化及丰富生态的优势。基本流程包括数据获取、预处理、探索、模型选择与训练、评估优化及结果可视化。应用案例包括疾病预测、药物效果分析和医疗资源优化,例如使用RandomForestClassifier进行疾病预测,Logit模型分析药物效果,以及linprog优化医疗资源配置。
|
13天前
|
安全 Unix Linux
一、linux 常用命令之 linux版本信息 系统管理与设置 持续更新******
一、linux 常用命令之 linux版本信息 系统管理与设置 持续更新******
15 0
|
15天前
|
人工智能 机器人 测试技术
【Python】Python仓储管理系统(源码)【独一无二】
【Python】Python仓储管理系统(源码)【独一无二】
|
18天前
|
安全 Ubuntu Linux
Linux远程访问Windows实现步骤
在Windows上启用远程桌面连接并获取IP地址后,Linux用户需安装SSH客户端( Debian系:`sudo apt-get update; sudo apt-get install openssh-client`,RPM系:`sudo yum install openssh-clients`)。然后使用命令`ssh 用户名@Windows_IP地址`连接,其中`用户名`和`Windows_IP地址`按实际情况填写。
14 4