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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
|
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import re
import os
import sys
import platform
def _get_windows_version():
"""
Get's the OS major and minor versions. Returns a tuple of
(OS_MAJOR, OS_MINOR).
"""
import ctypes
class _OSVERSIONINFOEXW(ctypes.Structure):
_fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong),
('dwMajorVersion', ctypes.c_ulong),
('dwMinorVersion', ctypes.c_ulong),
('dwBuildNumber', ctypes.c_ulong),
('dwPlatformId', ctypes.c_ulong),
('szCSDVersion', ctypes.c_wchar*128),
('wServicePackMajor', ctypes.c_ushort),
('wServicePackMinor', ctypes.c_ushort),
('wSuiteMask', ctypes.c_ushort),
('wProductType', ctypes.c_byte),
('wReserved', ctypes.c_byte)]
os_version = _OSVERSIONINFOEXW()
os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version)
retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version))
if retcode != 0:
raise Exception("Failed to get OS version")
return os_version.dwMajorVersion, os_version.dwMinorVersion, os_version.dwBuildNumber, os_version.wProductType
# path to resources dir
RESOURCES_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resources")
# family JSON data
OSFAMILY_JSON_RESOURCE = "os_family.json"
JSON_OS_TYPE = "distro"
JSON_OS_VERSION = "versions"
JSON_EXTENDS = "extends"
#windows family constants
SYSTEM_WINDOWS = "Windows"
REL_2008 = "win2008server"
REL_2008R2 = "win2008serverr2"
REL_2012 = "win2012server"
REL_2012R2 = "win2012serverr2"
# windows machine types
VER_NT_WORKSTATION = 1
VER_NT_DOMAIN_CONTROLLER = 2
VER_NT_SERVER = 3
# Linux specific releases, caching them since they are execution invariants
_IS_ORACLE_LINUX = os.path.exists('/etc/oracle-release')
_IS_REDHAT_LINUX = os.path.exists('/etc/redhat-release')
def _is_oracle_linux():
return _IS_ORACLE_LINUX
def _is_redhat_linux():
return _IS_REDHAT_LINUX
def advanced_check(distribution):
distribution = list(distribution)
if os.path.exists("/etc/issue"):
with open("/etc/issue", "rb") as fp:
issue_content = fp.read()
if "Amazon" in issue_content:
distribution[0] = "amazon"
search_groups = re.search('(\d+)\.(\d+)', issue_content)
if search_groups:
distribution[1] = search_groups.group(1) # if version is 2015.09 only get 2015.
return tuple(distribution)
class OS_CONST_TYPE(type):
# Declare here os type mapping
OS_FAMILY_COLLECTION = []
# Would be generated from Family collection definition
OS_COLLECTION = []
FAMILY_COLLECTION = []
def initialize_data(cls):
"""
Initialize internal data structures from file
"""
try:
f = open(os.path.join(RESOURCES_DIR, OSFAMILY_JSON_RESOURCE))
json_data = eval(f.read())
f.close()
for family in json_data:
cls.FAMILY_COLLECTION += [family]
cls.OS_COLLECTION += json_data[family][JSON_OS_TYPE]
cls.OS_FAMILY_COLLECTION += [{
'name': family,
'os_list': json_data[family][JSON_OS_TYPE]
}]
if JSON_EXTENDS in json_data[family]:
cls.OS_FAMILY_COLLECTION[-1][JSON_EXTENDS] = json_data[family][JSON_EXTENDS]
except:
raise Exception("Couldn't load '%s' file" % OSFAMILY_JSON_RESOURCE)
def __init__(cls, name, bases, dct):
cls.initialize_data()
def __getattr__(cls, name):
"""
Added support of class.OS_<os_type> properties defined in OS_COLLECTION
Example:
OSConst.OS_CENTOS would return centos
OSConst.OS_OTHEROS would triger an error, coz
that os is not present in OS_FAMILY_COLLECTION map
"""
name = name.lower()
if "os_" in name and name[3:] in cls.OS_COLLECTION:
return name[3:]
if "_family" in name and name[:-7] in cls.FAMILY_COLLECTION:
return name[:-7]
raise Exception("Unknown class property '%s'" % name)
class OSConst:
__metaclass__ = OS_CONST_TYPE
class OSCheck:
@staticmethod
def os_distribution():
if platform.system() == SYSTEM_WINDOWS:
# windows distribution
major, minor, build, code = _get_windows_version()
if code in (VER_NT_DOMAIN_CONTROLLER, VER_NT_SERVER):
# we are on server os
release = None
if major == 6:
if minor == 0:
release = REL_2008
elif minor == 1:
release = REL_2008R2
elif minor == 2:
release = REL_2012
elif minor == 3:
release = REL_2012R2
distribution = (release, "{0}.{1}".format(major,minor),"WindowsServer")
else:
# we are on unsupported desktop os
distribution = ("", "","")
else:
# linux distribution
PYTHON_VER = sys.version_info[0] * 10 + sys.version_info[1]
if PYTHON_VER < 26:
distribution = platform.dist()
elif _is_redhat_linux():
distribution = platform.dist()
else:
distribution = platform.linux_distribution()
if distribution[0] == '':
distribution = advanced_check(distribution)
if platform.system().lower() == 'darwin':
# mac - used for unit tests
distribution = ("Darwin", "TestOnly", "1.1.1", "1.1.1", "1.1")
return distribution
@staticmethod
def get_os_type():
"""
Return values:
redhat, fedora, centos, oraclelinux, ascendos,
amazon, xenserver, oel, ovs, cloudlinux, slc, scientific, psbm,
ubuntu, debian, sles, sled, opensuse, suse ... and others
In case cannot detect - exit.
"""
# Read content from /etc/*-release file
# Full release name
dist = OSCheck.os_distribution()
operatingSystem = dist[0].lower()
# special cases
if _is_oracle_linux():
return 'oraclelinux'
elif operatingSystem.startswith('suse linux enterprise server'):
return 'sles'
elif operatingSystem.startswith('red hat enterprise linux'):
return 'redhat'
elif operatingSystem.startswith('darwin'):
return 'mac'
if operatingSystem != '':
return operatingSystem
else:
raise Exception("Cannot detect os type. Exiting...")
@staticmethod
def get_os_family():
"""
Return values:
redhat, debian, suse ... and others
In case cannot detect raises exception( from self.get_operating_system_type() ).
"""
os_family = OSCheck.get_os_type()
for os_family_item in OSConst.OS_FAMILY_COLLECTION:
if os_family in os_family_item['os_list']:
os_family = os_family_item['name']
break
return os_family.lower()
@staticmethod
def get_os_family_parent(os_family):
for os_family_item in OSConst.OS_FAMILY_COLLECTION:
if os_family_item['name'] == os_family:
if JSON_EXTENDS in os_family_item:
return os_family_item[JSON_EXTENDS]
else:
return None
@staticmethod
def get_os_version():
"""
Returns the OS version
In case cannot detect raises exception.
"""
# Read content from /etc/*-release file
# Full release name
dist = OSCheck.os_distribution()
dist = dist[1]
if dist:
return dist
else:
raise Exception("Cannot detect os version. Exiting...")
@staticmethod
def get_os_major_version():
"""
Returns the main OS version like
Centos 6.5 --> 6
RedHat 1.2.3 --> 1
"""
return OSCheck.get_os_version().split('.')[0]
@staticmethod
def get_os_release_name():
"""
Returns the OS release name
In case cannot detect raises exception.
"""
dist = OSCheck.os_distribution()
dist = dist[2].lower()
if dist:
return dist
else:
raise Exception("Cannot detect os release name. Exiting...")
# Exception safe family check functions
@staticmethod
def is_ubuntu_family():
"""
Return true if it is so or false if not
This is safe check for ubuntu/debian families, doesn't generate exception
"""
return OSCheck.is_in_family(OSCheck.get_os_family(), OSConst.UBUNTU_FAMILY)
@staticmethod
def is_suse_family():
"""
Return true if it is so or false if not
This is safe check for suse family, doesn't generate exception
"""
return OSCheck.is_in_family(OSCheck.get_os_family(), OSConst.SUSE_FAMILY)
@staticmethod
def is_redhat_family():
"""
Return true if it is so or false if not
This is safe check for redhat family, doesn't generate exception
"""
return OSCheck.is_in_family(OSCheck.get_os_family(), OSConst.REDHAT_FAMILY)
@staticmethod
def is_in_family(current_family, family):
try:
if current_family == family or OSCheck.get_os_family_parent(current_family) and OSCheck.is_in_family(OSCheck.get_os_family_parent(current_family), family):
return True
except Exception:
pass
return False
@staticmethod
def is_windows_family():
"""
Return true if it is so or false if not
This is safe check for winsrv , doesn't generate exception
"""
try:
return OSCheck.get_os_family() == OSConst.WINSRV_FAMILY
except Exception:
pass
return False
|