-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathpyfacts
executable file
·822 lines (716 loc) · 30.5 KB
/
pyfacts
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
#!/usr/bin/python
'''
This script returns all or specified facts about your Mac.
Requirements
------------
+ OS X 10.9.x
+ python 2.7
'''
##############################################################################
# Copyright 2014 Joseph Chilcote
#
# Licensed 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 os
import re
import sys
import socket
import platform
import sysconfig
import subprocess
import argparse
import plistlib
import datetime
import urllib2
import json
from collections import Counter
from AppKit import NSScreen
from CoreFoundation import CFPreferencesCopyAppValue
import objc
# from SystemConfiguration import *
from SystemConfiguration import SCPreferencesCreate, \
SCNetworkServiceCopyAll, \
SCNetworkInterfaceCopyAll, \
SCDynamicStoreCopyComputerName, \
SCDynamicStoreCopyLocalHostName, \
SCDynamicStoreCopyConsoleUser, \
SCNetworkInterfaceGetBSDName, \
SCNetworkInterfaceGetHardwareAddressString, \
SCNetworkInterfaceGetLocalizedDisplayName, \
SCNetworkServiceGetName, \
SCDynamicStoreCreate, \
SCDynamicStoreCopyValue
objc.loadBundle('CoreWLAN',
bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
module_globals=globals())
class Facts(object):
'''
Facts object
Import the module into your python script:
from pyfacts import Facts
fact = Facts()
serial = fact.get_serial()
print serial
'''
def __init__(self):
self.facts = {}
self.prefs = SCPreferencesCreate(None, 'foo', None)
self.network_services = SCNetworkServiceCopyAll(self.prefs)
self.network_interfaces = SCNetworkInterfaceCopyAll()
self.wifi = CWInterface.interfaceNames()
self.net_config = SCDynamicStoreCreate(None, "net", None, None)
self.primaryinterface = self.get_primaryinterface()
self.hardwaredatatype = plistlib.readPlistFromString(
subprocess.check_output(
['/usr/sbin/system_profiler',
'SPHardwareDataType',
'-xml']
))[0]['_items'][0]
if self.wifi:
for iname in self.wifi:
self.interface = CWInterface.interfaceWithName_(iname)
def get_script(self):
'''Returns the name of this script'''
try:
return sys.argv[0]
except:
return None
def get_hostname(self):
'''Returns the hostname of this Mac'''
# hostname = SCDynamicStoreCopyLocalHostName(None)
sys_info = SCDynamicStoreCopyValue(self.net_config, "Setup:/System")
return sys_info['HostName']
def get_computername(self):
'''Returns the ComputerName of this Mac'''
# computername = SCDynamicStoreCopyComputerName(None, None)[0]
sys_info = SCDynamicStoreCopyValue(self.net_config, "Setup:/System")
return sys_info['ComputerName']
def get_kernelversion(self):
'''Returns the darwin version of this Mac
example: 13.1.0'''
return platform.release()
def get_productversion(self):
'''Returns the os x version of this Mac
example: 10.9.2'''
return platform.mac_ver()[0]
def get_productversionmajor(self):
'''Returns the major os x version of this Mac'''
return '.'.join(platform.mac_ver()[0].split('.')[0:2])
def get_productversionminor(self):
'''Returns the minor os x version of this Mac'''
return platform.mac_ver()[0].split('.')[-1]
def get_pythonversion(self):
'''Returns the python version on this Mac'''
return platform.python_version()
def get_architecture(self):
'''Returns the architecture of this Mac
example: x86_64'''
return platform.machine()
def get_platform(self):
'''Returns the processor type of this Mac
exxample: darwin'''
return sys.platform
def get_id(self):
'''Returns the current console user on this Mac'''
## Using SystemConfiguration:
# return SCDynamicStoreCopyConsoleUser(None, None, None)[0]
return os.getlogin()
def get_user(self):
script = ['/usr/bin/last']
users = []
get_last = subprocess.check_output(script)
for line in get_last.splitlines():
if line != '':
name = line.split()
users.append(name[0])
users = Counter(users).most_common()
return users[0][0]
def get_uname(self):
'''Returns the full uname of this Mac as a tuple'''
return os.uname()
def get_sysinfo(self):
'''Returns the system info of this Mac'''
return os.uname()[3]
def get_homedir(self):
'''Returns the home directory of the current user'''
return os.environ['HOME']
def get_prompt(self):
'''Returns the prompt env of the current user'''
try:
pc = os.environ['PROMPT_COMMAND']
except KeyError:
pc = None
return pc
def get_path(self):
'''Returns the path env of the current user'''
return os.environ['PATH']
def get_term(self):
'''Returns the term env of the current user'''
return os.environ['TERM']
def get_termprogram(self):
'''Returns the term program env of the current user'''
try:
tp = os.environ['TERM_PROGRAM']
except KeyError:
tp = None
return tp
def get_shell(self):
'''Returns the shell env of the current user'''
return os.environ['SHELL']
def get_pythoninterpreter(self):
'''Returns the python interpreter on this Mac'''
return os.environ['VERSIONER_PYTHON_VERSION']
def get_editor(self):
'''Returns the editor env of the current user'''
try:
ed = os.environ['EDITOR']
except KeyError:
ed = None
return ed
def get_pwd(self):
'''Returns the pwd'''
try:
pwd = os.environ['PWD']
except KeyError:
pwd = None
return pwd
def get_tmpdir(self):
'''Returns the tempdir env of the current user'''
try:
td = os.environ['TMPDIR']
except KeyError:
td = None
return td
def get_cwd(self):
'''Returns the cwd'''
return os.getcwd()
def get_euid(self):
'''Returns the euid of the current user'''
return os.geteuid()
def get_uid(self):
'''Returns the uid of the current user'''
## Using SystemConfiguration:
# return SCDynamicStoreCopyConsoleUser(None, None, None)[1]
return os.getuid()
def get_egid(self):
'''Returns the egid of the current user'''
return os.getegid()
def get_gid(self):
'''Returns the gid of the current user'''
## Using SystemConfiguration:
# return SCDynamicStoreCopyConsoleUser(None, None, None)[2]
return os.getgid()
def get_groups(self):
'''Returns the groups of the current user'''
return os.getgroups()
def get_ip(self):
'''Returns the IP address of the primary network interface'''
# interface = self.get_primaryinterface()
# try:
# ip = subprocess.check_output(['/usr/sbin/ipconfig', 'getifaddr', interface])
# except subprocess.CalledProcessError:
# ip = 'Unknown'
# return ip.strip()
addresses = SCDynamicStoreCopyValue(self.net_config, "State:/Network/Interface/%s/IPv4" % self.primaryinterface)
try:
return addresses['Addresses'][0]
except TypeError:
return None
def get_external_ip(self):
url = 'http://ipecho.net/plain'
try:
ip = urllib2.urlopen(url).read()
return ip.strip()
except urllib2.HTTPError as err:
return 'Cannot connect to %s: %s' % (url, err)
return 'Unknown'
def get_networkservices(self):
'''Returns a list of all network interface names'''
l = []
for interface in self.network_interfaces:
l.append(SCNetworkInterfaceGetLocalizedDisplayName(interface))
return l
def get_dns_domain(self):
'''Returns the current dns domain'''
dns_info = SCDynamicStoreCopyValue(self.net_config, "State:/Network/Global/DNS")
if dns_info.get('DomainName'):
return dns_info['DomainName']
def get_searchdomains(self):
'''Returns the current search domains'''
l = []
dns_info = SCDynamicStoreCopyValue(self.net_config, "State:/Network/Global/DNS")
if dns_info and dns_info.get('SearchDomains'):
try:
for i in dns_info['SearchDomains']:
l.append(i)
return l
except KeyError as err:
return 'No search domains found'
def get_dns_servers(self):
'''Returns the current dns servers'''
l = []
dns_info = SCDynamicStoreCopyValue(self.net_config, "State:/Network/Global/DNS")
if dns_info:
for i in dns_info['ServerAddresses']:
l.append(i)
return l
def get_searchdomains_from_dhcp(self):
'''Returns a list of search domains'''
interface = self.get_primaryinterface()
cmd = ['/usr/sbin/ipconfig', 'getpacket', interface]
output = subprocess.check_output(cmd)
for line in output.splitlines():
if 'domain_search' in line:
return re.sub('[{}]', '', line.split(': ')[1])
return 'None'
def get_networkinterfacelist(self):
'''Returns a list of all network interface names'''
d = {}
for interface in self.network_interfaces:
d[SCNetworkInterfaceGetLocalizedDisplayName(interface)] = (
SCNetworkInterfaceGetBSDName(interface),
SCNetworkInterfaceGetHardwareAddressString(interface)
)
return d
def get_wifiinterface(self):
'''Returns the name of the Wi-Fi network interface'''
interface = self.get_networkinterfacelist()
try:
return interface['Wi-Fi'][0]
except KeyError:
return None
def get_wifimacaddress(self):
'''Returns the MAC address of the Wi-Fi network interface'''
interface = self.get_networkinterfacelist()
try:
return interface['Wi-Fi'][1]
except KeyError:
return None
def get_wifistatus(self):
'''Returns the wifi status
Yes or No'''
try:
if self.interface.powerOn() == 1:
return "Yes"
return "No"
except AttributeError:
return None
def get_ssid(self):
'''Returns the SSID of the Wi-Fi interface'''
try:
return self.interface.ssid()
except AttributeError:
return None
def get_serial(self):
'''Returns the serial number of the Mac'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-c', 'IOPlatformExpertDevice',
'-d', '2',
'-a'])
d = plistlib.readPlistFromString(output)
return d['IORegistryEntryChildren'][0]['IOPlatformSerialNumber']
def get_activepower(self):
'''Returns the active power source
Battey or AC'''
output = subprocess.check_output(['/usr/bin/pmset', '-g'])
for line in output.splitlines():
if '*' in line:
return line.split(' ')[0]
def get_batterycycles(self):
'''Returns the number of battery cycles'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-r',
'-c', 'AppleSmartBattery',
'-a'])
if output:
d = plistlib.readPlistFromString(output)[0]
return d['CycleCount']
def get_batteryhealth(self):
'''Returns the battery health
Healthy or Failing'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-r',
'-c', 'AppleSmartBattery',
'-a'])
if output:
d = plistlib.readPlistFromString(output)[0]
if not d['PermanentFailureStatus']:
return 'Healthy'
else:
return 'Failing'
def get_batteryserial(self):
'''Returns the serial of the battery'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-r',
'-c', 'AppleSmartBattery',
'-a'])
if output:
d = plistlib.readPlistFromString(output)[0]
return d['BatterySerialNumber']
def get_batterycharging(self):
'''Returns the serial of the battery'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-r',
'-c', 'AppleSmartBattery',
'-a'])
if output:
d = plistlib.readPlistFromString(output)[0]
return d['IsCharging']
def get_batterycharged(self):
'''Returns the serial of the battery'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-r',
'-c', 'AppleSmartBattery',
'-a'])
if output:
d = plistlib.readPlistFromString(output)[0]
return d['FullyCharged']
def get_batteryremaining(self):
'''Returns the serial of the battery'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-r',
'-c', 'AppleSmartBattery',
'-a'])
if output:
d = plistlib.readPlistFromString(output)[0]
return d['TimeRemaining']
def get_batterycapacity(self):
'''Returns the serial of the battery'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-r',
'-c', 'AppleSmartBattery',
'-a'])
if output:
d = plistlib.readPlistFromString(output)[0]
return d['CurrentCapacity']
def get_batterypercentage(self):
'''Returns the percetage of the battery'''
if 'Book' in self.get_model():
task = ['pmset', '-g', 'batt']
return re.findall(r'\d+%', subprocess.check_output(
task))[0].replace('%','')
def get_freespace(self):
'''Returns the free space on the boot drive'''
output = subprocess.check_output(['/usr/sbin/diskutil',
'info',
'-plist',
'/'])
xml = plistlib.readPlistFromString(output)
return int(xml['FreeSpace']) / 1000 / 1000 / 1000
def get_bootcamp(self):
'''Returns whether a bootcamp volume is detected'''
output = subprocess.check_output(['/usr/sbin/diskutil', 'list'])
for line in output.splitlines():
if 'Microsoft Basic Data' in line:
return 'Yes'
return 'No'
def get_filevalutstatus(self):
'''Returns whether filevault is enabled'''
output = subprocess.check_output(['/usr/bin/fdesetup', 'status'])
return output.strip()
def get_gatekeeperstatus(self):
'''Returns whether gatekeeper is enabled'''
proc = subprocess.Popen(['/usr/sbin/spctl', '--status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
return stdout.strip()
def get_primaryinterface(self):
'''Returns the active network interface of the Mac'''
# output = subprocess.check_output(['/usr/sbin/netstat', '-rn'])
# for line in output.splitlines():
# if 'default' in line and not 'utun' in line:
# return line.split(' ')[-1].strip()
try:
states = SCDynamicStoreCopyValue(self.net_config, "State:/Network/Global/IPv4")
return states['PrimaryInterface']
except TypeError:
return None
def get_macaddress(self):
'''Returns the MAC address of the current active network'''
interface = self.primaryinterface
if interface:
output = subprocess.check_output(['/usr/sbin/networksetup',
'-getmacaddress', interface])
return output.split(' ')[2]
def get_model(self):
'''Returns the hardware model of the Mac'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'hw.model'])
return output.strip()
def get_memory(self):
'''Returns the memory in bytes of the Mac'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'hw.memsize'])
return int(output.strip())/1024/1024/1024
def get_processor(self):
'''Returns the processor model of the Mac'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'machdep.cpu.brand_string'])
return output.strip()
def get_is_64(self):
'''Returns whether the Mac is 64-bit capable'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'hw.cpu64bit_capable'])
if output:
return True
return False
def get_buildversion(self):
'''Returns the os build version of the Mac'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'kern.osversion'])
return output.strip()
def get_cpucores(self):
'''Returns how many CPU cores on the Mac'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n', 'hw.ncpu'])
return output.strip()
def get_cpus(self):
'''Returns how many CPUs on the Mac'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'hw.physicalcpu'])
return output.strip()
def get_uuid(self):
'''Returns the UUID of the Mac'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'kern.uuid'])
return output.strip()
def get_screenresolution(self):
'''Returns the screen resolution of the main screen'''
width = NSScreen.mainScreen().frame().size.width
height = NSScreen.mainScreen().frame().size.height
return width, height
def get_sus(self):
'''Returns the custom SUS if set'''
sus = CFPreferencesCopyAppValue('CatalogURL',
'/Library/Preferences/com.apple.SoftwareUpdate.plist')
return sus
def get_javaversion(self):
'''Returns the java plug-in version'''
plist = '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Info.plist'
if os.path.exists(plist):
return CFPreferencesCopyAppValue('CFBundleVersion', plist)
def get_javavendor(self):
'''Returns the java vendor (apple or oracle)'''
plist = '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Info.plist'
if os.path.exists(plist):
return CFPreferencesCopyAppValue('CFBundleIdentifier', plist).split('.')[1]
def get_remotelogin(self):
'''Returns whether remote login is activated'''
if os.geteuid() == 0:
output = subprocess.check_output(['/usr/sbin/systemsetup',
'getremotelogin'])
return output.split(': ')[1].strip()
return "run as root to check this setting"
def get_is_virtual(self):
'''Returns whether the Mac is a virtual machine'''
output = subprocess.check_output(['/usr/sbin/sysctl', '-n',
'machdep.cpu.features'])
if 'VMM' in output:
return True
return False
def get_board_id(self):
'''Returns the board-id of the Mac
Ref: https://github.com/hjuutilainen/adminscripts/blob/master/check-mavericks-compatibility.py'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-p', 'IODeviceTree',
'-r',
'-n', '/',
'-d', '1',
'-a'])
d = plistlib.readPlistFromString(output)
return str(d[0]['board-id']).split("'")[1].split('\\')[0]
def get_drive_model(self):
'''Returns drive model
Ref: https://github.com/hjuutilainen/adminscripts/blob/master/check-mavericks-compatibility.py'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-p', 'IOService',
'-n', 'AppleAHCIDiskDriver',
'-r',
'-l',
'-d', '1',
'-w', '0',
'-a'])
d = plistlib.readPlistFromString(output)
return d[0]['Model'].strip()
def get_drive_revision(self):
'''Returns drive revision
Ref: https://github.com/hjuutilainen/adminscripts/blob/master/check-mavericks-compatibility.py'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-p', 'IOService',
'-n', 'AppleAHCIDiskDriver',
'-r',
'-l',
'-d', '1',
'-w', '0',
'-a'])
d = plistlib.readPlistFromString(output)
return d[0]['Revision'].strip()
def get_drive_serial(self):
'''Returns a tuple of the firmware version of the Mac
Ref: https://github.com/hjuutilainen/adminscripts/blob/master/check-mavericks-compatibility.py'''
output = subprocess.check_output(['/usr/sbin/ioreg',
'-p', 'IOService',
'-n', 'AppleAHCIDiskDriver',
'-r',
'-l',
'-d', '1',
'-w', '0',
'-a'])
d = plistlib.readPlistFromString(output)
return d[0]['Serial Number'].strip()
def get_cidr(self):
'''Returns the cidr of the current network'''
netmask = ''
ip = self.get_ip()
if ip:
output = subprocess.check_output(['/sbin/ifconfig', 'en0'])
for line in output.splitlines():
if ip in line:
netmask = line.split(' ')[3].lower()
count = int(0)
count+=int(netmask.count('f')) * 4
count+=int(netmask.count('e')) * 3
count+=int(netmask.count('c')) * 2
count+=int(netmask.count('8')) * 1
return '%s.%s/%s' % ('.'.join(ip.split('.')[0:3]), '0', count)
def get_bootvolume(self):
'''Returns the boot volume name'''
output = subprocess.check_output(['/usr/sbin/diskutil', 'info',
'-plist', '/'])
xml = plistlib.readPlistFromString(output)
return xml['VolumeName']
def get_recoveryhd(self):
'''Returns the recovery hd device name'''
output = subprocess.check_output(['/usr/sbin/diskutil', 'info',
'-plist', '/'])
xml = plistlib.readPlistFromString(output)
return xml['RecoveryDeviceIdentifier']
def get_volumeuuid(self):
'''Returns the boot volume uuid'''
output = subprocess.check_output(['/usr/sbin/diskutil', 'info',
'-plist', '/'])
xml = plistlib.readPlistFromString(output)
return xml['VolumeUUID']
def get_boottime(self):
'''Returns the system uptime'''
cmd = ['sysctl', '-n', 'kern.boottime']
task = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(epoch, err) = task.communicate()
return ".".join([datetime.datetime.fromtimestamp(int(epoch.split(' = ')[1].split(',')[0])).strftime('%Y-%m-%d %H:%M:%S'), '000'])
def get_is_laptop(self):
'''Returns whether the Mac is a laptop'''
return True if 'book' in self.hardwaredatatype['machine_model'].lower() else False
def get_smc_version(self):
'''Returns the smc version'''
return self.hardwaredatatype['SMC_version_system']
def get_boot_rom(self):
'''Returns the boot rom version'''
return self.hardwaredatatype['boot_rom_version']
def get_activeinterfaces(self):
interfaces = [ SCNetworkInterfaceGetBSDName(i) for i in SCNetworkInterfaceCopyAll() if SCNetworkInterfaceGetBSDName(i).startswith('en') ]
d = {}
for i in interfaces:
try:
d[i] = subprocess.check_output(['/usr/sbin/ipconfig', 'getifaddr', i]).strip()
except subprocess.CalledProcessError:
continue
return d
def get_password_changed(self, username=None):
'''Gets the date of last password change'''
# for 10.10+ or non-migrated accounts
username = SCDynamicStoreCopyConsoleUser(None, None, None)[0]
task = subprocess.check_output(['/usr/bin/dscl', '.', 'read', 'Users/' + username, 'accountPolicyData'])
plist = plistlib.readPlistFromString('\n'.join(task.split()[1:]))
if 'creationTime' in plist.keys():
creation_date = datetime.datetime.utcfromtimestamp(plist['creationTime']).date()
if 'passwordLastSetTime' in plist.keys():
return datetime.datetime.utcfromtimestamp(plist['passwordLastSetTime']).date()
else:
# for 10.9.x and lower, or migrated accounts
task = subprocess.Popen(['/usr/bin/dscl', '.', 'read', 'Users/' + username, 'PasswordPolicyOptions'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = task.communicate()
if not err:
plist = plistlib.readPlistFromString('\n'.join(out.split()[1:]))
if 'passwordLastSetTime' in plist.keys():
return plist['passwordLastSetTime'].date()
return creation_date
def get_password_age(self):
'''Gets the age (in days) since the last password change'''
username = SCDynamicStoreCopyConsoleUser(None, None, None)[0]
if username:
changed = self.get_password_changed(username)
if changed:
today = datetime.datetime.utcnow().date()
pw_age = (today - changed).days
return pw_age
else:
return 'Undetermined'
def get_printers(self):
'''Returns name, ppd, and uri of printers
ref: https://gist.githubusercontent.com/arubdesu/639d3d228824ebc57cc0/raw/fdbef07ded37c8ed8d2c2973e6fa3ede505d0ea2/ad-hoc_inventory.py'''
full_prints = plistlib.readPlistFromString(
subprocess.check_output(
['/usr/sbin/system_profiler',
'SPPrintersDataType',
'-xml']))
all_printdicts = full_prints[0]['_items']
just_prints = {}
for printer in all_printdicts:
just_prints[printer.get('_name', None)] = [printer.get('ppd', None),
printer.get('uri', None)]
return just_prints
def get_adinfo(self):
'''Returns the ad directory info'''
ad_info = SCDynamicStoreCopyValue(self.net_config, "com.apple.opendirectoryd.ActiveDirectory")
return ad_info
def get_dscontactsnode(self):
'''Returns the directory /Contacts node'''
contacts_node = SCDynamicStoreCopyValue(self.net_config, "com.apple.opendirectoryd.node:/Contacts")
return contacts_node[0]
def get_dssearchnode(self):
'''Returns the directory /Search node'''
l = []
search_node = SCDynamicStoreCopyValue(self.net_config, "com.apple.opendirectoryd.node:/Contacts")
return search_node[0]
def main():
'''Runs in interactive mode'''
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--list', help='list categories',
action='store_true')
parser.add_argument('category', help='input category',
nargs=argparse.REMAINDER)
args = parser.parse_args()
facts = Facts()
l = []
for k, v in Facts.__dict__.items():
if callable(v):
l.append(k.replace('get_', ''))
l.remove('__init__')
if args.list:
for i in sorted(l):
print i
elif args.category:
try:
print getattr(facts, 'get_' + args.category[0])()
except AttributeError as err:
print err
exit(1)
else:
d = {}
for i in sorted(l):
print 'Processing: %s' % i
d[i] = getattr(facts, 'get_' + i)()
for k, v in sorted(d.items()):
print '%s => %s' % (k, v)
if __name__ == "__main__":
main()