|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Gentoo dependencies: |
| 3 | +# dev-python/psutil |
| 4 | +# dev-python/pyopenssl |
| 5 | +# sys-apps/lm_sensors |
| 6 | + |
| 7 | +from datetime import datetime |
| 8 | +from datetime import timedelta |
| 9 | +from OpenSSL import crypto |
| 10 | +import os |
| 11 | +import psutil |
| 12 | +import re |
| 13 | +import shlex |
| 14 | +from socket import gethostname |
| 15 | +from socket import getfqdn |
| 16 | +import subprocess |
| 17 | + |
| 18 | +smart_cmd = 'smartctl -H' # Command to use to fetch SMART data (the /dev/x bit will be added for you). |
| 19 | +sensors_cmd = 'sensors' # Command to collect temperature data. |
| 20 | +portage_cmd = 'emerge -puDN world' # Command to build the update list (this is intended to work for portage based repos). |
| 21 | +config_file_ssl = '/etc/weeklycheck/ssl_certs' |
| 22 | + |
| 23 | +version = '1.0.0' |
| 24 | +debug = 0 |
| 25 | + |
| 26 | +# Fetch the uptime from /proc/uptime and format it nicely |
| 27 | +def get_uptime(): |
| 28 | + try: |
| 29 | + with open('/proc/uptime', 'r') as f: |
| 30 | + uptime_seconds = float(f.readline().split()[0]) |
| 31 | + uptime_string = str(timedelta(seconds = uptime_seconds))[:-7] |
| 32 | + except IOError: |
| 33 | + uptime_string = 'Could not open /proc/uptime. Are you sure you\'re using a real computer?' |
| 34 | + return (uptime_string) |
| 35 | + |
| 36 | +# This function handles rounding the disk sizes in get_all_disk_usage() |
| 37 | +def round_disk_size(value_in, reference_size): |
| 38 | + value_in = str(value_in) |
| 39 | + value_out = '' |
| 40 | + reference_size = str(reference_size) |
| 41 | + # Size in B |
| 42 | + if len(reference_size) < 4: |
| 43 | + value_out = value_in + 'B' |
| 44 | + # Size in KB |
| 45 | + elif 4 <= len(reference_size) < 7: |
| 46 | + value_out = value_in[:-3] + 'KB' |
| 47 | + # Size in MB |
| 48 | + elif 7 <= len(reference_size) < 10: |
| 49 | + value_out = value_in[:-6] + 'MB' |
| 50 | + # Size in GB |
| 51 | + elif 10 <= len(reference_size) < 13: |
| 52 | + value_out = value_in[:-9] + 'GB' |
| 53 | + elif 13 <= len(reference_size) < 16: |
| 54 | + value_out = value_in[:-12] + 'TB' |
| 55 | + else: |
| 56 | + print ('We didn\'t handle that size well') |
| 57 | + return value_out |
| 58 | + |
| 59 | +# My python version of df -h. |
| 60 | +def check_all_disk_usage(): |
| 61 | + partition_list = psutil.disk_partitions() |
| 62 | + print (' Partition Path Used Total Percent') |
| 63 | + for partition in partition_list: |
| 64 | + usage_data = psutil.disk_usage(partition[1]) |
| 65 | + used = round_disk_size(str(usage_data[1]), usage_data[0]) |
| 66 | + total = round_disk_size(str(usage_data[0]), usage_data[0]) |
| 67 | + print (' ' + partition[0] + ' ' + partition[1] + ' ' + used + ' ' + total + ' ' + str(usage_data[3])) |
| 68 | + |
| 69 | +# General purpose function to execute shell commands |
| 70 | +def run_shell_cmd(do_this): |
| 71 | + do_this = str(do_this) |
| 72 | + stdout = '' |
| 73 | + proc = subprocess.Popen(shlex.split(do_this), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) |
| 74 | + stdout, stderr = proc.communicate() |
| 75 | + return str(stdout) |
| 76 | + |
| 77 | +# Display SMART data for all disks |
| 78 | +def check_smart_data(): |
| 79 | + dev_list = os.listdir('/dev/') |
| 80 | + search_dev = re.compile('^sd[a-z]$') |
| 81 | + search_result = re.compile('[A-S]{6}') |
| 82 | + for dev in dev_list: |
| 83 | + result = search_dev.match(dev) |
| 84 | + if result: |
| 85 | + health = str(search_result.findall(run_shell_cmd(smart_cmd + ' /dev/' + dev))[0]) |
| 86 | + print (' /dev/' + dev + ': ' + health) |
| 87 | + |
| 88 | +# Get temperatures from sensors |
| 89 | +def check_temp_data(): |
| 90 | + output = run_shell_cmd(sensors_cmd) |
| 91 | + output = output.split('\\n') |
| 92 | + for i in output: |
| 93 | + if 'temp' in i: |
| 94 | + print (' ' + re.sub('\\\\xc2\\\\xb0', '\u00b0', i)) |
| 95 | + |
| 96 | +# Check for portage updates |
| 97 | +def check_portage_updates(): |
| 98 | + output = run_shell_cmd(portage_cmd) |
| 99 | + output = output.split('\\n') |
| 100 | + for i in output: |
| 101 | + if '[ebuild' in i: |
| 102 | + print (' ' + i) |
| 103 | + |
| 104 | +# convert the 20161218201146Z format from the crypto object to something a bit more helpful. |
| 105 | +def ASN1_to_datetime(info): |
| 106 | + year = int(info[0:4]) |
| 107 | + month = int(info[4:6]) |
| 108 | + day = int(info[6:8]) |
| 109 | + hour = int(info[8:10]) |
| 110 | + minute = int(info[10:12]) |
| 111 | + second = int(info[12:14]) |
| 112 | + |
| 113 | + dt = datetime(year, month, day, hour, minute, second, 0) |
| 114 | + |
| 115 | + return dt |
| 116 | + |
| 117 | +# Check one given SSL certificate |
| 118 | +def check_ssl_cert(cert_path): |
| 119 | + error = True |
| 120 | + valid = False |
| 121 | + expires = '' |
| 122 | + |
| 123 | + try: |
| 124 | + f = open(cert_path, 'r') |
| 125 | + except IOError: |
| 126 | + return (error, valid, expires) |
| 127 | + error = False |
| 128 | + |
| 129 | + cert_raw = f.read() |
| 130 | + cert_data = crypto.load_certificate(crypto.FILETYPE_PEM, cert_raw) |
| 131 | + |
| 132 | + if cert_data.has_expired(): |
| 133 | + valid = False |
| 134 | + else: |
| 135 | + valid = True |
| 136 | + expires = ASN1_to_datetime(cert_data.get_notAfter()) |
| 137 | + |
| 138 | + f.close() |
| 139 | + return (error, valid, expires) |
| 140 | + |
| 141 | +# Check all certificates listed in the config file and format things nicely. |
| 142 | +def check_all_ssl_certs(): |
| 143 | + try: |
| 144 | + f = open(config_file_ssl,'r') |
| 145 | + except IOError: |
| 146 | + print (' Could not open SSL cert list from ' + config_file_ssl + '. Unable to check SSL certificates.') |
| 147 | + return |
| 148 | + for line in f: |
| 149 | + if line[0] != '#': |
| 150 | + error, valid, expires = check_ssl_cert(line.rstrip()) |
| 151 | + if error: |
| 152 | + print (' error opening ' + line.rstrip() + '.') |
| 153 | + else: |
| 154 | + remaining = str(expires - datetime.now()) |
| 155 | + if valid: |
| 156 | + print (' ' + line.rstrip() + ': expires ' + str(expires) + ' UTC (' + remaining + ' remaining)') |
| 157 | + else: |
| 158 | + print (' ' + line.rstrip() + ' has expired. You should look into that.') |
| 159 | + f.close() |
| 160 | + |
| 161 | +def main(): |
| 162 | + if debug: |
| 163 | + print ('+----------------------------------------------+') |
| 164 | + print ('| Cam\'s weekly audit - ver ' + version + ' DEV BUILD |') |
| 165 | + print ('| (This totally isn\'t a ripoff of dwaudit) |') |
| 166 | + print ('+----------------------------------------------+') |
| 167 | + else: |
| 168 | + print ('+------------------------------------+') |
| 169 | + print ('| Cam\'s weekly audit - ver ' + version + ' |') |
| 170 | + print ('+------------------------------------+') |
| 171 | + print ('Hostname: {0} ({1})'.format(gethostname(), getfqdn())) |
| 172 | + print ('Uptime: {0}'.format(get_uptime())) |
| 173 | + print ('Generated on {0} at {1} (local time)'.format(datetime.now().strftime('%Y-%m-%d'), datetime.now().strftime('%H:%M:%S'))) |
| 174 | + print ('') |
| 175 | + print ('CPU usage: {0}%'.format(psutil.cpu_percent(interval=0.5))) |
| 176 | + print ('Memory consumption: {0}/{1} ({2}%)'.format(str(psutil.virtual_memory()[3])[:-6],str(psutil.virtual_memory()[0])[:-6],psutil.virtual_memory()[2])) |
| 177 | + print ('Disk Usage:') |
| 178 | + check_all_disk_usage() |
| 179 | + print ('SMART status:') |
| 180 | + check_smart_data() |
| 181 | + print ('System temperatures:') |
| 182 | + check_temp_data() |
| 183 | + print ('Package updates:') |
| 184 | + check_portage_updates() |
| 185 | + print ('Running kernel: {0}'.format(os.uname()[2])) |
| 186 | + print ('SSL certificates:') |
| 187 | + check_all_ssl_certs() |
| 188 | + |
| 189 | +if __name__ == '__main__': |
| 190 | + main() |
0 commit comments