Specify bash to prevent shellcheck from complaining
[khome.git] / home / lib / login_functions.sh
1 #! /bin/bash
2
3 ## open : string -> unit
4 ##
5 ## Fork xdg-open so we don't block current terminal session when opening
6 ## things like pdf files. For example:
7 ##
8 ## open book.pdf
9 ##
10 open() {
11 (xdg-open "$1" &) &
12 }
13
14 ## notify_done : unit -> unit
15 notify_done() {
16 local -r _status_code="$?"
17 local -r _program="$1"
18 local _timestamp
19 _timestamp="$(timestamp)"
20 local -r _msg="$_timestamp [$_program] done "
21 if [[ "$_status_code" -eq 0 ]]
22 then
23 notify-send -u normal "$_msg OK: $_status_code"
24 else
25 notify-send -u critical "$_msg ERROR: $_status_code"
26 fi
27 }
28
29 ## p : string -> unit
30 p() {
31 local -r usage='Usage: p [FILE] NAME'
32 local name
33 local file
34
35 case "$#" in
36 0)
37 echo "$usage" >&2
38 return 1;;
39 1)
40 file=~/._p/p
41 name="$1";;
42 2)
43 file="$1"
44 name="$2";;
45 *)
46 echo "$usage" >&2
47 return 1;;
48 esac
49
50 awk \
51 -v _s="$name" \
52 '
53 BEGIN {_s = tolower(_s)}
54
55 # TODO fzf/dmenu select instead of searching:
56 /^[a-zA-Z]/ && tolower($1) ~ _s && NF >= 2 {
57 n++
58 s = $1
59 p = $NF
60 if (NF == 2) {
61 e = ""
62 u = ""
63 } else if (NF == 3) {
64 e = $2
65 u = ""
66 } else {
67 e = $2
68 u = $3
69 } # TODO What would NF > 4 mean?
70
71 printf("%d [O] s:\"%s\", e:\"%s\", u:\"%s\"\n", n, s, e, u) > "/dev/stderr"
72 if (match(u, "@")) {
73 tmp = e
74 e = u
75 u = tmp
76 printf("%d [C] s:\"%s\", e:\"%s\", u:\"%s\"\n", n, s, e, u) > "/dev/stderr"
77 }
78 ps[n] = p
79 }
80
81 END {
82 printf "%s", ps[n] # XXX Intentionally avoiding newline in the result.
83 if (n == 1) {
84 exit 0
85 } else if (n == 0) {
86 printf "[ERROR] Found nothing.\n" > "/dev/stderr"
87 exit 1
88 } else if (n > 1) {
89 # TODO fzf-select which of the records the user (ahem, me) wants.
90 printf "[WARNING] Found more than one record. Selecting the last one.\n" > "/dev/stderr"
91 exit 0
92 }
93 }
94 ' \
95 "$file" \
96 | xsel -i -b -t 30000
97 }
98
99 dl() {
100 local -r timestamp="$(date --iso-8601=ns)"
101 local -r dir="$HOME"/dl/adhoc/"$timestamp"
102 local -r url_file_path="${dir}/url"
103
104 mkdir -p "$dir"
105 touch "$url_file_path"
106 cd "$dir"
107 }
108
109 ## web search
110 ## ws : string -> unit
111 ws() {
112 local line search_string0 search_string
113
114 search_string0="$*"
115 case "$search_string0" in
116 '')
117 while read -r line; do
118 search_string="${search_string} ${line}"
119 done;;
120 *)
121 search_string="$search_string0";;
122 esac
123
124 firefox --search "$search_string"
125 }
126
127
128 ## dictionary
129 ## d : string -> string list
130 d() {
131 local -r word=$(fzf < /usr/share/dict/words)
132 dict "$word"
133 }
134
135 ## shell_activity_report : (mon | dow) -> string list
136 shell_activity_report() {
137 # TODO: optional concrete number output
138 # TODO: optional combinations of granularities: hour, weekday, month, year
139 local group_by="$1"
140 case "$group_by" in
141 'mon') ;;
142 'dow') ;;
143 '') group_by='dow';;
144 *)
145 echo "Usage: $0 [mon|dow]" >&2
146 kill -INT $$
147 esac
148 history \
149 | awk -v group_by="$group_by" '
150 function date2dow(y, m, d, _t, _i) {
151 # Contract:
152 # y > 1752, 1 <= m <= 12.
153 # Source:
154 # Sakamoto`s methods
155 # https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto%27s_methods
156 _t[ 0] = 0
157 _t[ 1] = 3
158 _t[ 2] = 2
159 _t[ 3] = 5
160 _t[ 4] = 0
161 _t[ 5] = 3
162 _t[ 6] = 5
163 _t[ 7] = 1
164 _t[ 8] = 4
165 _t[ 9] = 6
166 _t[10] = 2
167 _t[11] = 4
168 y -= m < 3
169 _i = int(y + y/4 - y/100 + y/400 + _t[m - 1] + d) % 7
170 _i = _i == 0 ? 7 : _i # Make Sunday last
171 return _i
172
173 }
174
175 {
176 # NOTE: $2 & $3 are specific to oh-my-zsh history output
177 date = $2
178 time = $3
179 d_fields = split(date, d, "-")
180 t_fields = split(time, t, ":")
181 if (t_fields && d_fields) {
182 # +0 to coerce number from string
183 year = d[1] + 0
184 month = d[2] + 0
185 day = d[3] + 0
186 hour = t[1] + 0
187 dow = date2dow(year, month, day)
188 g = group_by == "mon" ? month : dow # dow is default
189 c = count[g, hour]++
190 }
191 if (c > max)
192 max = c
193 }
194
195 END {
196 w[1] = "Monday"
197 w[2] = "Tuesday"
198 w[3] = "Wednesday"
199 w[4] = "Thursday"
200 w[5] = "Friday"
201 w[6] = "Saturday"
202 w[7] = "Sunday"
203
204 m[ 1] = "January"
205 m[ 2] = "February"
206 m[ 3] = "March"
207 m[ 4] = "April"
208 m[ 5] = "May"
209 m[ 6] = "June"
210 m[ 7] = "July"
211 m[ 8] = "August"
212 m[ 9] = "September"
213 m[10] = "October"
214 m[11] = "November"
215 m[12] = "December"
216
217 n = group_by == "mon" ? 12 : 7 # dow is default
218
219 for (gid = 1; gid <= n; gid++) {
220 group = group_by == "mon" ? m[gid] : w[gid]
221 printf "%s\n", group;
222 for (hour=0; hour<24; hour++) {
223 c = count[gid, hour]
224 printf " %2d ", hour
225 for (i = 1; i <= (c * 100) / max; i++)
226 printf "|"
227 printf "\n"
228 }
229 }
230 }'
231 }
232
233 ## top_commands : unit -> (command:string * count:number * bar:string) list
234 top_commands() {
235 history \
236 | awk '
237 {
238 count[$4]++
239 }
240
241 END {
242 for (cmd in count)
243 print count[cmd], cmd
244 }' \
245 | sort -n -r -k 1 \
246 | head -50 \
247 | awk '
248 {
249 cmd[NR] = $2
250 c = count[NR] = $1 + 0 # + 0 to coerce number from string
251 if (c > max)
252 max = c
253 }
254
255 END {
256 for (i = 1; i <= NR; i++) {
257 c = count[i]
258 printf "%s %d ", cmd[i], c
259 scaled = (c * 100) / max
260 for (j = 1; j <= scaled; j++)
261 printf "|"
262 printf "\n"
263 }
264 }' \
265 | column -t
266 }
267
268 ## Top Disk-Using directories
269 ## tdu : path-string -> (size:number * directory:path-string) list
270 tdu() {
271 local -r root_path="$1"
272
273 du -h "$root_path" \
274 | sort -r -h -k 1 \
275 | head -50 \
276 | tac
277 # A slight optimization: head can exit before traversing the full input.
278 }
279
280 ## Top Disk-Using Files
281 ## tduf : path-string list -> (size:number * file:path-string) list
282 tduf() {
283 find "$@" -type f -printf '%s\t%p\0' \
284 | sort -z -n -k 1 \
285 | tail -z -n 50 \
286 | numfmt -z --to=iec \
287 | tr '\0' '\n'
288 }
289
290 # Most-recently modified file system objects
291 ## recent : ?(path-string list) -> path-string list
292 recent() {
293 # NOTES:
294 # - %T+ is a GNU extension;
295 # - gawk is able to split records on \0, while awk cannot.
296 find "$@" -printf '%T@ %T+ %p\0' \
297 | tee >(gawk -v RS='\0' 'END { printf("[INFO] Total found: %d\n", NR); }') \
298 | sort -z -k 1 -n -r \
299 | head -n "$(stty size | awk 'NR == 1 {print $1 - 5}')" -z \
300 | gawk -v RS='\0' '
301 {
302 sub("^" $1 " +", "") # Remove epoch time
303 sub("+", " ") # Blank-out the default separator
304 sub("\\.[0-9]+", "") # Remove fractional seconds
305 print
306 }'
307 }
308
309 ## recent_dirs : ?(path-string list) -> path-string list
310 recent_dirs() {
311 recent "$@" -type d
312 }
313
314 ## recent_files : ?(path-string list) -> path-string list
315 recent_files() {
316 recent "$@" -type f
317 }
318
319 ## pa_def_sink : unit -> string
320 pa_def_sink() {
321 pactl info | awk '/^Default Sink:/ {print $3}'
322 }
323
324 ## void_pkgs : ?(string) -> json
325 void_pkgs() {
326 curl "https://xq-api.voidlinux.org/v1/query/x86_64?q=$1" | jq '.data'
327 }
328
329 ## Colorful man
330 ## man : string -> string
331 man() {
332 # mb: begin blink
333 # md: begin bold
334 # me: end bold, blink and underline
335 #
336 # so: begin standout (reverse video)
337 # se: end standout
338 #
339 # us: begin underline
340 # ue: end underline
341
342 LESS_TERMCAP_md=$'\e[01;30m' \
343 LESS_TERMCAP_me=$'\e[0m' \
344 LESS_TERMCAP_so=$'\e[01;44;33m' \
345 LESS_TERMCAP_se=$'\e[0m' \
346 LESS_TERMCAP_us=$'\e[01;33m' \
347 LESS_TERMCAP_ue=$'\e[0m' \
348 command man "$@"
349 }
350
351 ## new experiment
352 ## x : string list -> unit
353 x() {
354 cd "$(~/bin/x $@)" || kill -INT $$
355 }
356
357 ## ocaml repl
358 ## hump : unit -> unit
359 hump() {
360 ledit -l "$(stty size | awk '{print $2}')" ocaml $@
361 }
362
363 ## search howtos
364 ## howto : unit -> string
365 howto() {
366 cat "$(find ~/arc/doc/HOWTOs -mindepth 1 -maxdepth 1 | sort | fzf)"
367 }
368
369 _yt() {
370 local -r base_dir="$1"
371 local -r uri="$2"
372 local -r opts="$3"
373
374 local -r yt=youtube-dl
375 local -r id=$("$yt" --get-id "$uri")
376 local -r title=$("$yt" --get-title "$uri" | sed 's/[^А-Яа-яA-Za-z0-9._-]/_/g')
377 local -r dir="${base_dir}/${title}--${id}"
378
379 mkdir -p "$dir"
380 cd "$dir" || kill -INT $$
381 echo "$uri" > 'uri'
382 "$yt" $opts -c --write-all-thumbnails --write-description --write-info-json "$uri"
383 }
384
385 yt_audio() {
386 local -r uri="$1"
387 _yt "${DIR_YOUTUBE_AUDIO}/individual" "$uri" '-f 140'
388 }
389
390 yt_video() {
391 local -r uri="$1"
392 _yt "${DIR_YOUTUBE_VIDEO}/individual" "$uri"
393 }
394
395 gh_fetch_repos() {
396 local -r user_type="$1"
397 local -r user_name="$2"
398
399 curl "https://api.github.com/$user_type/$user_name/repos?page=1&per_page=10000"
400 }
401
402 gh_clone() {
403 local -r gh_user_type="$1"
404 local -r gh_user_name="$2"
405
406 local -r gh_dir="${DIR_GITHUB}/${gh_user_name}"
407 mkdir -p "$gh_dir"
408 cd "$gh_dir" || kill -INT $$
409 gh_fetch_repos "$gh_user_type" "$gh_user_name" \
410 | jq --raw-output '.[] | select(.fork | not) | .clone_url' \
411 | parallel -j 25 \
412 git clone {}
413 }
414
415 gh_clone_user() {
416 gh_clone 'users' "$1"
417 }
418
419 gh_clone_org() {
420 gh_clone 'orgs' "$1"
421 }
422
423 gh_clone_repo() {
424 gh_username=$(echo "$1" | awk -F / '"$1 == "https" && $3 == github.com" {print $4}')
425 gh_dir="${DIR_GITHUB}/${gh_username}"
426 mkdir -p "$gh_dir"
427 cd "$gh_dir" || kill -INT $$
428 git clone "$1"
429 }
430
431 bar() {
432 local -r len="${1:-79}" # 1st arg or 79.
433 local -r char="${2:--}" # 2nd arg or a dash.
434 for _ in {1.."$len"}; do
435 printf '%c' "$char";
436 done
437 }
438
439 daily_todo_file_template() {
440 cat << EOF
441 ===============================================================================
442 $(date '+%F %A')
443 ===============================================================================
444
445 -------------------------------------------------------------------------------
446 TODAY
447 -------------------------------------------------------------------------------
448
449
450 -------------------------------------------------------------------------------
451 CURRENT
452 -------------------------------------------------------------------------------
453
454
455 -------------------------------------------------------------------------------
456 BLOCKED
457 -------------------------------------------------------------------------------
458
459
460 -------------------------------------------------------------------------------
461 BACKLOG
462 -------------------------------------------------------------------------------
463 EOF
464 }
465
466 today() {
467 local date
468 date="$(date +%F)"
469 local -r dir="$DIR_TODO/daily"
470 local -r file="$dir/$date.txt"
471
472 mkdir -p "$dir"
473 if [ ! -f "$file" ]
474 then
475 daily_todo_file_template > "$file"
476 fi
477 cd "$DIR_TODO" && "$EDITOR" $EDITOR_ARGS "$file"
478 }
479
480 todo() {
481 cd "$DIR_TODO" && "$EDITOR" TODO
482 }
483
484 work_log_template() {
485 cat << EOF
486 $(date '+%F %A')
487 ==========
488
489 Morning report
490 --------------
491
492 ### Prev
493
494 ### Curr
495
496 ### Next
497
498 ### Blockers
499
500 Day's notes
501 -----------
502 EOF
503 }
504
505 work_log() {
506 mkdir -p "$DIR_WORK_LOG"
507 local -r file_work_log_today="${DIR_WORK_LOG}/daily-$(date +%F).md"
508 if [ ! -f "$file_work_log_today" ]
509 then
510 work_log_template > "$file_work_log_today"
511 fi
512 vim -c 'set spell' "$file_work_log_today"
513
514 }
515
516 note() {
517 mkdir -p "$DIR_NOTES"
518 vim -c 'set spell' "$DIR_NOTES/$(date +'%Y_%m_%d--%H_%M_%S%z')--$1.md"
519 }
520
521 _bt_devs_infos() {
522 # grep's defintion of a line does not include \r, wile awk's does and
523 # which bluetoothctl outputs
524 awk '/^Device +/ {print $2}' \
525 | xargs -I% sh -c 'echo info % | bluetoothctl' \
526 | awk '/^Device |^\t[A-Z][A-Za-z0-9]+: /'
527 }
528
529 bt_devs_paired() {
530 echo 'paired-devices' | bluetoothctl | _bt_devs_infos
531 }
532
533 bt_devs() {
534 echo 'devices' | bluetoothctl | _bt_devs_infos
535 }
536
537 run() {
538 local -r stderr="$(mktemp)"
539
540 local code urgency
541
542 $@ 2> >(tee "$stderr")
543 code="$?"
544 case "$code" in
545 0) urgency='normal';;
546 *) urgency='critical'
547 esac
548 notify-send -u "$urgency" "Job done: $code" "$(cat $stderr)"
549 rm "$stderr"
550 }
551
552 bar_gauge() {
553 awk "$@" '
554 BEGIN {
555 # CLI options
556 width = width ? width : 80
557 ch_left = ch_left ? ch_left : "["
558 ch_right = ch_right ? ch_right : "]"
559 ch_blank = ch_blank ? ch_blank : "-"
560 ch_used = ch_used ? ch_used : "|"
561 num = num ? 1 : 0
562 pct = pct ? 1 : 0
563 }
564
565 {
566 cur = $1
567 max = $2
568 lab = $3
569
570 cur_scaled = num_scale(cur, max, 1, width)
571
572 printf \
573 "%s%s%s%s", \
574 lab ? lab " " : "", \
575 num ? cur "/" max " " : "", \
576 pct ? sprintf("%3.0f%% ", cur / max * 100) : "", \
577 ch_left
578 for (i=1; i<=width; i++) {
579 c = i <= cur_scaled ? ch_used : ch_blank
580 printf "%s", c
581 }
582 printf "%s\n", ch_right
583 }
584
585 function num_scale(src_cur, src_max, dst_min, dst_max) {
586 return dst_min + ((src_cur * (dst_max - dst_min)) / src_max)
587 }
588 '
589 }
590
591 flat_top_5() {
592 sort -n -k 1 -r \
593 | head -5 \
594 | awk '
595 {
596 cur = $1
597 max = $2
598 name = $3
599 pct = cur / max * 100
600 printf "%s%s %.2f%%", sep, name, pct
601 sep = ", "
602 }
603
604 END {printf "\n"}
605 '
606 }
607
608 internet_addr() {
609 curl --silent --show-error --max-time "${1:=1}" 'https://api.ipify.org' 2>&1
610 }
611
612 status_batt() {
613 case "$(uname)" in
614 'Linux')
615 if which upower > /dev/null
616 then
617 upower --dump \
618 | awk '
619 /^Device:[ \t]+/ {
620 device["path"] = $2
621 next
622 }
623
624 / battery/ && device["path"] {
625 device["is_battery"] = 1
626 next
627 }
628
629 / percentage:/ && device["is_battery"] {
630 device["battery_percentage"] = $2
631 sub("%$", "", device["battery_percentage"])
632 next
633 }
634
635 /^$/ {
636 if (device["is_battery"] && device["path"] == "/org/freedesktop/UPower/devices/DisplayDevice")
637 print device["battery_percentage"], 100, "batt"
638 delete device
639 }
640 '
641 fi
642 ;;
643 esac
644 }
645
646 indent() {
647 awk -v unit="$1" '{printf "%s%s\n", unit, $0}'
648 }
649
650 status() {
651 local -r indent_unit=' '
652
653 uname -srvmo
654 hostname | figlet
655 uptime
656
657 echo
658
659 echo 'accounting'
660
661 # TODO Bring back seesion and client listing, but per server/socket.
662 printf '%stmux\n' "$indent_unit"
663 ps -eo comm,cmd \
664 | awk '
665 # Expecting lines like:
666 # "tmux: server tmux -L pistactl new-session -d -s pistactl"
667 # "tmux: client tmux -L foo"
668 # "tmux: client tmux -Lbar"
669 # "tmux: client tmux"
670 # "tmux: server tmux -L foo -S bar" <-- -S takes precedence
671 /^tmux:/ {
672 # XXX This of course assumes pervasive usage of -L
673 # TODO Handle -S
674 role=$2
675
676 split($0, sides_of_S, "-S")
677 split(sides_of_S[2], words_right_of_S, FS)
678
679 split($0, sides_of_L, "-L")
680 split(sides_of_L[2], words_right_of_L, FS)
681
682 if (words_right_of_S[1]) {
683 sock = "path." words_right_of_S[1]
684 } else if (words_right_of_L[1]) {
685 sock = "name." words_right_of_L[1]
686 } else {
687 sock = "default"
688 }
689
690 roles[role]++
691 socks[sock]++
692 count[role, sock]++
693 }
694
695 END {
696 for (sock in socks) {
697 clients = count["client", sock]
698 printf "%s ", sock
699 if (clients) {
700 printf "<-> %d", clients
701 }
702 printf "\n"
703 }
704 printf "\n"
705 }' \
706 | sort \
707 | column -t \
708 | indent "${indent_unit}${indent_unit}"
709
710 echo
711
712 printf '%sprocs by user\n' "${indent_unit}"
713 ps -eo user \
714 | awk '
715 NR > 1 {
716 count_by_user[$1]++
717 total++
718 }
719
720 END {
721 for (user in count_by_user)
722 print count_by_user[user], total, user
723 }
724 ' \
725 | flat_top_5 \
726 | indent "${indent_unit}${indent_unit}"
727
728 echo
729
730 echo 'resources'
731 (
732 free | awk '$1 == "Mem:" {print $3, $2, "mem"}'
733 df ~ | awk 'NR == 2 {print $3, $3 + $4, "disk"}'
734 status_batt
735 ) \
736 | bar_gauge -v width=60 -v pct=1 \
737 | column -t \
738 | indent "$indent_unit"
739
740 echo
741
742 printf '%smem by proc\n' "$indent_unit"
743 ps -eo rss,comm \
744 | awk -v total="$(free | awk '$1 == "Mem:" {print $2; exit}')" '
745 NR > 1 {
746 rss = $1
747 proc = $2
748 by_proc[proc] += rss
749 }
750
751 END {
752 for (proc in by_proc)
753 print by_proc[proc], total, proc
754 }
755 ' \
756 | flat_top_5 \
757 | indent "${indent_unit}${indent_unit}"
758
759 echo
760
761 local _dir temp_input label_file label
762
763 printf '%sthermal\n' "$indent_unit"
764 for _dir in /sys/class/hwmon/hwmon*; do
765 cat "$_dir"/name
766 find "$_dir"/ -name 'temp*_input' \
767 | while read -r temp_input; do
768 label_file=${temp_input//_input/_label}
769 if [ -f "$label_file" ]; then
770 label=$(< "$label_file")
771 else
772 label=''
773 fi
774 awk -v label="$label" '{
775 if (label)
776 label = sprintf(" (%s)", label)
777 printf("%.2f°C%s\n", $1 / 1000, label)
778 }' \
779 "$temp_input"
780 done \
781 | sort \
782 | indent "$indent_unit"
783 done \
784 | indent "${indent_unit}${indent_unit}"
785
786 echo 'net'
787 #local -r internet_addr=$(internet_addr 0.5)
788 #local -r internet_ptr=$(host -W 1 "$internet_addr" | awk 'NR == 1 {print $NF}' )
789
790 #echo "${indent_unit}internet"
791 #echo "${indent_unit}${indent_unit}$internet_addr $internet_ptr"
792 echo "${indent_unit}if"
793 (ifconfig; iwconfig) 2> /dev/null \
794 | awk '
795 /^[^ ]/ {
796 device = $1
797 sub(":$", "", device)
798 if ($4 ~ "ESSID:") {
799 _essid = $4
800 sub("^ESSID:\"", "", _essid)
801 sub("\"$", "", _essid)
802 essid[device] = _essid
803 }
804 next
805 }
806
807 /^ / && $1 == "inet" {
808 address[device] = $2
809 next
810 }
811
812 /^ +Link Quality=[0-9]+\/[0-9]+ +Signal level=/ {
813 split($2, lq_parts_eq, "=")
814 split(lq_parts_eq[2], lq_parts_slash, "/")
815 cur = lq_parts_slash[1]
816 max = lq_parts_slash[2]
817 link[device] = cur / max * 100
818 next
819 }
820
821 END {
822 for (device in address)
823 if (device != "lo") {
824 l = link[device]
825 e = essid[device]
826 l = l ? sprintf("%.0f%%", l) : "--"
827 e = e ? e : "--"
828 print device, address[device], e, l
829 }
830 }
831 ' \
832 | column -t \
833 | indent "${indent_unit}${indent_unit}"
834
835 # WARN: ensure: $USER ALL=(ALL) NOPASSWD:/bin/netstat
836
837 echo "${indent_unit}-->"
838
839 # TODO Populate pid->cmd dict from `ps -eo pid,comm` and lookup progs there
840 # since netstat -p output comes out truncated.
841
842 sudo -n netstat -tulnp \
843 | awk -v indent="${indent_unit}${indent_unit}" '
844 NR > 2 && ((/^tcp/ && proc = $7) || (/^udp/ && proc = $6)) {
845 protocol = $1
846 addr = $4
847 port = a[split(addr, a, ":")]
848 name = p[split(proc, p, "/")]
849 names[name] = 1
850 protocols[protocol] = 1
851 if (!seen[protocol, name, port]++)
852 ports[protocol, name, ++seen[protocol, name]] = port
853 }
854
855 END {
856 for (protocol in protocols) {
857 printf "%s%s\t", indent, toupper(protocol)
858 for (name in names) {
859 if (n = seen[protocol, name]) {
860 sep = ""
861 printf "%s:", name
862 for (i = 1; i <= n; i++) {
863 printf "%s%d", sep, ports[protocol, name, i]
864 sep = ","
865 }
866 printf " "
867 }
868 }
869 printf "\n"
870 }
871 }'
872
873 echo "${indent_unit}<->"
874
875 printf '%sTCP\t' "${indent_unit}${indent_unit}"
876 sudo -n netstat -tnp \
877 | awk 'NR > 2 && $6 == "ESTABLISHED" {print $7}' \
878 | awk '{sub("^[0-9]+/", ""); print}' \
879 | sort -u \
880 | xargs \
881 | column -t
882
883 # TODO: iptables summary
884 }
885
886 ssh_invalid_by_addr() {
887 awk '
888 /: Invalid user/ && $5 ~ /^sshd/ {
889 addr=$10 == "port" ? $9 : $10
890 max++
891 by_addr[addr]++
892 }
893
894 END {
895 for (addr in by_addr)
896 if ((c = by_addr[addr]) > 1)
897 printf "%d %d %s\n", c, max, addr
898 }
899 ' \
900 /var/log/auth.log \
901 /var/log/auth.log.1 \
902 | sort -n -k 1 \
903 | bar_gauge -v width="$(stty size | awk '{print $2}')" -v num=1 -v ch_right=' ' -v ch_left=' ' -v ch_blank=' ' \
904 | column -t
905 }
906
907 ssh_invalid_by_day() {
908 awk '
909 BEGIN {
910 m["Jan"] = "01"
911 m["Feb"] = "02"
912 m["Mar"] = "03"
913 m["Apr"] = "04"
914 m["May"] = "05"
915 m["Jun"] = "06"
916 m["Jul"] = "07"
917 m["Aug"] = "08"
918 m["Sep"] = "09"
919 m["Oct"] = "10"
920 m["Nov"] = "11"
921 m["Dec"] = "12"
922 }
923
924 /: Invalid user/ && $5 ~ /^sshd/ {
925 day = m[$1] "-" $2
926 max++
927 by_day[day]++
928 }
929
930 END {
931 for (day in by_day)
932 if ((c = by_day[day]) > 1)
933 printf "%d %d %s\n", c, max, day
934 }
935 ' \
936 /var/log/auth.log \
937 /var/log/auth.log.1 \
938 | sort -k 3 \
939 | bar_gauge -v width="$(stty size | awk '{print $2}')" -v num=1 -v ch_right=' ' -v ch_left=' ' -v ch_blank=' ' \
940 | column -t
941 }
942
943 ssh_invalid_by_user() {
944 awk '
945 /: Invalid user/ && $5 ~ /^sshd/ {
946 user=$8
947 max++
948 by_user[user]++
949 }
950
951 END {
952 for (user in by_user)
953 if ((c = by_user[user]) > 1)
954 printf "%d %d %s\n", c, max, user
955 }
956 ' \
957 /var/log/auth.log \
958 /var/log/auth.log.1 \
959 | sort -n -k 1 \
960 | bar_gauge -v width="$(stty size | awk '{print $2}')" -v num=1 -v ch_right=' ' -v ch_left=' ' -v ch_blank=' ' \
961 | column -t
962 }
963
964 loggers() {
965 awk '
966 {
967 split($5, prog, "[")
968 sub(":$", "", prog[1]) # if there were no [], than : will is left behind
969 print prog[1]
970 }' /var/log/syslog /var/log/syslog.1 \
971 | awk '
972 {
973 n = split($1, path, "/") # prog may be in path form
974 prog = path[n]
975 total++
976 count[prog]++
977 }
978
979 END {
980 for (prog in count)
981 print count[prog], total, prog
982 }' \
983 | sort -n -k 1 \
984 | bar_gauge -v num=1 -v ch_right=' ' -v ch_left=' ' -v ch_blank=' ' \
985 | column -t
986 }
This page took 0.154662 seconds and 4 git commands to generate.