-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdisk.py
More file actions
839 lines (673 loc) · 26.9 KB
/
disk.py
File metadata and controls
839 lines (673 loc) · 26.9 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
#! /usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.rst
"""Offers file and disk related functions, like getting a list of
partitions, grepping a file, etc.
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026060801'
import csv
import os
import re
import shutil
import tempfile
from . import shell
def bd2dmd(device):
"""
Retrieve the mapped device name for a device-mapper block device.
This function reads the sysfs entry directly instead of using `dmsetup ls`, thus avoiding
elevated privileges. ("bd2dmd" = block device to device-mapper device).
### Parameters
- **device** (`str`):
The block device name or path (e.g., 'dm-0', '/dev/dm-0').
### Returns
- **str**:
The full path to the mapped device (e.g., '/dev/mapper/rl_rocky8-root'),
or an empty string if not a device-mapper device.
### Example
>>> bd2dmd('dm-0')
'/dev/mapper/rl_rocky8-root'
>>> bd2dmd('sda')
''
"""
device = os.path.basename(device)
success, name = read_file(f'/sys/class/block/{device}/dm/name')
if not success or not name:
return ''
mapped_device = f'/dev/mapper/{name.strip()}'
return mapped_device if os.path.islink(mapped_device) else ''
def copy_dir(src, dst):
"""
Recursively copy a directory tree.
Wraps `shutil.copytree()` and reports the outcome in the same
`(success, error)` style as the other disk helpers, so callers do not have to
handle exceptions themselves.
### Parameters
- **src** (`str`): Source directory.
- **dst** (`str`): Destination directory (must not exist yet).
### Returns
- **tuple**:
- tuple[0] (**bool**): True if the copy succeeded, otherwise False.
- tuple[1] (**None or str**): None on success, otherwise an error message.
### Example
>>> copy_dir('/usr/share/lynis', '/tmp/lynis')
(True, None)
"""
try:
shutil.copytree(src, dst)
return True, None
except (OSError, shutil.Error) as e:
return False, f'Error copying directory {src} to {dst}: {e}'
except Exception as e:
return False, f'Unknown error copying directory {src} to {dst}: {e}'
def copy_file(src, dst):
"""
Copy a single file, preserving its metadata.
Wraps `shutil.copy2()` and reports the outcome in the same `(success, error)`
style as the other disk helpers.
### Parameters
- **src** (`str`): Source file.
- **dst** (`str`): Destination file or directory.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if the copy succeeded, otherwise False.
- tuple[1] (**None or str**): None on success, otherwise an error message.
### Example
>>> copy_file('/etc/lynis/default.prf', '/tmp/lynis/default.prf')
(True, None)
"""
try:
shutil.copy2(src, dst)
return True, None
except OSError as e:
return False, f'OS error "{e.strerror}" while copying {src} to {dst}'
except Exception as e:
return False, f'Unknown error copying {src} to {dst}: {e}'
def dir_exists(path):
"""
Check if a directory exists at the given path.
Use this when you specifically want a directory check. `file_exists()`
only returns `True` for regular files (it is `os.path.isfile()` under
the hood), so passing a directory to it always returns `False`.
### Parameters
- **path** (`str`):
The path to the directory to check.
### Returns
- **bool**:
`True` if the path exists and is a directory (or a symlink to one),
`False` otherwise.
### Example
>>> dir_exists('/etc')
True
>>> dir_exists('/etc/passwd')
False
>>> dir_exists('/path/that/does/not/exist')
False
"""
return os.path.isdir(path)
def file_exists(path, allow_empty=False):
"""
Check if a regular file exists at the given path, optionally allowing
empty files.
This wraps `os.path.isfile()`, so it only matches regular files and
symlinks pointing at regular files. Directories return `False`; use
`dir_exists()` for directory checks.
### Parameters
- **path** (`str`):
The path to the file to check.
- **allow_empty** (`bool`, optional):
If True, consider empty files as existing.
If False, empty files are treated as non-existent. Defaults to False.
### Returns
- **bool**:
True if the file exists (and is non-empty unless `allow_empty` is True), otherwise False.
### Example
>>> file_exists('/path/to/file')
True
>>> file_exists('/path/to/empty_file', allow_empty=False)
False
>>> file_exists('/path/to/empty_file', allow_empty=True)
True
"""
if not os.path.isfile(path):
return False
if allow_empty:
return True
return os.path.getsize(path) > 0
# Block-device name prefixes that never carry meaningful I/O for monitoring
# (loopback, RAM disks, compressed RAM, floppy and optical devices). They are
# skipped by get_block_devices().
_PSEUDO_DEVICE_PREFIXES = ('fd', 'loop', 'ram', 'sr', 'zram')
def get_block_devices():
"""
Return all local block devices that expose I/O counters, mounted or not.
Unlike `get_real_disks()`, which is limited to block devices that currently have a mounted
filesystem, this also includes devices without a mounted filesystem, for example raw devices
backing a database or storage layer, or unmounted multipath/SAN volumes. Devices are
enumerated from `/proc/diskstats`, so their names line up with the per-device I/O counters
exposed there.
Each device is represented as a dictionary with:
- 'bd' : Block device path (e.g. '/dev/sda' or '/dev/dm-7').
- 'dmd': Device-mapper path if the device is a device-mapper target (e.g.
'/dev/mapper/data'), otherwise an empty string.
- 'mp' : Mount point(s), space-separated if mounted in several places, or an empty string if
the device is not mounted.
Pseudo devices that never carry meaningful I/O are skipped by name prefix: loopback (`loop`),
RAM disks (`ram`), compressed RAM (`zram`), floppy (`fd`) and optical (`sr`) devices.
### Parameters
- None
### Returns
- **list of dict**: One entry per block device, including unmounted ones. Empty list on
systems without `/proc/diskstats` (e.g. non-Linux).
### Example
>>> get_block_devices()
[{'bd': '/dev/dm-7', 'dmd': '/dev/mapper/data', 'mp': ''},
{'bd': '/dev/sda1', 'dmd': '', 'mp': '/boot'}]
"""
success, diskstats = read_file('/proc/diskstats')
if not success:
return []
# map every mounted block-device path to its mount point(s)
mountpoints = {}
mounts_ok, mounts_content = read_file('/proc/mounts')
if mounts_ok:
for line in mounts_content.splitlines():
if not line.startswith('/dev/'):
continue
parts = line.split()
device_path, mount_point = parts[0], parts[1]
if device_path in mountpoints:
mountpoints[device_path] += f' {mount_point}'
else:
mountpoints[device_path] = mount_point
disks = []
for line in diskstats.splitlines():
parts = line.split()
if len(parts) < 3:
continue
name = parts[2]
if name.startswith(_PSEUDO_DEVICE_PREFIXES):
continue
bd = f'/dev/{name}'
dmd = bd2dmd(name)
# a device can be mounted under its block-device path or its device-mapper path
mp = mountpoints.get(bd, '') or (mountpoints.get(dmd, '') if dmd else '')
disks.append({'bd': bd, 'dmd': dmd, 'mp': mp})
return disks
def get_cwd():
"""
Get the current working directory.
### Parameters
- None
### Returns
- **str**:
The absolute path of the current working directory.
### Example
>>> get_cwd()
'/home/user/project'
"""
try:
return os.getcwd()
except OSError:
# Optional: handle rare cases where the cwd is invalid (e.g., directory was deleted)
return ''
def get_owner(file):
"""
Get the numeric user ID (UID) of the owner of a filesystem entry.
### Parameters
- **file** *(str | os.PathLike)*:
Path to the file or directory whose owner UID should be retrieved.
### Returns
- **int**:
The owner's UID if available; `-1` if the call fails or ownership cannot be determined.
### Notes
- This function is POSIX-oriented. On Windows, `st_uid` may be `0` for all files
and not reflect the real owner. If you need the account name on Windows,
consider platform-specific APIs (e.g., `win32security`).
- All exceptions are caught and result in `-1`.
### Example
>>> get_owner('/etc/passwd') # doctest: +SKIP (system-dependent)
0
>>> get_owner('/path/does/not/exist')
-1
"""
try:
return os.stat(file).st_uid
except OSError:
return -1
def get_real_disks():
"""
Return a list of real local block devices that are mounted and have a filesystem.
Each device is represented as a dictionary with:
- 'bd': Block device name (e.g., '/dev/sda1' or '/dev/dm-0').
- 'dmd': Device-mapper name if available (e.g., '/dev/mapper/rl-root'), otherwise None.
- 'mp' : Mount point(s), space-separated if mounted in multiple places.
Devices are discovered by parsing /proc/mounts and resolving device-mapper relationships
via udevadm. Devices under /dev/loop* (loopback devices) are ignored.
### Parameters
- None
### Returns
- **list of dict**: List of mounted devices and their details.
### Example
>>> get_real_disks()
[{'bd': '/dev/dm-0', 'dmd': '/dev/mapper/rl-root', 'mp': '/ /home'}]
"""
success, mounts_content = read_file('/proc/mounts')
if not success:
return []
disks = {}
for line in mounts_content.splitlines():
if not line.startswith('/dev/') or line.startswith('/dev/loop'):
continue
parts = line.split()
device_path, mount_point = parts[0], parts[1]
if device_path.startswith('/dev/mapper/'):
dmdname = device_path
bdname = udevadm(dmdname, 'DEVNAME')
else:
bdname = device_path
dmdname = udevadm(bdname, 'DM_NAME')
if dmdname:
dmdname = f'/dev/mapper/{dmdname}'
if bdname not in disks:
disks[bdname] = {'bd': bdname, 'dmd': dmdname, 'mp': mount_point}
else:
disks[bdname]['mp'] += f' {mount_point}'
return list(disks.values())
def get_tmpdir():
"""
Return the absolute path of the directory used for temporary files, without a trailing '/'.
Thin wrapper around `tempfile.gettempdir()`, which picks a usable temporary directory by
trying to create, write and delete a test file in each candidate and returning the first one
that works. The candidates are tried in this order:
- The directories named by the `TMPDIR`, `TEMP` and `TMP` environment variables.
- Platform-specific defaults: on Windows `~\\AppData\\Local\\Temp`, `%SYSTEMROOT%\\Temp`,
`c:\\temp`, `c:\\tmp`, `\\temp`, `\\tmp`; on other systems `/tmp`, `/var/tmp`, `/usr/tmp`.
- As a last resort, the current working directory.
The literal `/tmp` is only returned as a fallback if `tempfile.gettempdir()` itself raises.
### Parameters
- None
### Returns
- **str**: The absolute path to the temporary directory.
### Notes
- `tempfile.gettempdir()` computes the result once and caches it; changing `TMPDIR` and
friends afterwards has no effect for the rest of the process.
- The path is made absolute but not symlink-resolved (`os.path.abspath`, not
`os.path.realpath`), so a caller that needs a trusted location must validate the final path
itself.
### Example
>>> get_tmpdir()
'/tmp'
>>> get_tmpdir()
'C:\\Users\\vagrant\\AppData\\Local\\Temp\\2'
"""
tmpdir = None
try:
tmpdir = tempfile.gettempdir()
except Exception:
pass
return tmpdir or '/tmp' # nosec B108 - fallback when tempfile.gettempdir() fails
def grep_file(filename, pattern):
"""
Search for a regex pattern in a file, similar to the `grep` command.
Returns the first match found; if no match is found or an error occurs, returns False.
### Parameters
- **filename** (`str`): Path to the file to search.
- **pattern** (`str`): A Python regular expression pattern to search for.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if the operation succeeded (no I/O or file handling errors),
otherwise False.
- tuple[1] (**str**): The string matched by `pattern` (if any), or an error message if
unsuccessful.
### Example
>>> success, nc_version = grep_file('version.php', r'\\$OC_version=array\\((.*)\\)')
"""
try:
with open(filename, 'r', encoding='utf-8') as f:
data = f.read()
except OSError as e:
return False, f'I/O error "{e.strerror}" while opening or reading {filename}'
except Exception as e:
return False, f'Unknown error opening or reading {filename}: {e}'
match = re.search(pattern, data)
if match:
return True, match.group(1)
return True, ''
def make_temp_dir(prefix=''):
"""
Create a unique temporary directory and return its path.
Wraps `tempfile.mkdtemp()` and reports the outcome in the same
`(success, result)` style as the other disk helpers.
### Parameters
- **prefix** (`str`, optional): Prefix for the directory name. Defaults to ''.
### Returns
- **tuple**:
- tuple[0] (**bool**): True on success, otherwise False.
- tuple[1] (**str**): The created directory path on success, otherwise an
error message.
### Example
>>> make_temp_dir(prefix='myapp-')
(True, '/tmp/myapp-abcd1234')
"""
try:
return True, tempfile.mkdtemp(prefix=prefix)
except OSError as e:
return False, f'OS error "{e.strerror}" while creating a temporary directory'
except Exception as e:
return False, f'Unknown error creating a temporary directory: {e}'
def mkdir(path, mode=0o755, exist_ok=True):
"""
Create a directory, including any missing parent directories.
Wraps `os.makedirs()` and reports the outcome in the same `(success, error)`
style as the other disk helpers, so callers do not have to handle exceptions
themselves.
### Parameters
- **path** (`str`): Directory path to create.
- **mode** (`int`, optional): Permission bits for newly created directories.
Defaults to `0o755`.
- **exist_ok** (`bool`, optional): If `True`, an already existing directory is
not an error. Defaults to `True`.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if the directory exists afterwards, else False.
- tuple[1] (**None or str**): None on success, otherwise an error message.
### Example
>>> mkdir('/tmp/example/sub')
(True, None)
"""
try:
os.makedirs(path, mode=mode, exist_ok=exist_ok)
return True, None
except OSError as e:
return False, f'OS error "{e.strerror}" while creating {path}'
except Exception as e:
return False, f'Unknown error creating {path}: {e}'
def read_csv(
filename,
delimiter=',',
quotechar='"',
newline='',
as_dict=False,
skip_empty_rows=False,
):
"""
Read a CSV file and return its content as a list or dictionary.
### Parameters
- **filename** (`str`): Path to the CSV file.
- **delimiter** (`str`, optional): The field delimiter character. Defaults to ','.
- **quotechar** (`str`, optional): The character used to quote fields. Defaults to '"'.
- **newline** (`str`, optional): Controls how universal newlines mode works while opening the
file. Defaults to ''.
- **as_dict** (`bool`, optional): If True, return each row as a dictionary using the CSV header.
Defaults to False.
- **skip_empty_rows** (`bool`, optional): If True, skip rows that contain only empty or
whitespace fields. Defaults to False.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if reading succeeded, otherwise False.
- tuple[1] (**list or str**):
- If successful, a list of rows (as lists or dicts depending on `as_dict`).
- If unsuccessful, an error message string.
### Example
>>> success, data = read_csv('data.csv')
>>> success, data = read_csv('data.csv', as_dict=True, skip_empty_rows=True)
"""
reader = None
try:
with open(filename, 'r', newline=newline, encoding='utf-8') as csvfile:
reader = (
csv.DictReader(csvfile, delimiter=delimiter, quotechar=quotechar)
if as_dict
else csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar)
)
data = [
row
for row in reader
if not (
skip_empty_rows
and all(
not str(v).strip()
for v in (row.values() if isinstance(row, dict) else row)
)
)
]
return True, data
except csv.Error as e:
line_num = getattr(reader, 'line_num', 'unknown')
return False, f'CSV error in file {filename}, line {line_num}: {e}'
except OSError as e:
return False, f'I/O error "{e.strerror}" while opening or reading {filename}'
except Exception as e:
return False, f'Unknown error opening or reading {filename}: {e}'
def read_env(filename, delimiter='='):
"""
Read a shell script that sets environment variables and return a dictionary with the
extracted variables.
Lines starting with '#' are treated as comments and ignored. Only lines that set variables
(optionally prefixed with 'export') are processed. More complex shell logic (e.g., conditional
reads) is ignored.
### Parameters
- **filename** (`str`): Path to the environment file to read.
- **delimiter** (`str`, optional): The character that separates keys and values.
Defaults to '='.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if reading succeeded, otherwise False.
- tuple[1] (**dict or str**):
- If successful, a dictionary of environment variable names and values.
- If unsuccessful, an error message string.
### Example
Example shell script 'env.sh':
export OS_AUTH_URL="https://api/v3"
export OS_PROJECT_NAME=mypro
# comment
OS_PASSWORD='linuxfabrik'
[ -z "$OS_PASSWORD" ] && read -e -p "Pass: " OS_PASSWORD
export OS_PASSWORD
>>> read_env('env.sh')
{'OS_AUTH_URL': 'https://api/v3', 'OS_PROJECT_NAME': 'mypro', 'OS_PASSWORD': 'linuxfabrik'}
"""
try:
with open(filename, mode='r', encoding='utf-8') as envfile:
data = {}
for raw_line in envfile:
line = raw_line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('export '):
line = line[7:]
if delimiter not in line:
continue
key, value = line.split(delimiter, 1)
data[key.strip()] = value.strip().strip('\'"')
return True, data
except OSError as e:
return False, f'I/O error "{e.strerror}" while opening or reading {filename}'
except Exception as e:
return False, f'Unknown error opening or reading {filename}: {e}'
def read_file(filename):
"""
Read the contents of a file and return it as a string.
### Parameters
- **filename** (`str`): Path to the file to read.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if reading succeeded, otherwise False.
- tuple[1] (**str**):
- If successful, the contents of the file as a string.
- If unsuccessful, an error message string.
### Example
>>> success, content = read_file('example.txt')
"""
try:
with open(filename, mode='r', encoding='utf-8') as f:
return True, f.read()
except OSError as e:
return False, f'I/O error "{e.strerror}" while opening or reading {filename}'
except Exception as e:
return False, f'Unknown error opening or reading {filename}: {e}'
def rm_dir(path):
"""
Recursively delete a directory tree.
Wraps `shutil.rmtree()` and reports the outcome in the same `(success, error)`
style as `rm_file()`.
### Parameters
- **path** (`str`): Directory tree to delete.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if deletion succeeded, otherwise False.
- tuple[1] (**None or str**): None on success, otherwise an error message.
### Example
>>> rm_dir('/tmp/lynis')
(True, None)
"""
try:
shutil.rmtree(path)
return True, None
except OSError as e:
return False, f'OS error "{e.strerror}" while deleting {path}'
except Exception as e:
return False, f'Unknown error deleting {path}: {e}'
def rm_file(filename):
"""
Delete or remove a file.
### Parameters
- **filename** (`str`): Path to the file to delete.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if deletion succeeded, otherwise False.
- tuple[1] (**None or str**):
- None if the file was successfully deleted.
- An error message string if unsuccessful.
### Example
>>> rm_file('test.txt')
(True, None)
"""
try:
os.remove(filename)
return True, None
except OSError as e:
return False, f'OS error "{e.strerror}" while deleting {filename}'
except Exception as e:
return False, f'Unknown error deleting {filename}: {e}'
def shorten_path(path):
"""
Shorten a path for display.
Abbreviate a slash-separated path by reducing every component except the last one to its
first character, the way the zsh prompt shortens a long working directory. The last
component is kept in full because it usually carries the identifying information. This is
a pure string transformation; the path is not resolved and the filesystem is not touched.
### Parameters
- **path** (`str`): A slash-separated path, for example `/etc/pki/tls/certs/002c0b4f.0`.
### Returns
- **str**: The abbreviated path, for example `/e/p/t/c/002c0b4f.0`. A value without a
slash (a bare basename, an empty string, a sentinel like `-`) is returned unchanged.
### Example
>>> shorten_path('/etc/pki/tls/certs/002c0b4f.0')
'/e/p/t/c/002c0b4f.0'
>>> shorten_path('index.php')
'index.php'
"""
if not path or '/' not in path:
return path
head, _, tail = path.rpartition('/')
abbrev = '/'.join(part[:1] for part in head.split('/'))
return f'{abbrev}/{tail}'
def udevadm(device, _property):
"""
Run `udevadm info` and extract a specific property manually.
To support older systems, the function does not use the `--property=` option
and instead parses all properties manually to find the desired one.
### Parameters
- **device** (`str`): Path to the device (e.g., '/dev/dm-0' or '/dev/mapper/rl-root').
- **_property** (`str`): The property name to retrieve (e.g., 'DEVNAME', 'DM_NAME').
### Returns
- **str**: The value of the requested property if found, otherwise an empty string.
### Example
>>> udevadm('/dev/mapper/rl_rocky8-root', 'DEVNAME')
'/dev/dm-0'
>>> udevadm('/dev/dm-0', 'DM_NAME')
'rl_rocky8-root'
>>> udevadm('/dev/linuxfabrik', 'DEVNAME')
''
"""
success, result = shell.shell_exec(f'udevadm info --query=property --name={device}')
if not success:
return ''
stdout, _, _ = result
for line in stdout.strip().splitlines():
if '=' not in line:
continue
key, value = line.split('=', maxsplit=1)
if key == _property:
return value
return ''
def walk_directory(path, exclude_pattern=r'', include_pattern=r'', relative=True):
"""
Walk recursively through a directory and create a list of files.
If an `exclude_pattern` (regex) is specified, files matching this pattern
are ignored. If an `include_pattern` (regex) is specified, only files matching
this pattern are included. Exclude filtering is applied before include filtering.
### Parameters
- **path** (`str`): The root directory to walk.
- **exclude_pattern** (`str`, optional): Regex pattern to exclude files. Defaults to ''.
- **include_pattern** (`str`, optional): Regex pattern to include files. Defaults to ''.
- **relative** (`bool`, optional): Return relative paths if True, else absolute.
Defaults to True.
### Returns
- **list of str**: List of matching file paths.
### Example
>>> walk_directory('/tmp')
['cpu-usage.db', 'segv_output.MCiVt9']
>>> walk_directory('/tmp', exclude_pattern='.*Temp-.*', relative=False)
['/tmp/cpu-usage.db', '/tmp/segv_output.MCiVt9']
"""
if exclude_pattern:
exclude_pattern = re.compile(exclude_pattern, re.IGNORECASE)
if include_pattern:
include_pattern = re.compile(include_pattern, re.IGNORECASE)
path = path.rstrip('/') + '/'
result = []
for current, _, files in os.walk(path):
for file in files:
full_path = os.path.join(current, file)
if exclude_pattern and exclude_pattern.match(full_path):
continue
if include_pattern and not include_pattern.match(full_path):
continue
result.append(full_path.replace(path, '') if relative else full_path)
return result
def write_file(filename, content, append=False):
"""
Write a string to a file.
If `append` is True, the content is appended to the file instead of overwriting it.
### Parameters
- **filename** (`str`): Path to the file to write to.
- **content** (`str`): The string content to write into the file.
- **append** (`bool`, optional): If True, append to the file; if False, overwrite the file.
Defaults to False.
### Returns
- **tuple**:
- tuple[0] (**bool**): True if writing succeeded, otherwise False.
- tuple[1] (**None or str**):
- None if the file was written successfully.
- An error message string if unsuccessful.
### Example
>>> write_file('test.txt', 'First line\\nSecond line')
(True, None)
"""
try:
mode = 'a' if append else 'w'
with open(filename, mode, encoding='utf-8') as f:
f.write(content)
return True, None
except OSError as e:
return False, f'I/O error "{e.strerror}" while writing {filename}'
except Exception as e:
return False, f'Unknown error writing {filename}: {e}'