-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharch_check.py
More file actions
executable file
·3424 lines (3032 loc) · 148 KB
/
Copy patharch_check.py
File metadata and controls
executable file
·3424 lines (3032 loc) · 148 KB
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
def check_smart(as_dict=False):
"""Check SMART health for all disks using smartctl. Warn if any disk is failing. Return dict if as_dict."""
global issue_count
import glob
import subprocess
results = []
summary = {"status": "ok", "issues": 0, "error": None}
try:
devs = glob.glob('/dev/sd?') + glob.glob('/dev/nvme*n1')
if not devs:
if as_dict:
summary["status"] = "no_disks"
summary["error"] = "No disks found for SMART check."
return {"devices": [], **summary}
print_header("SMART Disk Health Summary")
print(f"{YELLOW}No disks found for SMART check.{RESET}")
return
for dev in devs:
dev_result = {"device": dev, "status": None, "attributes": [], "error": None}
try:
out =subprocess.check_output(["smartctl", "-H", dev], text=True, stderr=subprocess.STDOUT)
if "PASSED" in out:
dev_result["status"] = "PASSED"
if not as_dict:
print(f"{GREEN}{dev}: PASSED{RESET}")
else:
dev_result["status"] = out.strip()
summary["issues"] += 1
summary["status"] = "attention"
if not as_dict:
print(f"{RED}{dev}: {out.strip()}{RESET}")
issue_count += 1
# Optionally collect some attributes
attr = subprocess.check_output(["smartctl", "-A", dev], text=True, stderr=subprocess.STDOUT)
for line in attr.splitlines():
if any(x in line for x in ["Reallocated_Sector_Ct", "Power_On_Hours", "Temperature_Celsius", "Media_Wearout_Indicator"]):
dev_result["attributes"].append(line.strip())
if not as_dict:
print(f" {line.strip()}")
except subprocess.CalledProcessError as e:
dev_result["status"] = "unavailable"
dev_result["error"] = "SMART not available or permission denied."
if not as_dict:
print(f"{YELLOW}{dev}: SMART not available or permission denied.{RESET}")
except Exception as e:
dev_result["status"] = "error"
dev_result["error"] = str(e)
if not as_dict:
print(f"{RED}{dev}: SMART check failed: {e}{RESET}")
results.append(dev_result)
if as_dict:
return {"devices": results, **summary}
print_header("SMART Disk Health Summary")
except FileNotFoundError:
if as_dict:
summary["status"] = "no_smartctl"
summary["error"] = "smartctl command not found. Please install smartmontools."
return {"devices": [], **summary}
print(f"{YELLOW}smartctl command not found. Please install smartmontools.{RESET}")
except Exception as e:
if as_dict:
summary["status"] = "error"
summary["error"] = str(e)
return {"devices": [], **summary}
print(f"{RED}SMART summary failed: {e}{RESET}")
#!/usr/bin/env python3
import subprocess
import os
import sys
import argparse
import shutil
import platform
import logging
import re
# Color control
def get_colors(enable=True):
if enable:
return {
'BLUE': '\033[34m',
'CYAN': '\033[36m',
'RED': '\033[31m',
'GREEN': '\033[32m',
'YELLOW': '\033[33m',
'BOLD': '\033[1m',
'RESET': '\033[0m',
}
else:
return {k: '' for k in ['BLUE','CYAN','RED','GREEN','YELLOW','BOLD','RESET']}
# --- Configuration & Colors ---
# These will be set in main() based on --color/--no-color
BLUE = CYAN = RED = GREEN = YELLOW = BOLD = RESET = ''
# The high-detail ASCII logo provided from https://github.com/deater/linux_logo
ARCH_LOGO = [
f"{CYAN} -` {RESET}",
f"{CYAN} .o+` {RESET}",
f"{CYAN} `ooo/ {RESET}",
f"{CYAN} `+oooo: {RESET}",
f"{CYAN} `+oooooo: {RESET}",
f"{CYAN} -+oooooo+: {RESET}",
f"{CYAN} `/:-:++oooo+: {RESET}",
f"{CYAN} `/++++/+++++++:{RESET}",
f"{CYAN} `/++++++++++++++:{RESET}",
f"{CYAN} `/+++++oooooooooo/`{RESET}",
f"{CYAN} ./ooosssso++osssssso+`{RESET}",
f"{CYAN} .oossssso-````/ossssss+`{RESET}",
f"{CYAN} -osssssso. :ssssssso.{RESET}",
f"{CYAN} :osssssss/ osssso+++.{RESET}",
f"{CYAN} /ossssssss/ +ssssooo/-{RESET}",
f"{CYAN} `/ossssso+/:- -:/+osssso+-{RESET}",
f"{CYAN} `+sso+:-` `.-/+oso:{RESET}",
f"{CYAN} `++:. `-/+/ {RESET}",
f"",
]
# Shared counter for the final summary
issue_count = 0
def print_header(title: str):
print(f"\n{BOLD}{'='*10} {title} {'='*10}{RESET}")
# --- Helper: Device Origin ---
def get_device_origin(mount_point: str):
try:
# findmnt gets the source (e.g., /dev/mapper/volume-home)
result = subprocess.check_output(["findmnt", "-nno", "SOURCE", mount_point], text=True).strip()
dev_name = os.path.basename(result)
# lsblk gets the parent (e.g., cryptlvm or nvme0n1)
lineage = subprocess.check_output(["lsblk", "-no", "PKNAME", result], text=True).strip().split('\n')[-1]
return dev_name, lineage if lineage else dev_name
except:
return "unknown", "unknown"
# --- Main Check Functions ---
def check_sensors(temp_warn: int = 80, as_dict=False):
"""Check and print all available sensor temperatures. Warn if any exceed temp_warn (Celsius)."""
global issue_count
import re
try:
out = subprocess.check_output(["sensors"], text=True)
lines = out.splitlines()
sensors = []
high_found = False
for line in lines:
if "temp" in line.lower() or "core" in line.lower() or "Package id" in line:
match = re.search(r'([+-]?[0-9]+\.[0-9])°C', line)
if match:
temp = float(match.group(1))
entry = {
"label": line.strip(),
"temp": temp,
"warn": temp >= temp_warn,
"color": "red" if temp >= temp_warn else ("yellow" if temp >= temp_warn-10 else "green")
}
sensors.append(entry)
if not as_dict:
color = RED if temp >= temp_warn else (YELLOW if temp >= temp_warn-10 else GREEN)
print(f"{color}{line.strip()}{RESET}")
if temp >= temp_warn:
high_found = True
if as_dict:
return {
"sensors": sensors,
"count": len(sensors),
"high_temp": high_found,
"status": "warn" if high_found else "ok",
"issues": 1 if high_found else 0
}
print_header("Temperature & Sensors")
if high_found:
print(f"{RED}{BOLD}Warning: High temperature detected!{RESET}")
issue_count += 1
if not lines:
print(f"{YELLOW}No sensor data found. Is lm_sensors installed and configured?{RESET}")
except FileNotFoundError:
if as_dict:
return {"sensors": [], "count": 0, "high_temp": False, "status": "no_sensors", "issues": 0, "error": "sensors command not found"}
print(f"{YELLOW}sensors command not found. Please install lm_sensors.{RESET}")
except Exception as e:
if as_dict:
return {"sensors": [], "count": 0, "high_temp": False, "status": "error", "issues": 0, "error": str(e)}
print(f"{RED}Sensor check failed: {e}{RESET}")
def print_logo_info():
# Gather System Info
info = {
'User': os.getlogin(),
'Host': platform.node(),
'OS': "Arch Linux",
'Kernel': platform.release(),
'Shell': os.environ.get('SHELL', 'N/A').split('/')[-1],
}
try:
with open('/proc/cpuinfo', 'r') as f:
cpu = [line.split(':')[1].strip() for line in f if "model name" in line][0]
info['CPU'] = cpu.split('@')[0].strip()
except: info['CPU'] = "Unknown"
try:
with open('/proc/meminfo', 'r') as f:
lines = f.readlines()
total = int(lines[0].split()[1]) // 1024
avail = int(lines[2].split()[1]) // 1024
info['Memory'] = f"{total - avail}MiB / {total}MiB"
except: info['Memory'] = "Unknown"
data_lines = [
f"{CYAN}{BOLD}{info['User']}@{info['Host']}{RESET}",
f"{'─' * (len(info['User']) + len(info['Host']) + 1)}",
f"{BOLD}OS:{RESET} {info['OS']}",
f"{BOLD}Kernel:{RESET} {info['Kernel']}",
f"{BOLD}Shell:{RESET} {info['Shell']}",
f"{BOLD}CPU:{RESET} {info['CPU']}",
f"{BOLD}Memory:{RESET} {info['Memory']}"
]
print("")
for i in range(max(len(ARCH_LOGO), len(data_lines))):
logo = ARCH_LOGO[i] if i < len(ARCH_LOGO) else " " * 20
text = data_lines[i] if i < len(data_lines) else ""
print(f" {logo} {text}")
def check_disk(as_dict=False):
"""Show disk usage, filesystem, device, and origin info for key mounts. Uses lsblk -f -J and /etc/fstab."""
import json
import shutil
import subprocess
import os
global issue_count
import logging
try:
lsblk_out = subprocess.check_output(["lsblk", "-f", "-J"], text=True)
logging.debug(f"lsblk -f -J output: {lsblk_out}")
blkinfo = json.loads(lsblk_out)["blockdevices"]
logging.debug(f"Parsed blkinfo: {blkinfo}")
except Exception as e:
if as_dict:
return {"error": f"lsblk failed: {e}", "status": "error", "issues": 1}
print(f"{RED}lsblk failed: {e}{RESET}")
return
# Parse /etc/fstab for subvolumes and mount options
fstab_info = {}
try:
with open('/etc/fstab', 'r') as fstab:
for line in fstab:
if line.strip() and not line.strip().startswith('#'):
parts = line.split()
if len(parts) > 3:
fstab_info[parts[1]] = parts[3]
logging.debug(f"fstab_info: {fstab_info}")
except Exception as e:
logging.debug(f"Failed to parse /etc/fstab: {e}")
# Gather all mountpoints from lsblk and fstab
def collect_mountpoints_from_lsblk(devs):
mounts = set()
for dev in devs:
mps = dev.get('mountpoints', [])
if mps:
for mp in mps:
if mp:
mounts.add(mp)
if 'children' in dev and dev['children']:
mounts.update(collect_mountpoints_from_lsblk(dev['children']))
return mounts
lsblk_mounts = collect_mountpoints_from_lsblk(blkinfo)
# Also gather mountpoints from fstab (may include unmounted targets)
fstab_mounts = set(fstab_info.keys())
# Union of all mountpoints, sorted for display
all_mounts = sorted(lsblk_mounts | fstab_mounts)
results = []
def find_mount_and_chain(devs, mount, chain=None):
if chain is None:
chain = []
for dev in devs:
mps = dev.get('mountpoints', [])
mps = [mp for mp in mps if mp]
if mount in mps:
return dev, chain + [dev]
if "children" in dev and dev["children"]:
found, found_chain = find_mount_and_chain(dev["children"], mount, chain + [dev]) or (None, None)
if found:
return found, found_chain
return None, None
# Filesystem types and mount names to skip
skip_fstypes = {
'swap', 'tmpfs', 'devtmpfs', 'proc', 'sysfs', 'cgroup', 'mqueue', 'hugetlbfs', 'fusectl', 'configfs', 'securityfs', 'pstore',
'efivarfs', 'debugfs', 'tracefs', 'ramfs', 'overlay', 'squashfs', 'autofs', 'binfmt_misc', 'bpf', 'nsfs',
}
skip_mounts = {'[SWAP]', 'none', ''}
# Parse df -h output for all mounts
df_info = {}
try:
df_out = subprocess.check_output(["df", "-hP"], text=True)
for line in df_out.splitlines()[1:]:
parts = line.split()
if len(parts) >= 6:
mp = parts[5]
df_info[mp] = {
"use_percent": parts[4],
"avail": parts[3]
}
except Exception as e:
logging.debug(f"Failed to parse df -h: {e}")
for mount in all_mounts:
# Find device info first to check fstype
dev_entry, chain = find_mount_and_chain(blkinfo, mount)
fstype = dev_entry.get("fstype", "") if dev_entry else ""
if fstype in skip_fstypes or mount in skip_mounts:
continue
entry = {"mount": mount}
try:
# Btrfs-specific reporting (optional, but will be overwritten by df below)
if fstype == "btrfs":
try:
import re
# Prefer the more-structured 'btrfs filesystem df -b' output (bytes)
btrfs_df = subprocess.check_output(["btrfs", "filesystem", "df", "-b", mount], text=True)
total_bytes = 0
used_bytes = 0
for line in btrfs_df.splitlines():
m_total = re.search(r'total=(\d+)', line)
m_used = re.search(r'used=(\d+)', line)
if m_total:
total_bytes += int(m_total.group(1))
if m_used:
used_bytes += int(m_used.group(1))
if total_bytes > 0:
percent = (used_bytes / total_bytes) * 100
entry["usage_percent"] = round(percent, 1)
entry["free_gb"] = round((total_bytes - used_bytes)/(2**30), 2)
entry["btrfs_device_size_bytes"] = int(total_bytes)
entry["btrfs_used_bytes"] = int(used_bytes)
else:
# Fallback to older 'btrfs filesystem usage -b' parsing if df didn't report totals
btrfs_out = subprocess.check_output(["btrfs", "filesystem", "usage", "-b", mount], text=True)
total_bytes = used_bytes = free_bytes = None
for line in btrfs_out.splitlines():
if "Device size:" in line:
try:
total_bytes = int(line.split(":",1)[1].strip().split()[0])
except Exception:
pass
elif "Used:" in line and "Device size:" not in line:
try:
used_bytes = int(line.split(":",1)[1].strip().split()[0])
except Exception:
pass
elif "Free (estimated):" in line:
try:
free_bytes = int(line.split(":",1)[1].strip().split()[0])
except Exception:
pass
if total_bytes and used_bytes is not None:
percent = (used_bytes / total_bytes) * 100
entry["usage_percent"] = round(percent, 1)
entry["free_gb"] = round((total_bytes - used_bytes)/(2**30), 2)
entry["btrfs_device_size_bytes"] = int(total_bytes)
entry["btrfs_used_bytes"] = int(used_bytes)
if free_bytes is not None:
entry["btrfs_free_estimated_bytes"] = int(free_bytes)
elif total_bytes and free_bytes is not None:
percent = (1 - (free_bytes / total_bytes)) * 100
entry["usage_percent"] = round(percent, 1)
entry["free_gb"] = round(free_bytes/(2**30), 2)
entry["btrfs_device_size_bytes"] = int(total_bytes)
entry["btrfs_free_estimated_bytes"] = int(free_bytes)
else:
entry["usage_percent"] = "?"
entry["free_gb"] = "?"
except Exception as e:
entry["usage_percent"] = "?"
entry["free_gb"] = "?"
entry["btrfs_error"] = str(e)
entry["btrfs_device_size_bytes"] = None
entry["btrfs_used_bytes"] = None
entry["btrfs_free_estimated_bytes"] = None
# Defer detailed subvolume parsing until after we collect fstab info
entry["status"] = "ok"
else:
entry["usage_percent"] = "?"
entry["free_gb"] = "?"
entry["status"] = "ok"
# Overwrite usage and free with df info only for non-Btrfs filesystems
if fstype != "btrfs" and mount in df_info:
try:
entry["usage_percent"] = float(df_info[mount]["use_percent"].strip('%'))
except Exception:
entry["usage_percent"] = df_info[mount]["use_percent"]
entry["free_gb"] = df_info[mount]["avail"]
if entry["usage_percent"] != "?" and isinstance(entry["usage_percent"], float):
if entry["usage_percent"] > 90:
entry["status"] = "critical"
issue_count += 1
elif entry["usage_percent"] > 75:
entry["status"] = "warn"
logging.debug(f"Searching for mount '{mount}' in blkinfo")
# dev_entry, chain already found above
logging.debug(f"Result for mount '{mount}': dev_entry={dev_entry}, chain={chain}")
# Device path
device = f"/dev/{dev_entry['name']}" if dev_entry and 'name' in dev_entry else "?"
entry["device"] = device
# Filesystem
entry["fstype"] = fstype if fstype else "?"
# Type: use 'fsver' if present, else 'type' (lsblk -f -J may not have 'type')
entry["type"] = dev_entry.get("fsver") or dev_entry.get("type", "?") if dev_entry else "?"
# For btrfs, if lsblk didn't provide a useful type, show the btrfs-progs version
if fstype == "btrfs" and (not entry.get("type") or entry.get("type") == "?"):
try:
bv = subprocess.check_output(["btrfs", "--version"], text=True).splitlines()[0]
# Typical output: 'btrfs-progs v5.15.1' -> show version number
parts = bv.split()
entry["type"] = parts[1] if len(parts) > 1 else bv
except Exception:
entry["type"] = "btrfs"
# Label
entry["label"] = dev_entry.get("label", "") if dev_entry else ""
# Origin chain (skip the mount leaf, join parent names)
if chain:
origin = '.'.join([d['name'] for d in chain])
else:
origin = dev_entry['name'] if dev_entry and 'name' in dev_entry else "?"
entry["origin"] = origin
# Subvolume from fstab only
subvol = ""
opts = fstab_info.get(mount, "")
for opt in opts.split(','):
if opt.startswith('subvol='):
subvol = opt.split('=',1)[1]
entry["subvol"] = subvol
# If this is a btrfs mount, try to gather richer subvolume metadata and prefer fstab's subvol if present
if fstype == 'btrfs':
entry.setdefault('subvol_id', None)
entry.setdefault('subvol_path', None)
entry.setdefault('subvol_uuid', None)
entry.setdefault('subvol_name', None)
try:
subvol_show = subprocess.check_output(["btrfs", "subvolume", "show", mount], text=True, stderr=subprocess.DEVNULL)
for line in subvol_show.splitlines():
l = line.strip()
if l.startswith('Subvolume ID:'):
try:
entry['subvol_id'] = int(l.split(':',1)[1].strip())
except Exception:
pass
elif l.startswith('Path:'):
entry['subvol_path'] = l.split(':',1)[1].strip()
elif l.startswith('Name:'):
entry['subvol_name'] = l.split(':',1)[1].strip()
elif l.startswith('UUID:') or l.startswith('Received UUID:'):
# Prefer UUID line if present
entry['subvol_uuid'] = l.split(':',1)[1].strip()
except Exception:
# leave the subvol_* fields as None
pass
# Decide what to show in the human-friendly Subvol column: prefer fstab subvol, then Name, then Path
display_subvol = entry.get('subvol') or entry.get('subvol_name') or entry.get('subvol_path') or ''
# Normalize display: strip leading/trailing slashes
display_subvol = display_subvol.strip('/') if display_subvol else display_subvol
if display_subvol and not display_subvol.startswith('@'):
# keep as-is; many setups name subvolumes with @ prefixes, but don't enforce
pass
# Attach final normalized display value
entry['subvol'] = display_subvol
except Exception as e:
entry["status"] = "error"
entry["error"] = str(e)
logging.debug(f"Error processing mount '{mount}': {e}")
results.append(entry)
if as_dict:
return {"mounts": results, "status": "ok", "issues": sum(1 for e in results if e.get("status") == "critical")}
# Only show the compact Btrfs used/total column when we actually have btrfs mounts
show_btrfs = any((e.get('fstype') == 'btrfs') or (e.get('btrfs_device_size_bytes') is not None) for e in results)
print_header("Disk Usage & Origins")
if show_btrfs:
print(f"{BOLD}{'Mount':<15} : {'Usage':<8} : {'Free':<10} : {'FS':<8} : {'Type':<10} : {'Device':<22} : {'Origin':<36} : {'Btrfs':<18} : {'Subvol'}{RESET}")
print("─" * 160)
else:
print(f"{BOLD}{'Mount':<15} : {'Usage':<8} : {'Free':<10} : {'FS':<8} : {'Type':<10} : {'Device':<22} : {'Origin':<36}{RESET}")
print("─" * 140)
for entry in results:
color = GREEN if entry["status"] == "ok" else (YELLOW if entry["status"] == "warn" else RED)
def safe(val, default="?"):
return str(val) if val is not None else default
# Prepare compact btrfs used/total display when available (only if show_btrfs)
btrfs_col = ""
if show_btrfs:
try:
if entry.get("btrfs_used_bytes") and entry.get("btrfs_device_size_bytes"):
used_gb = float(entry.get("btrfs_used_bytes") or 0) / (2**30)
total_gb = float(entry.get("btrfs_device_size_bytes") or 0) / (2**30)
btrfs_col = f"{used_gb:.2f}/{total_gb:.2f} GiB"
except Exception:
btrfs_col = ""
if show_btrfs:
print(f"{safe(entry['mount']):<15} : {color}{safe(entry.get('usage_percent')):>6}%{RESET} : {safe(entry.get('free_gb')):>7} GB : {safe(entry.get('fstype')):<8} : {safe(entry.get('type')):<10} : {safe(entry.get('device')):<22} : {safe(entry.get('origin')):<36} : {btrfs_col:<18} : {safe(entry.get('subvol'),'')}")
else:
print(f"{safe(entry['mount']):<15} : {color}{safe(entry.get('usage_percent')):>6}%{RESET} : {safe(entry.get('free_gb')):>7} GB : {safe(entry.get('fstype')):<8} : {safe(entry.get('type')):<10} : {safe(entry.get('device')):<22} : {safe(entry.get('origin')):<36}")
def check_kernel():
global issue_count
def _kernel_dict(installed, running, mismatch, details=None, error=None):
return {
"installed": installed,
"running": running,
"mismatch": mismatch,
"details": details or [],
"error": error,
"status": "mismatch" if mismatch else "ok",
"issues": 1 if mismatch else 0
}
import traceback
def _parse_versions(installed, running):
p_v = installed.replace('-', '.').split('.')
r_v = running.replace('-', '.').split('.')
return p_v, r_v
def _labels():
return ['Major', 'Minor', 'Patch', 'Arch Rel']
def check_kernel_inner(as_dict=False):
try:
pac_out = subprocess.check_output(["pacman", "-Qi", "linux"], text=True)
installed = next(l.split(":")[1].strip() for l in pac_out.splitlines() if l.startswith("Version"))
running = subprocess.check_output(["uname", "-r"], text=True).strip()
p_v, r_v = _parse_versions(installed, running)
mismatch = False
details = []
for lbl, p, r in zip(_labels(), p_v, r_v):
if p != r:
mismatch = True
details.append({"component": lbl, "installed": p, "running": r, "match": p == r})
if as_dict:
return _kernel_dict(installed, running, mismatch, details=details)
print_header("Kernel Version Check")
print(f"{'Component':<12} : {'Installed':<12} : {'Running'}")
print("─" * 45)
for d in details:
color = GREEN if d["match"] else RED
eq = '==' if d["match"] else '!='
print(f"{color}{d['component']:<12} : {d['installed']:<12} {eq} {d['running']}{RESET}")
if mismatch:
issue_count += 1
print(f"\n{RED}{BOLD}![REBOOT REQUIRED]: Running kernel mismatch.{RESET}")
except Exception as e:
if as_dict:
return _kernel_dict(None, None, True, error=str(e))
print(f"{RED}Kernel check failed.{RESET}")
return check_kernel_inner
def check_pacnew(as_dict=False):
global issue_count
found = [os.path.join(r, f) for r, _, fs in os.walk('/etc') for f in fs if f.endswith(('.pacnew', '.pacsave'))]
if as_dict:
result = {
"files": found,
"count": len(found),
"status": "pending" if found else "ok",
"issues": len(found) if found else 0
}
return result
print_header("Config Files (.pacnew/.pacsave)")
if found:
issue_count += len(found)
for f in found:
print(f"{YELLOW} -> {f}{RESET}")
else:
print(f"{GREEN}No pending merges.{RESET}")
def check_failed_services(as_dict=False):
global issue_count
try:
out = subprocess.check_output(["systemctl", "list-units", "--state=failed", "--plain", "--no-legend"], text=True).strip()
if out:
lines = out.splitlines()
if as_dict:
return {
"failed_services": [line.split()[0] for line in lines],
"count": len(lines),
"status": "failed",
"issues": len(lines)
}
issue_count += len(lines)
print_header("Failed Services")
for line in lines:
print(f"{RED} -> {line.split()[0]}{RESET}")
else:
if as_dict:
return {"failed_services": [], "count": 0, "status": "ok", "issues": 0}
print_header("Failed Services")
print(f"{GREEN}All units OK.{RESET}")
except Exception as e:
if as_dict:
return {"failed_services": [], "count": 0, "status": "error", "issues": 0, "error": str(e)}
pass
def check_orphans(as_dict=False):
global issue_count
try:
out = subprocess.check_output(["pacman", "-Qdtq"], text=True).strip()
if as_dict:
orphans = out.splitlines() if out else []
return {
"orphans": orphans,
"count": len(orphans),
"status": "found" if orphans else "ok",
"issues": len(orphans)
}
print_header("Orphaned Packages")
if out:
orphan_count = len(out.splitlines())
issue_count += orphan_count
print(f"{YELLOW}Orphans: {out.replace(chr(10), ' ')}{RESET}")
print(f' {RED}Caution: Review the list before removing anything!{RESET}')
print(f' {YELLOW}Tip({RED}potentially dangerous{RESET}): Run "pacman -Rns $(pacman -Qdtq)" to remove orphans, i.e. with pactree:{RESET}')
print(f' for p in {out.replace(chr(10), " ")}; do pactree -r $p; echo {30*"="} ; done')
else:
print(f"{GREEN}No orphans.{RESET}")
except Exception as e:
if as_dict:
return {"orphans": [], "count": 0, "status": "ok", "issues": 0, "error": str(e)}
print(f"{GREEN}No orphans.{RESET}")
def check_stats(as_dict=False):
try:
import pwd
def get_count(flags: str) -> int:
try:
out = subprocess.check_output(["pacman"] + flags.split(), text=True, stderr=subprocess.DEVNULL)
return len(out.strip().splitlines())
except subprocess.CalledProcessError:
return 0
def _dir_size(path: str) -> int:
"""Recursively calculate directory size in bytes. Returns 0 on any error."""
if not os.path.exists(path) or not os.path.isdir(path):
return 0
total = 0
try:
for entry in os.scandir(path):
try:
if entry.is_file(follow_symlinks=False):
total += entry.stat(follow_symlinks=False).st_size
elif entry.is_dir(follow_symlinks=False):
total += _dir_size(entry.path)
except (OSError, PermissionError):
continue
except (OSError, PermissionError):
pass
return total
def _pkg_archive_size(path: str) -> int:
"""Recursively calculate size of .pkg.tar.zst files only. Returns 0 on any error."""
if not os.path.exists(path) or not os.path.isdir(path):
return 0
total = 0
try:
for entry in os.scandir(path):
try:
if entry.is_file(follow_symlinks=False) and entry.name.endswith('.pkg.tar.zst'):
total += entry.stat(follow_symlinks=False).st_size
elif entry.is_dir(follow_symlinks=False):
total += _pkg_archive_size(entry.path)
except (OSError, PermissionError):
continue
except (OSError, PermissionError):
pass
return total
def _fmt_size(bytes_size: int) -> str:
"""Format bytes as human-readable string. Returns '-' if 0 or invalid."""
if bytes_size <= 0:
return "-"
if bytes_size >= 1_000_000_000:
return f"{bytes_size / 1_000_000_000:.1f}G"
elif bytes_size >= 1_000_000:
return f"{int(bytes_size / 1_000_000)}M"
elif bytes_size >= 1_000:
return f"{int(bytes_size / 1_000)}K"
else:
return f"{bytes_size}B"
total = get_count("-Q")
explicit = get_count("-Qe")
deps = get_count("-Qd")
foreign = get_count("-Qm")
native = total - foreign
# Resolve home directory (handle sudo)
sudo_user = os.environ.get('SUDO_USER')
if sudo_user:
try:
home = pwd.getpwnam(sudo_user).pw_dir
except KeyError:
home = os.path.expanduser('~')
else:
home = os.path.expanduser('~')
# Calculate cache sizes
pacman_cache = "/var/cache/pacman/pkg"
yay_cache = os.path.join(home, '.cache', 'yay')
paru_cache = os.path.join(home, '.cache', 'paru', 'clone')
pacman_cache_bytes = _dir_size(pacman_cache) if os.path.exists(pacman_cache) else 0
yay_cache_bytes = _dir_size(yay_cache) if os.path.exists(yay_cache) else 0
yay_cache_pkg_bytes = _pkg_archive_size(yay_cache) if os.path.exists(yay_cache) else 0
paru_cache_bytes = _dir_size(paru_cache) if os.path.exists(paru_cache) else 0
paru_cache_pkg_bytes = _pkg_archive_size(paru_cache) if os.path.exists(paru_cache) else 0
# Format sizes for display
pacman_cache_str = _fmt_size(pacman_cache_bytes)
yay_cache_str = _fmt_size(yay_cache_bytes)
yay_cache_pkg_str = _fmt_size(yay_cache_pkg_bytes)
paru_cache_str = _fmt_size(paru_cache_bytes)
paru_cache_pkg_str = _fmt_size(paru_cache_pkg_bytes)
if as_dict:
return {
"total": total,
"native": native,
"foreign": foreign,
"explicit": explicit,
"dependencies": deps,
"pacman_cache_bytes": pacman_cache_bytes,
"yay_cache_bytes": yay_cache_bytes,
"yay_cache_pkg_bytes": yay_cache_pkg_bytes,
"paru_cache_bytes": paru_cache_bytes,
"paru_cache_pkg_bytes": paru_cache_pkg_bytes,
"status": "ok",
"issues": 0
}
print_header("Pacman Statistics")
print(f"{BOLD}{'Category':<18} : {'Count/Size'}{RESET}")
print("─" * 35)
print(f"{'Total Packages':<18} : {total}")
print(f"{' ┗━ Native':<18} : {native}")
print(f"{' ┗━ Foreign/AUR':<18} : {CYAN}{foreign}{RESET}")
print("-" * 35)
print(f"{'Explicitly Sourced':<18} : {explicit}")
print(f"{'As Dependencies':<18} : {deps}")
print("-" * 35)
# Display cache sizes
if pacman_cache_str != "-":
print(f"{'Pacman Cache':<18} : {YELLOW}{pacman_cache_str}{RESET}")
else:
print(f"{'Pacman Cache':<18} : {CYAN}not found{RESET}")
# yay cache
if yay_cache_str != "-":
if yay_cache_pkg_str != "-":
print(f"{'AUR Cache (yay)':<18} : {YELLOW}{yay_cache_str}{RESET} total, {yay_cache_pkg_str} built pkgs")
else:
print(f"{'AUR Cache (yay)':<18} : {YELLOW}{yay_cache_str}{RESET} total")
else:
print(f"{'AUR Cache (yay)':<18} : {CYAN}not found{RESET}")
# paru cache
if paru_cache_str != "-":
if paru_cache_pkg_str != "-":
print(f"{'AUR Cache (paru)':<18} : {YELLOW}{paru_cache_str}{RESET} total, {paru_cache_pkg_str} built pkgs")
else:
print(f"{'AUR Cache (paru)':<18} : {YELLOW}{paru_cache_str}{RESET} total")
else:
print(f"{'AUR Cache (paru)':<18} : {CYAN}not found{RESET}")
# Show cleanup tips if built packages > 100MB
cleanup_tips = []
if yay_cache_pkg_bytes > 100_000_000:
yay_recoverable = _fmt_size(yay_cache_pkg_bytes)
cleanup_tips.append(f" yay: run 'yay -Sc' to recover ~{yay_recoverable}\n (yay -Sc keeps latest version per package)")
if paru_cache_pkg_bytes > 100_000_000:
paru_recoverable = _fmt_size(paru_cache_pkg_bytes)
cleanup_tips.append(f" paru: run 'paru -Sc' to recover ~{paru_recoverable}\n (paru -Sc keeps latest version per package)")
if cleanup_tips:
print(f"\n{CYAN}Cleanup tips:{RESET}")
for tip in cleanup_tips:
print(tip)
except Exception as e:
if as_dict:
return {"status": "error", "issues": 0, "error": str(e)}
print(f"{RED}Could not retrieve stats: {e}{RESET}")
def check_aur_integrity(as_dict=False):
"""Check integrity of AUR (foreign) packages using pacman -Qk and -Qkk.
Flag packages with missing files (>0) or MODIFIED lines. Skip noisy paths."""
global issue_count
import re
import subprocess
results = []
summary = {"status": "ok", "issues": 0, "packages_checked": 0, "packages_with_issues": []}
try:
# Get foreign packages
out = subprocess.check_output(["pacman", "-Qmq"], text=True).strip()
if not out:
if as_dict:
summary["packages_checked"] = 0
return summary
print_header("AUR Package Integrity")
print(f"{GREEN}No AUR (foreign) packages found.{RESET}")
return
foreign_pkgs = [pkg.strip() for pkg in out.splitlines() if pkg.strip()]
summary["packages_checked"] = len(foreign_pkgs)
# Paths to skip
skip_patterns = [r'\.pyc$', r'\.pyo$', r'\.log$', r'\.lock$', r'/var/', r'/run/']
for pkg in foreign_pkgs:
pkg_result = {"name": pkg, "missing_count": 0, "modified_files": []}
issue_found = False
# Try pacman -Qk (newer pacman)
try:
qk_out = subprocess.check_output(["pacman", "-Qk", pkg], text=True, stderr=subprocess.STDOUT)
# Parse missing count: "X missing" or "X files missing"
for line in qk_out.splitlines():
match = re.search(r'(\d+)\s+missing', line, re.IGNORECASE)
if match:
count = int(match.group(1))
if count > 0:
pkg_result["missing_count"] = count
issue_found = True
except subprocess.CalledProcessError:
pass
# Try pacman -Qkk (stricter, older pacman)
try:
qkk_out = subprocess.check_output(["pacman", "-Qkk", pkg], text=True, stderr=subprocess.STDOUT)
# Look for MODIFIED lines
for line in qkk_out.splitlines():
if "MODIFIED" in line.upper():
# Extract file path (skip noisy paths)
parts = line.split()
if parts:
filepath = parts[-1] if len(parts) > 1 else line.strip()
# Check if we should skip this path
skip = False
for pattern in skip_patterns:
if re.search(pattern, filepath):
skip = True
break
if not skip:
pkg_result["modified_files"].append(filepath)
issue_found = True
except subprocess.CalledProcessError:
pass
if issue_found:
summary["issues"] += 1
summary["status"] = "attention"
results.append(pkg_result)
issue_count += 1
if as_dict:
summary["packages_with_issues"] = results
return summary
print_header("AUR Package Integrity")
if not results:
print(f"{GREEN}All {len(foreign_pkgs)} AUR packages intact.{RESET}")
else:
print(f"{YELLOW}{BOLD}Warning: {len(results)} package(s) with integrity issues:{RESET}")
for pkg_result in results:
print(f"\n{CYAN}{pkg_result['name']}{RESET}")
if pkg_result["missing_count"] > 0:
print(f" {RED}Missing files: {pkg_result['missing_count']}{RESET}")
if pkg_result["modified_files"]:
print(f" {YELLOW}Modified files: {len(pkg_result['modified_files'])}{RESET}")
for f in pkg_result["modified_files"][:5]:
print(f" - {f}")
if len(pkg_result["modified_files"]) > 5:
print(f" ... and {len(pkg_result['modified_files']) - 5} more")
except FileNotFoundError:
if as_dict:
summary["status"] = "no_pacman"
summary["error"] = "pacman command not found"
return summary
print(f"{YELLOW}pacman command not found.{RESET}")
except Exception as e:
if as_dict:
summary["status"] = "error"
summary["error"] = str(e)
return summary
print(f"{RED}AUR integrity check failed: {e}{RESET}")
def check_aur_paths(as_dict=False):
"""Check for non-standard file paths in AUR (foreign) packages.
Flag files not under /usr, /etc, /var, /opt, /lib, /lib32, /bin, /sbin, /run, /share, /usr/local."""
global issue_count
import subprocess
results = []
summary = {"status": "ok", "issues": 0, "packages_checked": 0, "unusual_paths": []}
try:
# Get foreign packages
out = subprocess.check_output(["pacman", "-Qmq"], text=True).strip()
if not out:
if as_dict:
summary["packages_checked"] = 0
return summary
print_header("AUR Package Paths")
print(f"{GREEN}No AUR (foreign) packages found.{RESET}")
return
foreign_pkgs = [pkg.strip() for pkg in out.splitlines() if pkg.strip()]
summary["packages_checked"] = len(foreign_pkgs)
# Allowed path prefixes
allowed_prefixes = ('/usr', '/etc', '/var', '/opt', '/lib', '/lib32', '/bin', '/sbin', '/run', '/share', '/usr/local')
for pkg in foreign_pkgs:
try:
out = subprocess.check_output(["pacman", "-Ql", pkg], text=True)
for line in out.splitlines():
parts = line.split()
if len(parts) >= 2:
filepath = parts[1]
# Skip directory entries
if filepath.endswith('/'):
continue
# Check if path is outside allowed prefixes
if not filepath.startswith(allowed_prefixes):
results.append({"package": pkg, "path": filepath})
summary["issues"] += 1
summary["status"] = "attention"
except subprocess.CalledProcessError:
pass
if as_dict:
summary["unusual_paths"] = results
return summary
print_header("AUR Package Paths")
if not results:
print(f"{GREEN}All {len(foreign_pkgs)} AUR packages use standard paths.{RESET}")
else:
print(f"{YELLOW}{BOLD}Warning: {len(results)} unusual path(s) found:{RESET}")
for item in results:
print(f" {CYAN}{item['package']}{RESET}: {RED}{item['path']}{RESET}")
if summary["issues"] > 0:
issue_count += 1
except FileNotFoundError:
if as_dict:
summary["status"] = "no_pacman"
summary["error"] = "pacman command not found"
return summary
print(f"{YELLOW}pacman command not found.{RESET}")
except Exception as e:
if as_dict:
summary["status"] = "error"
summary["error"] = str(e)
return summary
print(f"{RED}AUR paths check failed: {e}{RESET}")
def check_aur_suid(as_dict=False):
"""Check for setuid/setgid files in AUR (foreign) packages.
Whitelist known safe binaries (chrome-sandbox, pmount, pumount, v4l-conf)."""
global issue_count
import os
import stat
import subprocess