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