-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path.bashrc_remote
More file actions
2022 lines (1801 loc) · 80 KB
/
.bashrc_remote
File metadata and controls
2022 lines (1801 loc) · 80 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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Check and install required packages
check_install_packages() {
local required_packages=("$@")
local missing_packages=()
local package_manager=""
local install_command=""
# Detect package manager
if command -v apt-get >/dev/null 2>&1; then
package_manager="apt"
install_command="apt-get install -y"
elif command -v dnf >/dev/null 2>&1; then
package_manager="dnf"
install_command="dnf install -y"
elif command -v yum >/dev/null 2>&1; then
package_manager="yum"
install_command="yum install -y"
elif command -v apk >/dev/null 2>&1; then
package_manager="apk"
install_command="apk add"
else
echo -e "${red}No supported package manager found (apt, dnf, yum, or apk)${reset}"
return 1
fi
# Package name mappings for different distributions
declare -A package_names
case $package_manager in
"apt")
package_names=(
["source-highlight"]="source-highlight"
["python3"]="python3"
["python3-psutil"]="python3-psutil"
["python3-docker"]="python3-docker"
["python3-requests"]="python3-requests"
["python3-distro"]="python3-distro"
["python3-netifaces"]="python3-netifaces"
["smartmontools"]="smartmontools"
["fio"]="fio"
["bc"]="bc"
["curl"]="curl"
["dmidecode"]="dmidecode"
["ethtool"]="ethtool"
["net-tools"]="net-tools"
["whois"]="whois"
)
;;
"dnf"|"yum")
package_names=(
["source-highlight"]="source-highlight"
["python3"]="python3"
["python3-psutil"]="python3-psutil"
["python3-docker"]="python3-docker"
["python3-requests"]="python3-requests"
["python3-distro"]="python3-distro"
["python3-netifaces"]="python3-netifaces"
["smartmontools"]="smartmontools"
["fio"]="fio"
["bc"]="bc"
["curl"]="curl"
["dmidecode"]="dmidecode"
["ethtool"]="ethtool"
["net-tools"]="net-tools"
["whois"]="whois"
)
;;
"apk")
package_names=(
["source-highlight"]="source-highlight"
["python3"]="python3"
["py3-psutil"]="py3-psutil"
["py3-docker"]="py3-docker"
["py3-requests"]="py3-requests"
["py3-distro"]="py3-distro"
["py3-netifaces"]="py3-netifaces"
["smartmontools"]="smartmontools"
["fio"]="fio"
["bc"]="bc"
["curl"]="curl"
["dmidecode"]="dmidecode"
["ethtool"]="ethtool"
["net-tools"]="net-tools"
["whois"]="whois"
)
;;
esac
# Check for missing packages
for pkg in "${required_packages[@]}"; do
local package_name="${package_names[$pkg]}"
if [ -z "$package_name" ]; then
package_name="$pkg"
fi
case $package_manager in
"apt")
if ! dpkg -l | grep -q "^ii.*$package_name"; then
missing_packages+=("$package_name")
fi
;;
"dnf"|"yum")
if ! rpm -q "$package_name" >/dev/null 2>&1; then
missing_packages+=("$package_name")
fi
;;
"apk")
if ! apk info -e "$package_name" >/dev/null 2>&1; then
missing_packages+=("$package_name")
fi
;;
esac
done
# Install missing packages if any
if [ ${#missing_packages[@]} -gt 0 ]; then
echo -e "\n${yellow}The following packages are required:${reset}"
echo -e "${On_Black}${bold}─────────────────────────────────────────${reset}"
for pkg in "${missing_packages[@]}"; do
echo -e " ${cyan}•${reset} $pkg"
done
echo -e "${On_Black}${bold}─────────────────────────────────────────${reset}\n"
read -p "$(echo -e "${yellow}Do you want to install these packages? [Y/n]${reset} ")" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]] || [[ -z $REPLY ]]; then
echo -e "\n${yellow}Installing packages...${reset}"
if [ "$package_manager" = "apt" ]; then
sudo apt-get update
fi
if sudo $install_command "${missing_packages[@]}"; then
echo -e "\n${green}✓ Successfully installed all required packages${reset}"
return 0
else
echo -e "\n${red}✗ Failed to install some packages${reset}"
return 1
fi
else
echo -e "\n${yellow}⚠ Package installation skipped${reset}"
return 1
fi
fi
return 0
}
# Function to check required packages for a specific command
check_requirements() {
local command_name="$1"
local required_packages=()
case $command_name in
"benchmark")
required_packages=("fio" "bc" "curl" "dmidecode" "ethtool" "net-tools")
;;
"checksec")
required_packages=("net-tools" "whois" "dmidecode" "curl")
;;
"webshare")
required_packages=("python3")
;;
"logwatch")
required_packages=("bc")
;;
esac
if [ ${#required_packages[@]} -gt 0 ]; then
if ! check_install_packages "${required_packages[@]}"; then
echo -e "${red}Unable to proceed: missing required packages${reset}"
return 1
fi
fi
return 0
}
. /etc/profile
. ~/.bashrc
# Color variables:
export black='\033[0;30m'
export red="\e[0;31m"
export green="\e[0;32m"
export yellow="\e[0;33m"
export blue="\e[0;34m"
export purple="\e[0;35m"
export grey="\e[0;37m"
export reset="\e[m"
export bold="\e[1m"
# Background
export On_Black='\033[40m' # Black
export On_Red='\033[41m' # Red
export On_Green='\033[42m' # Green
export On_Yellow='\033[43m' # Yellow
export On_Blue='\033[44m' # Blue
export On_Purple='\033[45m' # Purple
export On_Cyan='\033[46m' # Cyan
export On_White='\033[47m' # White
# Configuration for colored less output
export LESS='-R'
export LESSOPEN="| /usr/share/source-highlight/src-hilite-lesspipe.sh %s"
export LESS_TERMCAP_mb=$'\E[1;31m' # begin blink
export LESS_TERMCAP_md=$'\E[1;36m' # begin bold
export LESS_TERMCAP_me=$'\E[0m' # reset bold/blink
export LESS_TERMCAP_so=$'\E[01;44;33m' # begin reverse video
export LESS_TERMCAP_se=$'\E[0m' # reset reverse video
export LESS_TERMCAP_us=$'\E[1;32m' # begin underline
export LESS_TERMCAP_ue=$'\E[0m' # reset underline
# Enhanced log colorization without dependencies
colorize_log() {
# Common patterns
sed -E \
# Headers and separators
-e "s/^==> (.*) <==/$(printf '\033[1;35;40m')==> \1 <==$(printf '\033[0m')/g" \
-e "s/^([-=_]{3,}.*[-=_]{3,})/$(printf '\033[0;35m')\1$(printf '\033[0m')/g" \
-e "s/([|].*[|])/$(printf '\033[0;35m')\1$(printf '\033[0m')/g" \
# Log levels
-e "s/\[(DEBUG|TRACE)\]/$(printf '\033[0;32m')[\1]$(printf '\033[0m')/gi" \
-e "s/\[(INFO|NOTICE)\]/$(printf '\033[0;36m')[\1]$(printf '\033[0m')/gi" \
-e "s/\[(WARN(ING)?)\]/$(printf '\033[1;33m')[\1]$(printf '\033[0m')/gi" \
-e "s/\[(ERROR|FATAL|CRIT(ICAL)?)\]/$(printf '\033[1;31m')[\1]$(printf '\033[0m')/gi" \
-e "s/\[(UFW BLOCK|BLOCK(ED)?)\]/$(printf '\033[1;37;41m')[\1]$(printf '\033[0m')/gi" \
# Status and actions
-e "s/\b(error|fail(ed|ure)?|crit(ical)?|fatal)\b/$(printf '\033[1;31m')&$(printf '\033[0m')/gi" \
-e "s/\b(warn(ing)?)\b/$(printf '\033[1;33m')&$(printf '\033[0m')/gi" \
-e "s/\b(success(ful)?|succeed|completed)\b/$(printf '\033[1;32m')&$(printf '\033[0m')/gi" \
-e "s/\b(start(ed|ing)?|run(ning)?|done)\b/$(printf '\033[0;32m')&$(printf '\033[0m')/gi" \
-e "s/\b(stop(ped|ping)?|end(ed|ing)?|exit(ed|ing)?)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/gi" \
-e "s/\b(kill(ed|ing)?|terminat(e|ed|ing)|abort(ed)?)\b/$(printf '\033[1;31m')&$(printf '\033[0m')/gi" \
-e "s/\b(started|initialized|loaded|configured|enabled)\b/$(printf '\033[0;32m')&$(printf '\033[0m')/gi" \
-e "s/\b(stopped|disabled|unloaded|deconfigured|terminated)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/gi" \
# Security related
-e "s/\b(auth|login|user|root|admin|sudo)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
-e "s/\b(session opened|authenticated|granted)\b/$(printf '\033[0;32m')&$(printf '\033[0m')/gi" \
-e "s/\b(session closed|disconnected|logged out)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/gi" \
-e "s/\b(invalid|failed|denied|reject(ed)?)\b/$(printf '\033[0;31m')&$(printf '\033[0m')/gi" \
-e "s/\b(attack|hack|exploit|malicious|threat|intrusion|breach|vulnerability)\b/$(printf '\033[1;37;41m')&$(printf '\033[0m')/gi" \
-e "s/\b(unauthorized|forbidden|blocked|blacklisted|whitelisted)\b/$(printf '\033[1;31m')&$(printf '\033[0m')/gi" \
-e "s/\b(permission|access|authorization|authentication)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
# System operations
-e "s/\b(backup|restore|save|load|archive|snapshot)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
-e "s/\b(install(ed|ing)?|updat(e|ed|ing)|upgrade|config|setup|deploy(ed|ing)?)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
-e "s/\b(systemd|kernel|linux|ubuntu|debian|centos|fedora|redhat)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
-e "s/\b(read|write|execute|modify|create|delete|chmod|chown)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/gi" \
-e "s/\b(mount|umount|format|partition|filesystem)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
# Container and virtualization
-e "s/\b(docker|container|pod|volume|kubernetes|k8s|swarm|compose)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
-e "s/\b(vm|virtual|hypervisor|qemu|kvm|xen|vbox)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
# Network related
-e "s/\b(tcp|udp|icmp|http[s]?|ssh|ftp|dns|smtp|pop3|imap|ldap|ssl|tls)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
-e "s/\b(port|socket|connection|packet|protocol)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
-e "s/\b(IN|OUT|SRC|DST|PROTO|SPT|DPT|TTL|ID|WINDOW|MAC|LEN|SEQ|ACK|FLAGS)\b=/$(printf '\033[0;36m')\1=$(printf '\033[0m')/g" \
-e "s/\b([0-9]{1,3}\.){3}[0-9]{1,3}\b/$(printf '\033[1;34m')&$(printf '\033[0m')/g" \
-e "s/\b([0-9a-f]{2}:){5}[0-9a-f]{2}\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
-e "s/\b(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|TRACE|CONNECT)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/g" \
# Database related
-e "s/\b(nginx|apache|mysql|postgresql|mongodb|redis|elasticsearch)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
-e "s/\b(query|transaction|commit|rollback|index|table|database)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
# Performance and metrics
-e "s/\b(cpu|memory|disk|network|io|bandwidth|latency|throughput)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/gi" \
-e "s/\b([0-9]+(\.[0-9]+)?(ms|[TGMK]B|[TGMK]b|s|%|Hz|Mhz|Ghz))\b/$(printf '\033[0;33m')&$(printf '\033[0m')/g" \
-e "s/\b(timeout|expired|overflow|underflow|exceeded|limit)\b/$(printf '\033[0;31m')&$(printf '\033[0m')/gi" \
# Programming and debugging
-e "s/\b(0x[0-9a-fA-F]+)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/g" \
-e "s/\b(true|false|null|undefined|nil)\b/$(printf '\033[0;36m')&$(printf '\033[0m')/gi" \
-e "s/\b(exception|stacktrace|traceback|debug|breakpoint)\b/$(printf '\033[0;31m')&$(printf '\033[0m')/gi" \
-e "s/\b(function|method|class|object|variable|constant)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
# Time and dates
-e "s/\b([0-9]{4}-[0-9]{2}-[0-9]{2})[T ]([0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?([+-][0-9]{2}:?[0-9]{2})?)\b/$(printf '\033[0;34m')\1 \2$(printf '\033[0m')/g" \
-e "s/^([A-Za-z]{3}\s+[0-9]+\s+[0-9:]+)/$(printf '\033[0;34m')\1$(printf '\033[0m')/g" \
# URLs and paths
-e "s/(https?:\/\/[^\s]+)/$(printf '\033[4;34m')&$(printf '\033[0m')/g" \
-e "s/\b(\/[^\s]+)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/g" \
# Process and system
-e "s/\b(pid|process|thread|signal|fork|exec)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
-e "s/\b(daemon|service|init|systemd|cron|at)\b/$(printf '\033[0;35m')&$(printf '\033[0m')/gi" \
# Hardware related
-e "s/\b(cpu|gpu|ram|disk|nic|usb|pci|sata|nvme)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/gi" \
-e "s/\b(temperature|fan|power|voltage|current)\b/$(printf '\033[0;33m')&$(printf '\033[0m')/gi"
}
# Enhanced less and tail commands with automatic colorization
less_with_color() {
local file="$1"
# Check if the file is a log file (based on extension or path)
if [[ "$file" =~ \.(log|txt)$ ]] || [[ "$file" =~ ^/var/log/ ]] || [[ "$file" == "syslog" ]]; then
# If it's a compressed file
if [[ "$file" =~ \.gz$ ]]; then
zcat "$file" | colorize_log | less -R
else
cat "$file" | colorize_log | less -R
fi
else
# Use source-highlight for code files
less "$@"
fi
}
tail_with_color() {
# If -f option is present, add colorization
if [[ "$*" == *"-f"* ]]; then
tail "$@" | colorize_log
else
tail "$@"
fi
}
# Replace original commands with enhanced versions
alias less='less_with_color'
alias tail='tail_with_color'
# Function to detect distribution
detect_distribution() {
if [ -f /etc/os-release ]; then
. /etc/os-release
echo "$PRETTY_NAME"
elif [ -f /etc/redhat-release ]; then
cat /etc/redhat-release
elif [ -f /etc/debian_version ]; then
echo "Debian $(cat /etc/debian_version)"
elif [ -f /etc/lsb-release ]; then
. /etc/lsb-release
echo "$DISTRIB_DESCRIPTION"
else
echo "Unknown distribution"
fi
}
# Function to check for updates
check_updates() {
if command -v apt-get &> /dev/null; then
updates=$(apt-get -s upgrade | grep -c "^Inst")
security_updates=$(apt-get -s upgrade | grep -c "^Inst.*security")
if [ $updates -eq 0 ]; then
echo "${green}No updates available${reset}"
elif [ $updates -le 10 ]; then
echo "${yellow}$updates updates available${reset}"
else
echo "${red}$updates updates available${reset}"
fi
if [ $security_updates -gt 0 ]; then
echo "${red}$security_updates security updates available${reset}"
fi
elif command -v yum &> /dev/null; then
updates=$(yum check-update --quiet 2>/dev/null | grep -v "^$" | wc -l)
security_updates=$(yum updateinfo list security --quiet 2>/dev/null | grep -v "^$" | wc -l)
if [ $updates -eq 0 ]; then
echo "${green}No updates available${reset}"
elif [ $updates -le 10 ]; then
echo "${yellow}$updates updates available${reset}"
else
echo "${red}$updates updates available${reset}"
fi
if [ $security_updates -gt 0 ]; then
echo "${red}$security_updates security updates available${reset}"
fi
else
echo "${yellow}Unknown package manager${reset}"
fi
}
# MOTD
# Information gathering
motd() {
hostname=$(hostname)
distribution=$(detect_distribution)
updates_info=$(check_updates)
userconnected=$(who | grep -c pts)
usernames=$(who | grep pts | awk '{print $1}' | paste -sd " " -)
proc=$(nproc --all)
proc_120=$(($proc*120/100))
memtotal=$(cat /proc/meminfo | grep MemTotal | awk '{print $2}')
memavailable=$(cat /proc/meminfo | grep MemAvailable | awk '{print $2}')
memcached=$(cat /proc/meminfo | grep "^Cached:" | awk '{print $2}')
membuffers=$(cat /proc/meminfo | grep Buffers | awk '{print $2}')
memused=$((memtotal - memavailable))
memusedpercent=$((memused * 100 / memtotal))
if [ $memusedpercent -lt 90 ]; then
ramcolor=$green
elif [ $memusedpercent -lt 96 ]; then
ramcolor=$yellow
else
ramcolor=$red
fi
# Get swap information
swaptotal=$(cat /proc/meminfo | grep SwapTotal | awk '{print $2}')
swapfree=$(cat /proc/meminfo | grep SwapFree | awk '{print $2}')
if [ $swaptotal -gt 0 ]; then
swapused=$(($swaptotal-$swapfree))
swapusedpercent=$(($swapused*100/$swaptotal))
if [ $swapusedpercent -lt 50 ]; then
swapcolor=$green
elif [ $swapusedpercent -lt 80 ]; then
swapcolor=$yellow
else
swapcolor=$red
fi
fi
uptime=$(uptime -p 2> /dev/null)
uptime_s=$(awk -F '.' '{print $1}' /proc/uptime)
if [ $uptime_s -lt 86400 ]; then
uptcolor=$yellow
else
uptcolor=$green
fi
addrip=$(hostname -I | cut -d " " -f1)
public_ip=$(curl -s -f --connect-timeout 1 ifconfig.me)
read one five fifteen rest < /proc/loadavg
if (( $(echo "$one $proc" | awk '{print ($1 < $2)}') )); then
onecolor=$green
elif (( $(echo "$one $proc_120" | awk '{print ($1 < $2)}') )); then
onecolor=$yellow
else
onecolor=$red
fi
if (( $(echo "$five $proc" | awk '{print ($1 < $2)}') )); then
fivecolor=$green
elif (( $(echo "$five $proc_120" | awk '{print ($1 < $2)}') )); then
fivecolor=$yellow
else
fivecolor=$red
fi
if (( $(echo "$fifteen $proc" | awk '{print ($1 < $2)}') )); then
fifteencolor=$green
elif (( $(echo "$fifteen $proc_120" | awk '{print ($1 < $2)}') )); then
fifteencolor=$yellow
else
fifteencolor=$red
fi
# Function to generate progress bar
generate_progress_bar() {
local percent=$1
local width=20
local filled=$(($width * $percent / 100))
local empty=$(($width - $filled))
printf "["
printf "%${filled}s" | tr ' ' '='
printf "%${empty}s" | tr ' ' ' '
printf "] "
}
# Get storage information
while read -r line; do
if [[ $line =~ ^/dev/ ]]; then
mount=$(echo $line | awk '{print $6}')
size=$(echo $line | awk '{print $2}')
used=$(echo $line | awk '{print $3}')
avail=$(echo $line | awk '{print $4}')
usepercent=$(echo $line | awk '{print $5}' | sed 's/%//')
if [ $usepercent -lt 80 ]; then
diskcolor=$green
elif [ $usepercent -lt 90 ]; then
diskcolor=$yellow
else
diskcolor=$red
fi
# Calculate maximum length for alignment
mount_padded=$(printf "%-12s" "$mount")
size_padded=$(printf "%4s" "$size")
avail_padded=$(printf "%4s" "$avail")
usepercent_padded=$(printf "%3s" "$usepercent")
storage_info="$storage_info\n $mount_padded: ${diskcolor}$(generate_progress_bar $usepercent) ${usepercent_padded}%${reset} (${avail_padded} / ${size_padded})"
fi
done < <(df -h | grep -v "tmpfs\|devtmpfs\|snap")
# Check Docker presence
if command -v docker &> /dev/null; then
# Vérifier les droits Docker avec un timeout
if timeout 2 docker info &>/dev/null; then
total_containers=$(timeout 2 docker ps -a --format '{{.Status}}' | wc -l)
healthy_containers=$(timeout 2 docker ps -a --format '{{.Status}}' | grep -c "healthy")
running_containers=$(timeout 2 docker ps -a --format '{{.Status}}' | grep -c "Up" | grep -v "healthy")
unhealthy_containers=$(timeout 2 docker ps -a --format '{{.Status}}' | grep -c "unhealthy")
stopped_containers=$(timeout 2 docker ps -a --format '{{.Status}}' | grep -c "Exited")
docker_info=" Docker : ${blue}Present${reset} → ${blue}${running_containers} running${reset} (${green}${healthy_containers} healthy${reset}, ${red}${unhealthy_containers} unhealthy${reset}) - ${yellow}${stopped_containers} stopped${reset}"
else
docker_info=" Docker : ${yellow}Present (no permission)${reset}"
fi
fi
# Display MOTD
motd_content=$(cat /etc/motd /etc/motd.d/* 2>/dev/null)
if [ -n "$motd_content" ]; then
echo -e "\n$motd_content\n -------------------\n"
fi
echo -e "\n Hostname : ${blue}${bold}$(hostname)$purple${moreinfo}${reset}"
echo -e " Distribution : ${bold}$distribution${reset}"
echo -e " Updates : $updates_info"
echo -e " Connected users : ${bold}$userconnected$purple (${usernames})${reset}"
printf "\n Processors : $proc"
printf "\n"
printf " Load CPU : $onecolor$one (1min)$reset / $fivecolor$five (5min)$reset / $fifteencolor$fifteen (15min)$reset"
printf "\n"
printf " IP Address : $public_ip ($addrip)"
printf "\n"
printf " RAM : $(($memused/1024/1024))GB / $(($memtotal/1024/1024))GB ($ramcolor$memusedpercent%% used$reset) - Cache: $(($(($membuffers+$memcached))/1024/1024))GB"
printf "\n"
if [ $swaptotal -gt 0 ]; then
printf " SWAP : $(($swapfree/1024/1024))GB free / $(($swaptotal/1024/1024))GB ($swapcolor$swapusedpercent%% used$reset)"
else
printf " SWAP : ${yellow}disabled${reset}"
fi
printf "\n"
printf " Uptime : $uptcolor$uptime$reset"
printf "\n"
# Display storage information
echo -e "$storage_info"
printf "\n"
if [ -n "$docker_info" ]; then
printf "$docker_info"
else
printf " Docker : ${yellow}Absent${reset}"
fi
printf "\n"
printf "\n"
}
export -f motd
motd
# Family help
chelp() {
echo -e "\nAvailable commands:
${bold}System Information:${reset}
${bold}motd${reset} : Display welcome message with system information
${bold}benchmark${reset} : Run comprehensive server performance tests (CPU, RAM, Disk, Network)
${bold}checksec${reset} : Perform security audit and show recommendations
${bold}logwatch${reset} : Watch system logs in real-time with color highlighting
${bold}File Management:${reset}
${bold}extract${reset} : Extract any type of archive (tar, zip, rar, etc.)
${bold}compress${reset} : Compress files/directories (tar.gz, tar.bz2, zip)
${bold}findfile${reset} : Search for files with color highlighting
${bold}tree${reset} : Display directory structure in tree format
${bold}diskspace${reset} : Analyze disk usage and show largest files/directories
${bold}webshare${reset} : Start a web file sharing server with upload/download support
${bold}webshare_cleanup${reset} : Clean up webshare server and firewall rules
${bold}Editor Commands:${reset}
${bold}p / hp${reset} : Show / hide current path in prompt
${bold}vic${reset} : Vim with local vimrc /tmp/.vimrc_remote
${bold}System Commands:${reset}
${bold}start/stop/restart${reset} : Service management
${bold}status${reset} : Service status
${bold}enable/disable${reset} : Enable/disable services
${bold}reload${reset} : Reload service configuration
${bold}oomanalyser${reset} : Execute script to analyze out of memory events
${bold}Network Commands:${reset}
${bold}ips${reset} : Show all ips informations
${bold}ports${reset} : Show listening ports
${bold}myip${reset} : Show public IP
${bold}localip${reset} : Show local IP
${bold}Monitoring Commands:${reset}
${bold}topcpu${reset} : Show top 10 CPU processes
${bold}topmem${reset} : Show top 10 memory processes
${bold}df${reset} : Show disk usage (human readable)
${bold}du${reset} : Show directory usage (human readable)
${bold}free${reset} : Show memory usage (human readable)
${bold}Security Commands:${reset}
${bold}chmod${reset} : Change file permissions (verbose)
${bold}chown${reset} : Change file owner (verbose)
${bold}chgrp${reset} : Change file group (verbose)
${bold}Git Commands:${reset}
${bold}gs${reset} : Git status
${bold}ga${reset} : Git add
${bold}gc${reset} : Git commit
${bold}gp${reset} : Git push
${bold}gl${reset} : Git pull
${bold}gd${reset} : Git diff
${bold}Docker Commands:${reset}
${bold}dps${reset} : List running containers
${bold}dls${reset} : List all containers
${bold}dim${reset} : List images
${bold}dlog${reset} : Show container logs
${bold}dstop${reset} : Stop container
${bold}drm${reset} : Remove container
${bold}drmi${reset} : Remove image
"
}
export -f chelp
# Increase process priority with nice and ionice
if [ "$EUID" -eq 0 ]; then
renice -n -20 -p $$ >/dev/null
ionice -c 2 -n 0 -p $$ >/dev/null
fi
suroot() {
user=$(whoami)
sudo -E su -c "bash --rcfile /home/$user/.bashrc_remote"
}
export -f suroot
# Custom prompt
case "$(whoami)" in
root)
PS1_USER_COLOR="$red"
;;
l3)
PS1_USER_COLOR="$purple"
;;
*)
PS1_USER_COLOR="$green"
;;
esac
export PS1_USER_COLOR
export PS1="\[${PS1_USER_COLOR}\]\u\[${grey}\]@\[${blue}\]\h \[${grey}\]>\[${reset}\] "
p() {
export PS1="\[${PS1_USER_COLOR}\]\u\[${grey}\]@\[${blue}\]\h\[${yellow}\]:\w \[${grey}\]>\[${reset}\] "
}
export -f p
hp() {
export PS1="\[${PS1_USER_COLOR}\]\u\[${grey}\]@\[${blue}\]\h \[${grey}\]>\[${reset}\] "
}
export -f hp
bind '"\e[A": history-search-backward' # Up arrow to browse commands with similar start
bind '"\e[B": history-search-forward' # Down arrow to move forward in history
# Vim with custom vimrc
vic() {
$(which vim) -u /tmp/.vimrc_remote "$@"
}
export -f vic
oomanalyser() {
local tmpfile=$(mktemp)
local url="https://raw.githubusercontent.com/LukeShirnia/out-of-memory/3f8bdbc38f8139e228be0085960e190554148af3/oom-investigate.py"
local hash="1bdae43494d9ab115b565ff76bd0542b260017ad3ee1fd03d8c4cb929649d1ff"
curl "$url" --output "$tmpfile"
if [[ "$(sha256sum $tmpfile | awk '{print $1}')" == "$hash" ]]; then
chmod +x "$tmpfile"
"$tmpfile" "$@"
else
echo "Hash is not correct, exiting"
fi
rm "$tmpfile"
}
export -f oomanalyser
# ls color
alias ls='ls --color=auto -F'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias mkdir='mkdir -p'
# Service management aliases
if command -v systemctl &> /dev/null; then
alias start='sudo systemctl start'
alias stop='sudo systemctl stop'
alias restart='sudo systemctl restart'
alias status='systemctl status'
alias enable='sudo systemctl enable'
alias disable='sudo systemctl disable'
alias reload='sudo systemctl reload'
elif command -v service &> /dev/null; then
alias start='sudo service'
alias stop='sudo service'
alias restart='sudo service'
alias status='service'
alias reload='sudo service'
fi
# Network aliases
alias ports='netstat -tulanp'
alias myip='curl -s ifconfig.me'
alias localip='hostname -I | cut -d" " -f1'
# System monitoring aliases
alias topcpu='ps aux | sort -nrk 3,3 | head -n 10'
alias topmem='ps aux | sort -nrk 4,4 | head -n 10'
alias df='df -h'
alias du='du -h'
alias free='free -h'
# Security aliases
alias chmod='chmod -v'
alias chown='chown -v'
alias chgrp='chgrp -v'
# Git aliases
alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias gp='git push'
alias gl='git pull'
alias gd='git diff'
# Docker aliases
if command -v docker &> /dev/null; then
alias dps='docker ps'
alias dls='docker ps -a'
alias dim='docker images'
alias dlog='docker logs'
alias dstop='docker stop'
alias drm='docker rm'
alias drmi='docker rmi'
fi
# Progress bar function
progress_bar() {
local current=$1
local total=$2
local width=50
local percentage=$((current * 100 / total))
local completed=$((width * current / total))
local remaining=$((width - completed))
printf "\rProgress: ["
printf "%${completed}s" | tr " " "="
printf "%${remaining}s" | tr " " " "
printf "] %d%%" $percentage
}
# Memory formatting function
format_memory() {
local bytes=$1
if [ $bytes -gt 1073741824 ]; then # 1 GiB
echo "$(echo "scale=1; $bytes/1073741824" | bc) GiB"
elif [ $bytes -gt 1048576 ]; then # 1 MiB
echo "$(echo "scale=1; $bytes/1048576" | bc) MiB"
elif [ $bytes -gt 1024 ]; then # 1 KiB
echo "$(echo "scale=1; $bytes/1024" | bc) KiB"
else
echo "${bytes} B"
fi
}
# Server Benchmark Function
benchmark() {
# Check required packages
if ! check_requirements "benchmark"; then
return 1
fi
echo -e "\n${blue}🔍 Running Server Performance Tests${reset}\n"
# CPU Test
echo -e "${yellow}📊 CPU Performance Test${reset}"
echo -e "Testing CPU with simple calculation loop...\n"
local start_time=$(date +%s.%N)
local iterations=500
for i in $(seq 1 $iterations); do
echo "scale=500; 4*a(1)" | bc -l >/dev/null 2>&1
if [ $((i % 10)) -eq 0 ]; then
progress_bar $i $iterations
fi
done
local end_time=$(date +%s.%N)
local cpu_time=$(echo "$end_time - $start_time" | bc)
local cpu_score=$(echo "scale=2; $iterations / $cpu_time" | bc)
echo -e "\n\nCPU Results:"
echo -e "CPU Score: ${green}$cpu_score ops/s${reset}"
echo -e "\nCPU Info:"
grep "model name" /proc/cpuinfo | head -1
echo "CPU Cores: $(nproc)"
echo -e "Current CPU Load: $(uptime | awk -F'load average:' '{ print $2 }')\n"
# Memory Test
echo -e "${yellow}💾 Memory Information${reset}"
echo "Testing memory read/write speed..."
# Get total memory in MB for test sizing
local total_mb=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
# Use 25% of total memory for testing, minimum 1GB, maximum 8GB
local write_mb=$(( total_mb / 4 ))
if [ $write_mb -lt 1024 ]; then
write_mb=1024
elif [ $write_mb -gt 8192 ]; then
write_mb=8192
fi
# Test memory write speed with dd
local write_speed=0
local read_speed=0
# Create test file first
dd if=/dev/zero of=/dev/shm/test bs=1M count=$write_mb status=none
# Test write speed (3 iterations)
local write_total=0
local read_total=0
local test_iterations=3
echo "Testing write speed..."
for i in $(seq 1 $test_iterations); do
progress_bar $i $test_iterations
local result=$(dd if=/dev/zero of=/dev/shm/test bs=64k count=$(( write_mb * 16 )) conv=fdatasync 2>&1 | grep copied | awk '{print $(NF-1)}' | sed 's/,/./')
if [[ $result =~ ^[0-9.]+$ ]]; then
write_total=$(echo "$write_total + $result" | bc)
fi
done
write_speed=$(echo "scale=1; $write_total / $test_iterations" | bc)
echo -e "\n"
echo "Testing read speed..."
for i in $(seq 1 $test_iterations); do
progress_bar $i $test_iterations
local result=$(dd if=/dev/shm/test of=/dev/null bs=64k count=$(( write_mb * 16 )) 2>&1 | grep copied | awk '{print $(NF-1)}' | sed 's/,/./')
if [[ $result =~ ^[0-9.]+$ ]]; then
read_total=$(echo "$read_total + $result" | bc)
fi
done
read_speed=$(echo "scale=1; $read_total / $test_iterations" | bc)
echo -e "\n"
# Cleanup
rm -f /dev/shm/test
# Format speeds for display
local write_speed_display
local read_speed_display
if [ -n "$write_speed" ] && [ "$write_speed" != "0" ]; then
if [ $(echo "$write_speed > 1000" | bc -l) -eq 1 ]; then
write_speed_display="$(echo "scale=1; $write_speed/1000" | bc) GB/s"
else
write_speed_display="$write_speed MB/s"
fi
else
write_speed_display="N/A"
fi
if [ -n "$read_speed" ] && [ "$read_speed" != "0" ]; then
if [ $(echo "$read_speed > 1000" | bc -l) -eq 1 ]; then
read_speed_display="$(echo "scale=1; $read_speed/1000" | bc) GB/s"
else
read_speed_display="$read_speed MB/s"
fi
else
read_speed_display="N/A"
fi
echo -e "\nMemory Results:"
echo -e "Memory Write Speed: ${green}$write_speed_display${reset}"
echo -e "Memory Read Speed: ${green}$read_speed_display${reset}"
echo -e "\nMemory Status:"
# Get memory info in MB to avoid arithmetic errors
local total_mb=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
local free_mb=$(awk '/MemFree/ {print int($2/1024)}' /proc/meminfo)
local available_mb=$(awk '/MemAvailable/ {print int($2/1024)}' /proc/meminfo)
local buffers_mb=$(awk '/Buffers/ {print int($2/1024)}' /proc/meminfo)
local cached_mb=$(awk '/^Cached/ {print int($2/1024)}' /proc/meminfo)
local used_mb=$((total_mb - free_mb - buffers_mb - cached_mb))
# Format memory values in GiB for display with proper precision
local total_gib=$(echo "scale=1; $total_mb/1024" | bc)
local used_gib=$(echo "scale=1; $used_mb/1024" | bc)
local buffers_cached_gib=$(echo "scale=1; ($buffers_mb + $cached_mb)/1024" | bc)
local available_gib=$(echo "scale=1; $available_mb/1024" | bc)
# Calculate percentages using MB values to avoid floating point errors
local mem_usage=$(echo "scale=1; ($used_mb * 100) / $total_mb" | bc)
local mem_buffers_cached=$(echo "scale=1; (($buffers_mb + $cached_mb) * 100) / $total_mb" | bc)
# Ensure we don't display negative values for used memory
if [ $(echo "$used_gib < 0" | bc) -eq 1 ]; then
used_gib="0.0"
mem_usage="0.0"
fi
# Add proper spacing for single digit values
if [ $(echo "$total_gib < 10" | bc) -eq 1 ]; then
total_gib=" $total_gib"
fi
if [ $(echo "$used_gib < 10" | bc) -eq 1 ]; then
used_gib=" $used_gib"
fi
if [ $(echo "$buffers_cached_gib < 10" | bc) -eq 1 ]; then
buffers_cached_gib=" $buffers_cached_gib"
fi
if [ $(echo "$available_gib < 10" | bc) -eq 1 ]; then
available_gib=" $available_gib"
fi
echo -e "Total Memory: ${green}${total_gib} GiB${reset}"
echo -e "Used Memory: ${green}${used_gib} GiB${reset} (${mem_usage}%)"
echo -e "Cache/Buffers: ${green}${buffers_cached_gib} GiB${reset} (${mem_buffers_cached}%)"
echo -e "Available: ${green}${available_gib} GiB${reset}"
# Disk Test
echo -e "\n${yellow}💿 Disk Performance Test${reset}"
echo "Testing disk write speed..."
# Try to clear cache if we have sudo rights
if [ -w "/proc/sys/vm/drop_caches" ]; then
sync && echo 3 > /proc/sys/vm/drop_caches
fi
# Create a temporary directory for disk tests
local test_dir=$(mktemp -d)
local test_file="$test_dir/test_file"
# Write test with smaller file and multiple iterations for better average
local write_total=0
local read_total=0
local test_iterations=3
local file_size=512 # MB
echo -e "Running disk write test ($test_iterations iterations)..."
for i in $(seq 1 $test_iterations); do
progress_bar $i $test_iterations
local write_result=$(dd if=/dev/zero of="$test_file" bs=1M count=$file_size conv=fdatasync 2>&1 | grep -o "[0-9.]*" | tail -1)
write_total=$(echo "$write_total + $write_result" | bc)
done
local write_score=$(echo "scale=1; $write_total / $test_iterations" | bc)
echo -e "\n"
echo "Testing disk read speed..."
for i in $(seq 1 $test_iterations); do
progress_bar $i $test_iterations
local read_result=$(dd if="$test_file" of=/dev/null bs=1M count=$file_size 2>&1 | grep -o "[0-9.]*" | tail -1)
read_total=$(echo "$read_total + $read_result" | bc)
done
local read_score=$(echo "scale=1; $read_total / $test_iterations" | bc)
echo -e "\n"
# IOPS Test
echo "Testing disk IOPS..."
if command -v fio >/dev/null 2>&1; then
local test_dir=$(mktemp -d)
local test_file="$test_dir/fio_test"
# Sequential Write IOPS
echo "Testing sequential write IOPS..."
local seq_write_iops=$(fio --name=seq_write --filename=$test_file --rw=write --bs=4k --size=1G --numjobs=1 --direct=1 --group_reporting --runtime=10 --time_based --output-format=terse | awk -F';' '{print int($49)}')
# Sequential Read IOPS
echo "Testing sequential read IOPS..."
local seq_read_iops=$(fio --name=seq_read --filename=$test_file --rw=read --bs=4k --size=1G --numjobs=1 --direct=1 --group_reporting --runtime=10 --time_based --output-format=terse | awk -F';' '{print int($8)}')
# Random Write IOPS
echo "Testing random write IOPS..."
local random_write_iops=$(fio --name=rand_write --filename=$test_file --rw=randwrite --bs=4k --size=1G --numjobs=1 --direct=1 --group_reporting --runtime=10 --time_based --output-format=terse | awk -F';' '{print int($49)}')
# Random Read IOPS
echo "Testing random read IOPS..."
local random_read_iops=$(fio --name=rand_read --filename=$test_file --rw=randread --bs=4k --size=1G --numjobs=1 --direct=1 --group_reporting --runtime=10 --time_based --output-format=terse | awk -F';' '{print int($8)}')
# Cleanup
rm -rf "$test_dir"
echo -e "\nIOPS Results:"
echo -e "Sequential Write: ${green}${seq_write_iops:-0} IOPS${reset}"
echo -e "Sequential Read: ${green}${seq_read_iops:-0} IOPS${reset}"
echo -e "Random Write: ${green}${random_write_iops:-0} IOPS${reset}"
echo -e "Random Read: ${green}${random_read_iops:-0} IOPS${reset}"
else
echo -e "\n${yellow}IOPS test skipped: fio not installed${reset}"
echo -e "To install fio:"
echo -e " - Debian/Ubuntu: ${grey}sudo apt install fio${reset}"
echo -e " - RHEL/CentOS: ${grey}sudo yum install fio${reset}"
echo -e " - Alpine: ${grey}apk add fio${reset}"
seq_write_iops=0
seq_read_iops=0
random_write_iops=0