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