-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparpass
executable file
·636 lines (522 loc) · 17.8 KB
/
parpass
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
#!/usr/bin/env bash
#
# parpass
# Version: Look at the first constant definitions below!
#
# History: 2020-06-14, 2020-07-11, 2023-11-15, 2023-11-19, 2023-11-20, 2023-11-23, 2024-10-28
#
# Project Description:
#
# Reads the password file /etc/passwd, searches for user names beginning with $1,
# and parses the record to print it in a human-readable form on the screen.
#
# Usage:
# ./parpass <account_name>
#
# Author: Bernd Storck
# Contact: https://www.facebook.com/BStLinux/
#
# Copyright: 2024, Bernd Storck
# License: GNU General Public License 3.0
# set -x
# Daten zur Selbstbeschreibung des Scripts: ...............
readonly ORIGINAL_SCRIPT_NAME="parpass"
readonly CURRENT_SCRIPT_NAME="${0##*/}" ## Name of the script file
readonly TITLE="$ORIGINAL_SCRIPT_NAME (parsePasswd)"
readonly VERSION="1.6.1"
readonly VERSIONS_TIME_STAMP="2024-10-29 17:51:35" # date +"%Y-%m-%d %T"
# Farbnamensvariablen: ....................................
readonly WHITE='\e[0;37m'
readonly WHITE_BOLD='\e[1;37m'
readonly YELLOW='\e[0;33m'
readonly YELLOW_BOLD='\e[1;33m'
readonly YELLOW_BOLD_INTENS='\e[1;93m'
readonly GREEN_BOLD='\e[1;32m'
readonly COLOROFF='\e[0m'
OLDIFS="$IFS"
IFS=":"
declare -a field_descriptions # Array initialization for records with short descriptions for fields of `/etc/passwd`.
declare -a reduced_lines # Array initialization for records reduced by './parpasscut'.
selected_record_fields_index="1-7" # Used like a static var in select_record_fields().
# Defines the name of the language file according to system language:
readonly language_file_name="parpass.lang.${LANG:0:2}"
# Searching for an external language file:
file_found=false
for config_path in "$HOME/parpass/" "$HOME/" "/etc/parpass/" "/etc/" "./"; do
language_file="${config_path}$language_file_name"
if [ -f "$language_file" ]; then
source "${language_file}"
file_found=true
break
fi
done
# If no language file is found the following
# will define English text as default output:
if ! "$file_found" ; then
UILANG="English"
label_ID="IDs (uid/gid)"
label_homeDir="Directory"
label_loginShell="Login Shell"
label_realName="Real Name"
label_room="Room"
label_workPhone="Work Fon"
label_phone="Home Phone"
label_comment="Comment"
field_descriptions[1]="Username;Login name of the user"
field_descriptions[2]="Password;Placeholder for encrypted password (usually 'x')"
field_descriptions[3]="UID;User ID number"
field_descriptions[4]="GID;Primary group ID number"
field_descriptions[5]="GECOS;User information (full name, contact details)"
field_descriptions[6]="Home directory;Path to user's home directory "
field_descriptions[7]="Login shell;Path to user's default shell"
ERROR="ERROR"
ERR_INCORRECT_FIELD="Incorrect field name or number provided"
INFO_CORRECT_FIELDS="Please use a valid field name or field number!"
AVAILABLE_FIELD_NAMES="Available field names"
AVAILABLE_FIELD_NUMBERS="Available field numbers"
FIELD="Field"
fi
# Functions: -----------------------------------------
usage () {
# Displays program purpose and usage help.
echo -e "${YELLOW_BOLD}$TITLE $VERSION ${COLOROFF}\n"
if [ "$UILANG" = "Deutsch" ]; then
echo -e "Das Programm liest die Passwortdatei \"/etc/passwd\" und zeigt ihren Inhalt gut lesbar an.
AUFRUFPARAMETER:
--help|-h|--hilf # Diese Hilfe anzeigen.
--version|-V # Die Version dieses Bash-Skripts anzeigen.
--full_version # Eine ausführliche Versionsinformation anzeigen.
-i <feldname|nummer> # Ein Feld der '/etc/passwd' erklären.
-I # Alle Felder der '/etc/passwd' erklären.
BEISPIELAUFRUFE:
${GREEN_BOLD}Aufruf Beschreibung${COLOROFF}
$(indented_program_call "$CURRENT_SCRIPT_NAME root")# Zeigt die Daten aus der '/etc/passwd' zum Account 'root' an.
$(indented_program_call "$CURRENT_SCRIPT_NAME bs")# Zeigt die Daten zu allen Accounts an, die mit 'bs' beginnen.
$(indented_program_call "$CURRENT_SCRIPT_NAME")# Zeigt die Daten aus der Datei '/etc/passwd' zu allen Accounts an.
$(indented_program_call "$CURRENT_SCRIPT_NAME -i uid")# Erklärt das UID-Feld.
$(indented_program_call "$CURRENT_SCRIPT_NAME -i 7")# Erklärt das 7. Feld der Zeilen in der '/etc/passwd'.
"
else # English help:
echo -e "Reads the password file \"/etc/passwd\" and displays its content in a human-readable format on the screen.
PARAMETERS:
--help|-h|--hilf # Displays this help message.
--version|-V # Displays the script version.
--full_version # Displays detailed version information.
-i <fieldname|number> # Describes a field of '/etc/passwd'.
-I # Describes all fields of '/etc/passwd'.
EXAMPLES:
${GREEN_BOLD}Command Description${COLOROFF}
$(indented_program_call "$CURRENT_SCRIPT_NAME root" "23")# Displays information from the passwd file for the 'root' account.
$(indented_program_call "$CURRENT_SCRIPT_NAME bs" "23")# Displays information about all accounts that begin with 'bs'.
$(indented_program_call "$CURRENT_SCRIPT_NAME" "23")# Displays information from the passwd file for all accounts.
$(indented_program_call "$CURRENT_SCRIPT_NAME -i uid" "23")# Explains the UID field in '/etc/passwd'.
$(indented_program_call "$CURRENT_SCRIPT_NAME -i 7" "23")# Explains the 7th field of the line in '/etc/passwd'.
"
fi
}
# indented_program_call: Formats a program call string for help documentation.
# This function takes a program name as input, and produces a formatted output
# string that aligns example calls uniformly, regardless of any changes to
# the script filename. It ensures consistent indentation by padding the output
# to a specified total length, defaulting to 22 characters if not provided.
indented_program_call () {
local input
local output
local postfix_length
local complete_length
complete_length="${2:-22}"
input="$1"
input_length="${#input}"
postfix_length=$(( complete_length - input_length ))
output="${input}$(printf "%*s" "$postfix_length" "")"
echo "$output"
}
handle_long_options() {
for i in "$@"; do
option=$(normalize_option "$i")
case "$option" in
--help|--hilf)
usage
exit 0
;;
--version)
printf "%s (Version %s)\n" "$ORIGINAL_SCRIPT_NAME" "$VERSION"
exit 0
;;
--fullversion|--id|--identifi[ck]ation)
print_program_identification
exit 0
;;
# --info|--describe|--explain)
# explain_field
# ;;
*)
unset option
;;
esac
done
}
handle_single_letter_options() {
local option
local parameter_value
option="$1"
[ -n "$2" ] && parameter_value="$2"
case $option in
f) # Full-text search in selected fields.
selected_record_fields_index="$parameter_value"
modus="inFieldsSearch"
;;
F) # Full-text search in complete data set, the complete line.
modus="fullSearch"
;;
i) # Short explanation of a field from '/etc/passwd`.
explain_field "$parameter_value"
exit 0
;;
I) # Short explanation of a field from '/etc/passwd`.
explain_all_fields
exit 0
;;
h) usage; exit 0 ;; # Display help
\#) echo "$VERSION"; exit 0 ;; # Display version number
V)
printf "%s (Version %s)\n" "$ORIGINAL_SCRIPT_NAME" "$VERSION"
exit 0
;;
esac
}
identify_target_fields () {
# Parses the parameter value of the option '-f'.
#
local number_of_fields
local data_file
echo "1: \"$1\" / 2: \"$2\""
[ ! "$2" ] && data_file="/etc/passwd" || data_file="$2"
number_of_fields="$(colons="$(head -n 1 "$data_file" | sed -E 's/[^:]//g')";echo "${#colons}")"
echo "[DEBUG] number_of_fields = $number_of_fields"
# Remove numbers greater than 9, which are not used as section numbers:
section="$(sed -E "s/([$(( number_of_fields+1 ))-9]|[[:digit:]]{2,})//" <<< "$1")"
echo "section: \"$section\""
# Remove double commas:
section="$(sed -E 's:,+:,:g' <<< "$section")"
echo "section: \"$section\""
# Remove leading comma:
section="$(sed -E 's:^,::' <<< "$section")"
echo "section: \"$section\""
# Remove comma at the end of the option:
section="$(sed -E 's:,$::' <<< "$section")"
echo "section: \"$section\""; exit
}
print_program_identification () {
# Gibt die vollstaendige Programmselbstbezeichnung aus.
printf "\n${WHITE}%s (%s, %s, %s)${COLOROFF}\n\n" \
"$PROG_NAME" "$ORIGINAL_SCRIPT_NAME" "$VERSION" "$VERSIONS_TIME_STAMP"
}
normalize_option () {
# Wenn eine Option mehr als einen Buchstaben hat, korrigiert diese Funktion
# beispielsweise '-examples' zu '--examples'.
#
# Zudem wandelt sie mehrbuchstabige Optionen in Kleinbuchstaben um.
#
local input="$1"
local output="$input"
if [[ ! "$1" =~ ^[a-zA-Z0-9] ]]; then
input="$input"
# Prueft mit bash-internen Kommandos, ob die Option mit nur genau einem '-'
# beginnt und darauf mindestens zwei Buchtaben folgen und ersetzt
# gegebenenfalls das '-' am Anfang durch '--':
if [[ $input =~ ^-([a-zA-Z]{2,}) ]]; then
output="--${BASH_REMATCH[1]}"
output="${output,,}" # Converts to lower case.
fi
fi
echo "$output"
}
internal_filter () {
# Replaces functionallity of the programs 'look', 'grep' etc.,
# if none of those is available.
local lines
while read -r line; do
if [[ "$line" =~ ^$1 ]]; then
lines+="$line\n"
fi
done < /etc/passwd
printf "%b" "$lines"
}
# Function: get_field_by_name
# Description: This function searches for a specified field name in an array of field descriptions.
# It retrieves the corresponding field description if the field name matches or if
# an alternative field name (if available) matches the searched field name.
# Parameters:
# $1 - The field name to search for. The search is case-insensitive.
# Returns:
# 0 if the field is found, and prints the record counter, field name, and field description.
# Otherwise, it returns 1 if the field is not found (not explicitly handled in this code).
get_field_by_name () {
local searched_field
local record_counter
local field_name
local field_description
local alternative_field_name
local record_length
searched_field="$1"
for content in "${field_descriptions[@]}"; do
(( record_counter++ ))
alternative_field_name=
field_name="${content%%;*}"
field_description="${content#*;}" # Entfernt alles bis zum ersten Semikolon
field_description="${field_description%%;*}" # Entfernt alles ab dem nächsten Semikolon
record_length="$(grep -Fo ';' <<< "$content" 2> /dev/null | wc -l)"
# echo "DEBUG: record_length: \"$record_length\" / content: \"$content\""
if (( record_length == 2 )); then # Holen des dritten Feldes:
alternative_field_name="${content##*;}"
fi
if [ "${searched_field,,}" = "${field_name,,}" ] || [ "${searched_field,,}" = "${alternative_field_name,,}" ] ; then
printf "%d: %s = %s\n" "$record_counter" "$field_name" "$field_description"
return 0
fi
done
}
get_field_names () {
local field_number
local field_name
local answer
for field_number in {1..7}; do
field_name="${field_descriptions[field_number]/;*/}"
answer="${answer}$field_name, "
done
echo -e "${answer:0:-2}"
}
explain_field () {
local field_id
local description
field_id="$1"
if grep -Eq '^[1-7]$' <<< "$field_id" 2> /dev/null; then
description="${field_descriptions[field_id]/;/ = }"
description="${description/;*/}"
printf "%s %d: %s\n" "$FIELD" "$field_id" "$description"
elif grep -Eq '[[:alpha:]]{3,}' <<< "$field_id"; then
get_field_by_name "$field_id"
else
printf "%s: %s: '%s'. %s\n\n" "$ERROR" "$ERR_INCORRECT_FIELD" "$field_id" "$INFO_CORRECT_FIELDS"> /dev/stderr
printf "%s: %s\n" "$AVAILABLE_FIELD_NAMES" "$(get_field_names)." > /dev/stderr
printf "%s: 1-7\n" "$AVAILABLE_FIELD_NUMBERS" > /dev/stderr
fi
exit
}
explain_all_fields () {
local field_number
local description
for field_number in {1..7}; do
description="${field_descriptions[field_number]/;/ = }"
description="${description/;*/}"
printf "%s %d: %s\n" "$FIELD" "$field_number" "$description"
done
}
getLines () {
# Filters those lines which are beginning with "$1".
#
local line_start="$1"
local data_file
local prog
local program_found
local answer
[ ! "$2" ] && data_file="/etc/passwd" || data_file="$2"
for prog in look rg grep agrep tre-agrep; do
if command -v "$prog" > /dev/null 2>&1; then
case "$prog" in
look)
answer="$(look "$line_start" "$data_file")"
;;
rg)
answer="$(rg -N "^$line_start" "$data_file")"
;;
grep|agrep|tre-agrep)
answer="$($prog "^$line_start" "$data_file")"
;;
esac
program_found=true
break
fi
done
if ! "$program_found"; then
answer="$(internal_filter "$1")"
fi
echo "$answer"
}
fullSearch () {
# Gets all lines which do contain "$1".
#
local string_to_find="$1"
local data_file
local prog
local answer
[ -z "$2" ] && data_file="/etc/passwd" || data_file="$2"
prog="$(command -v rg grep agrep tre-agrep 2> /dev/null | head -n 1)"
prog="$(basename "$prog")"
case "$prog" in
rg)
answer="$(rg -NF "$string_to_find" "$data_file")"
;;
grep)
answer="$($prog -F "$string_to_find" "$data_file")"
;;
agrep|tre-agrep)
answer="$($prog -0 "$string_to_find" "$data_file")"
;;
esac
# if ! "$program_found"; then
# answer="$(internal_filter "$1")"
# fi
echo "$answer"
}
inFieldsSearch () {
# Gets all lines whit "$1" in certain fields
#
local string_to_find
local data_file
local prog
local answer
local lines
local field_selectors
field_seletors="$2"
string_to_find="$1"
[ -z "$3" ] && data_file="/etc/passwd" || data_file="$3"
echo "[DEBUG] $field_seletors / $string_to_find / $data_file" > /dev/stderr
prog="$(command -v rg grep agrep tre-agrep 2> /dev/null | head -n 1)"
prog="$(basename "$prog")"
case "$prog" in
rg)
mapfile -c 1 -C select_record_fields -t lines < <(rg -NF "$string_to_find" "$data_file")
for (( i=0; i<=${#lines[@]}; i++ )); do
answer+="${lines[$i]}\n"
done
;;
grep)
answer="$($prog -F "$string_to_find" "$data_file")"
;;
agrep|tre-agrep)
answer="$($prog -0 "$string_to_find" "$data_file")"
;;
esac
# if ! "$program_found"; then
# answer="$(internal_filter "$1")"
# fi
echo "$answer"
}
select_record_fields () {
# Callback function used in inFieldsSearch.
#
local index="$1"
local line="$2" # was: local line=${MAPFILE[$index]}
echo "DEBUG: In 'select_record_fields()'" > /dev/stderr
# Schreibe das gefilterte Ergebnis in ein zweites Array
reduced_lines["$index"]=$(echo "$line" |\
cut -d: -f "$selected_record_fields_index")
}
plotHeadLine () {
local len
local line=
len="$(( 62 - ${#1} ))"
echo -en "\n${YELLOW_BOLD_INTENS}${user} ${YELLOW}"
for ((i=0; i<len; i++ )); do
line+="-"
done
echo -e "$line${COLOROFF}";
}
printField() {
# Pairs of field names and their content are written to a variable,
# allowing the result to be reformatted at the end once all fields
# of a data set are collected in the variable.
dataSet+="\t${WHITE_BOLD}${2}:${COLOROFF}# ${1}\n"
}
printNotEmpty() {
if [ "$1" != "" ]; then
printField "$1" "$2"
fi
}
internal_column () {
# Replaces the external program 'column', if it is not available.
local line
local maxLen=0
while read -r line; do
field1="${line%%#*}" # Like: field1="$(cut -d'#' -f1 <<< "$line")"
if [ "${#field1}" -gt "$maxLen" ]; then
maxLen="${#field1}"
fi
done <<< "$1"
while read -r line; do
IFS="#" read -r field1 field2 <<< "${line}"
printf "%-${maxLen}b %b\n" "$field1" "$field2"
done <<< "$1"
}
getMaxLength () {
local len
local maxLen=0
for fieldName in "$label_ID" "$label_homeDir" "$label_loginShell" "$label_realName" "$label_room" "$label_workPhone" "$label_phone" "$label_comment"; do
len=$(echo -n "$fieldName" | wc -c)
if [ "$len" -gt "$maxLen" ]; then
maxLen="$len"
echo "fieldName: \"$fieldName\" / maxLen = $maxLen" > /dev/stderr
fi
done
echo "$maxLen"
}
external_output () {
local maxLen
maxLen="$(( maxLenOfFieldNames + 10 ))"
# was: echo -e "$1" | column -s# -t
echo -e "$1" |\
awk -F '\n' '{printf "%s\n", $1}' |\
awk -v maxLen="$maxLen" -F '#' '{printf "%-*s\t%s\n", maxLen, $1, $2}'
}
internal_output () {
internal_column "$(echo -e "$1")"
}
# Main: ----------------------------------------------
# Catch calls with long options:
if [ "$#" -gt 0 ]; then
handle_long_options "$@"
fi
# Catch single letter options:
while getopts "f:FIi:hV" opt; do
handle_single_letter_options "$opt" "$OPTARG" "/etc/passwd"
done
shift $((OPTIND-1))
# if command -v column > /dev/null 2>&1; then
if command -v awk > /dev/null 2>&1; then
# echo "DEBUG: external_output" > /dev/stderr
printData="external_output"
else
# echo "DEBUG: internal_output" > /dev/stderr
printData="internal_output"
fi
if [ -z "$modus" ]; then
lines="$(getLines "$1")"
else
lines="$(eval "$modus" "$1" "$2")"
fi
lines="$(echo -e "$lines")"
# Ermitteln des laengsten Feldnamensberzeichners
# in der vom Script gewaehlten Ausagbesprache:
maxLenOfFieldNames="$(getMaxLength)"
if [ -n "$lines" ]; then
while read -r user trash uid gid data homeDir loginShell; do
plotHeadLine "$user"
printField "$uid / $gid" "$label_ID"
printField "$homeDir" "$label_homeDir"
printField "$loginShell" "$label_loginShell"
IFS=','
read -r realName room workPhone phone comment <<< "$data"
printNotEmpty "$realName" "$label_realName"
printNotEmpty "$room" "$label_room"
printNotEmpty "$workPhone" "$label_workPhone"
printNotEmpty "$phone" "$label_phone"
printNotEmpty "$comment" "$label_comment"
"$printData" "$dataSet" # Prints data set to screen.
unset dataSet
IFS=':'
done <<< "$lines"
fi
IFS="$OLDIFS"
exit 0