13.第六章 shell腳本編程


第七部分

1、每隔3秒鍾到系統上獲取已經登錄的用戶信息;如果發現用戶hacker登錄,則將登錄時間和主機記錄於日志/var/log/login.log中,並退出腳本

[root@centos8 ~]# vim until_hacker.sh
#!/bin/bash
# 
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-14
#FileName:         until_hacker.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
until false;do
    if who |grep "^hacker\>"&>/dev/null;then
        who|grep "^hacker\>">/var/log/login.log
        break
    fi
    sleep 3
done
[root@centos8 ~]# useradd hacker 
[root@centos8 ~]# echo 123456 |passwd --stdin hacker
Changing password for user hacker.
passwd: all authentication tokens updated successfully.
[root@centos7 ~]# ssh hacker@10.0.0.8
The authenticity of host '10.0.0.8 (10.0.0.8)' can't be established.
ECDSA key fingerprint is SHA256:fUCdE0Lsxgab+roZ/EFe+btNS2VNOZYabFbNk7JfS98.
ECDSA key fingerprint is MD5:49:ed:65:c6:e9:74:3a:a3:1b:8f:0f:e5:57:8d:87:26.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.8' (ECDSA) to the list of known hosts.
hacker@10.0.0.8's password: 
[hacker@centos8 ~]$ 
[root@centos8 ~]# cat /var/log/login.log 
hacker   pts/2        2020-12-14 20:11 (10.0.0.7)

2、隨機生成10以內的數字,實現猜字游戲,提示比較大或小,相等則退出

[root@centos8 ~]# vim guess.sh
#Date:              2020-12-14
#FileName:         guess.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
NUM=$[RANDOM%10]
while read -p "輸入0-9之間的數字: " input ;do
    if grep '^[[:digit:]]*$' <<< "$input" ;then
        if [ $input -eq $NUM ];then
            echo "恭喜你猜對了!"
            break
        elif [ $input -gt $NUM ];then
            echo "數字太大,重新猜!"
        else
            echo "數字太小,重新猜!"
        fi
    else
        echo "請輸入數字"
    fi
done 
[root@centos8 ~]# bash guess.sh 
輸入0-9之間的數字: 5
5
數字太小,重新猜!
輸入0-9之間的數字: 6
6
數字太小,重新猜!
數字太小,重新猜!
輸入0-9之間的數字: 9
9
數字太大,重新猜!
輸入0-9之間的數字: 8
8
恭喜你猜對了!

3、用文件名做為參數,統計所有參數文件的總行數

[root@centos8 ~]# vim until_file.sh
#!/bin/bash
# 
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-14
#FileName:         until_file.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
if [ $# -eq 0 ];then
    echo "Please input file path"
else
    until [ -z "$1" ];do
        echo "統計文件: $1"
        echo "文件總行數: `wc -l $1|cut -d " " -f1`"
        echo
        shift
    done
echo "finish"
fi   
[root@centos8 ~]# bash until_file.sh 
Please input file path
[root@centos8 ~]# bash until_file.sh /etc/init.d/functions 
統計文件: /etc/init.d/functions
文件總行數: 709

finish

[root@centos8 ~]# bash until_file.sh /etc/issue /etc/fstab /etc/yum.repos.d/base.repo 
統計文件: /etc/issue
文件總行數: 3

統計文件: /etc/fstab
文件總行數: 15

統計文件: /etc/yum.repos.d/base.repo
文件總行數: 53

finish

4、用二個以上的數字為參數,顯示其中的最大值和最小值

[root@centos8 ~]# vim while_maxmin.sh
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-14
#FileName:         while_maxmin.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
max=$1
min=$1
while [ $# -gt 0 ];do
    if [ $1 -lt $min ];then
        min=$1
    fi
    if [ $1 -gt $max ];then
        max=$1
    fi
    shift
done
echo "maxnum is $max"
echo "minnum is $min"  
[root@centos8 ~]# bash while_maxmin.sh 10 9
maxnum is 10
minnum is 9

第八部分

1、編寫函數,實現OS的版本判斷

[root@centos8 ~]# vim os_version.sh
#!/bin/bash
#
#********************************************************************
#Author:		    zhanghui
#QQ: 			    19661891
#Date: 			    2021-01-04
#FileName:		    os_version.sh
#URL: 			    www.neteagles.cn
#Description:		The test script
#Copyright (C): 	2021 All rights reserved
#********************************************************************
os_version(){
    cat /etc/redhat-release 2> /dev/null || awk -F'"' '/PRETTY_NAME=/{print $2}' /etc/os-release
}
os_version  
:wq
[root@centos8-4 ~]# bash os_version.sh 
CentOS Linux release 8.3.2011
root@ubuntu2004:~# bash os_version.sh 
Ubuntu 20.04.1 LTS


root@ubuntu1804:~# vim os_version2.sh
#!/bin/bash
#
#********************************************************************
#Author:		    zhanghui
#QQ: 			    19661891
#Date: 			    2021-01-04
#FileName:		    os_version2.sh
#URL: 			    www.neteagles.cn
#Description:		The test script
#Copyright (C): 	2021 All rights reserved
#********************************************************************
os_version(){
    sed -rn 's#^.* ([0-9]+)\..*#\1#p' /etc/redhat-release 2> /dev/null || awk -F'=|"|[.]' '/VERSION=/{print $3}' /etc/os-release
}
os_version
:wq
root@ubuntu1804:~# bash os_version2.sh
20
[root@centos8-4 ~]# bash os_version2.sh 
8

2、編寫函數,實現取出當前系統eth0的IP地址

[root@centos8 ~]# vim eth0_ip.sh
#!/bin/bash
# 
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-16
#FileName:         eth0_ip.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
get_ip(){
    ip addr |sed -rn '/global/s#(.*inet )([0-9].*)(/.*)#\2#p'
}
get_ip 
:wq
[root@centos8 ~]# bash eth0_ip.sh 
10.0.0.8

3、編寫函數,實現打印綠色OK和紅色FAILED

[root@centos8 ~]# vim ok_failed.sh
#!/bin/bash
# 
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-16
#FileName:         ok_failed.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
. /etc/init.d/functions
action "success!" true
action "failed!" false
[root@centos8 ~]# bash ok_failed.sh 
success!                                                   [  OK  ]
failed!                                                    [FAILED]

4、編寫函數,實現判斷是否無位置參數,如無參數,提示錯誤

[root@centos8 ~]# vim parameter.sh
#!/bin/bash
# 
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-16
#FileName:         parameter.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
args () {
    if [ $# -eq 0 ];then
    . /etc/init.d/functions
    action "fail...you must input a parameter" false
    fi
}
args $1 
[root@centos8 ~]# bash parameter.sh 
fail...you must input a parameter                          [FAILED]
[root@centos8 ~]# bash parameter.sh 0

5、編寫函數,實現兩個數字做為參數,返回最大值

[root@centos8 ~]# vim return_max.sh
#!/bin/bash
# 
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-16
#FileName:         return_max.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
return_max(){
    until [ $# -eq 0 ];do
    if [ $1 -lt $2 ] ;then
        echo "$2"
        break
    else
        echo "$1"
        break                                       
    fi
    done
}
return_max $1 $2
:wq
[root@centos8 ~]# bash return_max.sh
[root@centos8 ~]# bash return_max.sh 10 6
10
[root@centos8 ~]# bash return_max.sh 100 94
100

6、編寫服務腳本/root/bin/testsrv.sh,完成如下要求

(1)腳本可接受參數:start,stop,restart,status

(2)如果參數非此四者之一,提示使用格式后報錯退出

(3)如果start:則創建/var/lock/subsys/SCRIPT_NAME,並顯示“啟動成功”

​ 考慮:如果事先已經啟動過一次,該如何處理?

(4)如果stop:則刪除/var/lock/subsys/SCRIPT_NAME,並顯示“停止完成”

​ 考慮:如果事先已經停止過了,該如何處理?

(5)如果restart,則先stop,再start

​ 考慮:如果本來沒有start,該如何處理?

(6)如果status,則如果/var/lock/subsys/SCRIPT_NAME文件存在,則顯示“SCRIPT_NAME is running...”,如果/var/lock/subsys/SCRIPT_NAME文件不存在,則顯示“SCRIPT_NAME is stopped...”

(7)在所有模式下禁止啟動該服務,可用chkconfig和service命令管理

​ 說明:SCRIPT_NAME為當前腳本名

[root@centos8 ~]# cat /root/bin/testsrv.sh 
#!/bin/bash
#chkconfig: - 96 3
#description: the service script

. /etc/init.d/functions
start(){
        touch /var/lock/subsys/testsrv
        action "Starting testsrv"
        sleep 3
} 
stop(){
        rm -f /var/lock/subsys/testsrv
        action "Shutting down testsrv"
}
restart(){
        stop
        start
}
status(){
        if [ -e /var/lock/subsys/testsrv ];then
            echo "testsrv is runing..."
        else
            echo "testsrv is stopped"
        fi
}

case $1 in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    restart
    ;;
status)
    status
    ;;
*)
    echo "Usage: /etc/init.d/testsrv {start|stop|restart|status}"
    ;; 
esac

7、編寫腳本/root/bin/copycmd.sh

(1)提示用戶輸入一個可執行命令名稱

(2)獲取此命令所依賴到的所有庫文件列表

(3)賦值命令至某目標目錄(例如/mnt/sysroot)下的對應路徑下

​ 如:/bin/bash ==> /mnt/sysroot/bin/bash

​ /usr/bin/passwd ==> /mnt/sysroot/usr/bin/passwd

(4)復制此命令依賴到的所有庫文件至目標目錄下的對應路徑下: 如:/lib64/ld-linux-x86-64.so.2 ==> /mnt/sysroot/lib64/ld-linux-x86-64.so.2

(5)每次復制完成一個命令后,不要退出,而是提示用戶鍵入新的要復制的命令,並重復完成上述功能;直到用戶輸入 quit退出

[root@centos8 ~]# vim copycmd.sh 
#!/bin/bash
#
#********************************************************************
#Author:		    zhanghui
#QQ: 			    19661891
#Date: 			    2020-12-16
#FileName:		    copycmd.sh
#URL: 			    www.neteagles.cn
#Description:		The test script
#Copyright (C): 	2020 All rights reserved
#********************************************************************
read -p "please input a excute cmd(eg:cat|bash|quit):" command
[ -a /mnt/sysroot ]||mkdir /mnt/sysroot &>/dev/null
cpdir () {
      cmd=`which --skip-alias $command`
      if [ -f  /mnt/sysroot$cmd ];then
           echo "the $cmd has been cp before"
       else
       local dir=`dirname $cmd`
         mkdir -p /mnt/sysroot$dir
         cp $cmd /mnt/sysroot$cmd
                echo "cp $cmd finished"
          fi
}
cplib () {
          cmd=`which --skip-alias $command`
          ldd $cmd |egrep -o "/lib64.* "|while read i;do
            if  [ ! -f /mnt/sysroot$i ];then
            local dir=`dirname $i`
             mkdir -p /mnt/sysroot$dir
                cp $i /mnt/sysroot$i     
                    echo "cp $i  finished"
            else
                   echo "$i has been cp before"
             fi
            done
}
type $command&>/dev/null||{ echo the command is not exsit;exit 100; }
until [ $command == quit ];do
type $command&>/dev/null||{ echo the command is not exsit;exit 100; }
cpdir
cplib
read -p "please input new excute cmd(eg:cat|bash|quit):" command
cmd=`which --skip-alias $command`
done
:wq
[root@centos8 ~]# bash copycmd.sh 
please input a excute cmd(eg:cat|bash|quit):ls
cp /usr/bin/ls finished
cp /lib64/libselinux.so.1  finished
cp /lib64/libcap.so.2  finished
cp /lib64/libc.so.6  finished
cp /lib64/libpcre2-8.so.0  finished
cp /lib64/libdl.so.2  finished
cp /lib64/ld-linux-x86-64.so.2  finished
cp /lib64/libpthread.so.0  finished
please input new excute cmd(eg:cat|bash|quit):cd
cp /usr/bin/cd finished
please input new excute cmd(eg:cat|bash|quit):pwd
cp /usr/bin/pwd finished
/lib64/libc.so.6 has been cp before
/lib64/ld-linux-x86-64.so.2 has been cp before
please input new excute cmd(eg:cat|bash|quit):rm
cp /usr/bin/rm finished
/lib64/libc.so.6 has been cp before
/lib64/ld-linux-x86-64.so.2 has been cp before
please input new excute cmd(eg:cat|bash|quit):quit
which: no quit in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)
[root@centos8 ~]# tree /mnt/sysroot/
/mnt/sysroot/
├── lib64
│   ├── ld-linux-x86-64.so.2
│   ├── libcap.so.2
│   ├── libc.so.6
│   ├── libdl.so.2
│   ├── libpcre2-8.so.0
│   ├── libpthread.so.0
│   └── libselinux.so.1
└── usr
    └── bin
        ├── cd
        ├── ls
        ├── pwd
        └── rm

3 directories, 11 files

8、裴波那契數列又稱黃金分割數列,因數學家列昂納多·裴波那契以兔子繁殖為例子而引入,故又稱為“兔子數列”,指的是這樣一個數列:0、1、1、2、3、5、8、13、21、34、...,裴波那契數列以如下被以遞歸的方法定義:F (0) =0,F (1) =1,F (n) =F(n-1)+F(n-2) (n≥2),利用函數,求n階裴波那契數列

[root@centos8 ~]# vim fibonacci.sh 
#!/bin/bash
# 
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-16
#FileName:         fibonacci.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
fibonacci(){
    tmp=$1
    if [ $tmp -le 2 ];then
        echo 1
    else        
        F1=`fibonacci $[tmp-1]`
        F2=`fibonacci $[tmp-2]`
        echo $[F1+F2]
    fi
}
fibonacci $1 
[root@centos8 ~]# bash fibonacci.sh 10
55
[root@centos8 ~]# bash fibonacci.sh 15
610

9、漢諾塔(又稱河內塔)問題是源於印度一個古老傳說。大梵天創造世界的時候做了三根金剛石柱子,在一根柱子上從下往上按照大小順序摞着64片黃金圓盤。大梵天命令婆羅門把圓盤從下面開始按大小順序重新擺放在另一根柱子上。並且規定,在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動一個圓盤,利用函數,實現N片盤的漢諾塔的移動步驟

[root@centos8 ~]# cat hanoi.sh 
#!/bin/bash
#
#********************************************************************
#Author:		    zhanghui
#QQ: 			    19661891
#Date: 			    2020-12-16
#FileName:		    hanoi.sh
#URL: 			    www.neteagles.cn
#Description:		The test script
#Copyright (C): 	2020 All rights reserved
#********************************************************************
hanoi(){
    local tmp=$1
    if [ $tmp -eq 1 ] ;then
        let i++
        echo "step:$i move $2--->$4"      #move A to C
    else
        hanoi $[$1-1] $2 $4 $3 # move the n-1 plate to B
        let i++
        echo "step:$i move $2--->$4" #move the bigest  plate to C
        hanoi $[$1-1] $3 $2 $4  #move the n-1 plate to C
    fi
}

trap 'echo Ctrl+C is not work ,Please type q or quit to exit' 2
while : ;do
    read -p "please input a number:" tmp
    declare -i i=0
    if [[ $tmp =~ ^[Qq]([Uu][Ii][Tt])?$ ]] ;then
        break 
    elif [[ $tmp =~ ^[0-9]+$ ]] ;then
        hanoi $tmp A B C
    else
        echo "Error:please input a positive number!"
    fi
    unset tmp
done
:wq
[root@centos8 ~]# bash hanoi.sh 
please input a number:5
step:1 move A--->C
step:2 move A--->B
step:3 move C--->B
step:4 move A--->C
step:5 move B--->A
step:6 move B--->C
step:7 move A--->C
step:8 move A--->B
step:9 move C--->B
step:10 move C--->A
step:11 move B--->A
step:12 move C--->B
step:13 move A--->C
step:14 move A--->B
step:15 move C--->B
step:16 move A--->C
step:17 move B--->A
step:18 move B--->C
step:19 move A--->C
step:20 move B--->A
step:21 move C--->B
step:22 move C--->A
step:23 move B--->A
step:24 move B--->C
step:25 move A--->C
step:26 move A--->B
step:27 move C--->B
step:28 move A--->C
step:29 move B--->A
step:30 move B--->C
step:31 move A--->C
please input a number:q

第九部分

1、輸入若干個數值存入數組中,采用冒泡算法進行升序或降序排序

#升序排序
root@ubuntu2004:~# vim maopao.sh
        if [ $L == 0 ];then
            echo 沒有數字。
        elif [ $L == 1 ];then
            echo 只有一個數字,無需排序。
        else
            for i in `seq $[L-1]`;do
                for j in `seq $i $[L-1]`;do
                    MIN=${NUMS[$i-1]}
                    if [ $MIN -gt ${NUMS[$j]} ];then
                        NUMS[$i-1]=${NUMS[$j]}
                        NUMS[$j]=$MIN
                    fi
                done
            done
            echo 從小到大排序:${NUMS[*]}
            break
        fi
    elif [[ $N =~ ^[0-9]+$ ]];then
        NUMS[$i]=$N
        echo 已輸入數字:${NUMS[*]}
        echo 個數: ${#NUMS[*]}
        let i++
    else
        echo "您輸入的不是數字,請重新輸入。"
        continue
    fi
done  
:wq
root@ubuntu2004:~# bash maopao.sh 
請輸入一個數字( e 結束輸入,q 退出程序 ):11
已輸入數字:11
個數: 1
請輸入一個數字( e 結束輸入,q 退出程序 ):587
已輸入數字:11 587
個數: 2
請輸入一個數字( e 結束輸入,q 退出程序 ):674
已輸入數字:11 587 674
個數: 3
請輸入一個數字( e 結束輸入,q 退出程序 ):2223
已輸入數字:11 587 674 2223
個數: 4
請輸入一個數字( e 結束輸入,q 退出程序 ):1568
已輸入數字:11 587 674 2223 1568
個數: 5
請輸入一個數字( e 結束輸入,q 退出程序 ):489413
已輸入數字:11 587 674 2223 1568 489413
個數: 6
請輸入一個數字( e 結束輸入,q 退出程序 ):e
從小到大排序:11 587 674 1568 2223 489413

#降序排序
root@ubuntu2004:~# vim maopao2.sh
        if [ $L == 0 ];then
            echo 沒有數字。
        elif [ $L == 1 ];then
            echo 只有一個數字,無需排序。
        else
            for i in `seq $[L-1]`;do
                for j in `seq $i $[L-1]`;do
                    MAX=${NUMS[$i-1]}
                    if [ $MAX -lt ${NUMS[$j]} ];then
                        NUMS[$i-1]=${NUMS[$j]}
                        NUMS[$j]=$MAX
                    fi
                done
            done
            echo 從大到小排序:${NUMS[*]}
            break
        fi
    elif [[ $N =~ ^[0-9]+$ ]];then
        NUMS[$i]=$N
        echo 已輸入數字:${NUMS[*]}
        echo 個數: ${#NUMS[*]}
        let i++
    else
        echo "您輸入的不是數字,請重新輸入。"
        continue
    fi
done 
:wq
root@ubuntu2004:~# bash maopao2.sh 
請輸入一個數字( e 結束輸入,q 退出程序 ):55
已輸入數字:55
個數: 1
請輸入一個數字( e 結束輸入,q 退出程序 ):86
已輸入數字:55 86
個數: 2
請輸入一個數字( e 結束輸入,q 退出程序 ):77896
已輸入數字:55 86 77896
個數: 3
請輸入一個數字( e 結束輸入,q 退出程序 ):1548
已輸入數字:55 86 77896 1548
個數: 4
請輸入一個數字( e 結束輸入,q 退出程序 ):1848
已輸入數字:55 86 77896 1548 1848
個數: 5
請輸入一個數字( e 結束輸入,q 退出程序 ):e
從大到小排序:77896 1848 1548 86 55

2、將下圖所示,實現轉置矩陣matrix.sh

1 2 3           1 4 7

​4 5 6 	==>	2 5 8

7 8 9           3 6 9
root@ubuntu2004:~# vim matrix.sh
#********************************************************************
#Author:            zhanghui
#QQ:                19661891
#Date:              2020-12-16
#FileName:         matrix.sh
#URL:               www.neteagles.cn
#Description:      The test script
#Copyright (C):     2020 All rights reserved
#********************************************************************
declare -a matrix
echo 原始:
for i in `seq 3`
do
    for j in `seq 3`
    do
        matrix[$i$j]=$[3*(i-1)+j]
        echo -n ${matrix[$i$j]} ''
    done
    echo
done
echo -e "\n轉換:"
for i in `seq 3`
do
    for j in `seq $i`
    do
        x=${matrix[$i$j]}
        matrix[$i$j]=${matrix[$j$i]}
        matrix[$j$i]=$x
     done
done
for i in `seq 3`
do
    for j in `seq 3`
    do
        echo -n ${matrix[$i$j]} ''
    done
    echo
done 
:wq
root@ubuntu2004:~# bash matrix.sh 
原始:
1 2 3 
4 5 6 
7 8 9 

轉換:
1 4 7 
2 5 8 
3 6 9 

3、打印楊輝三角形

root@ubuntu2004:~# cat yanghui.sh 
#!/bin/bash
#
#********************************************************************
#Author:		    zhanghui
#QQ: 			    19661891
#Date: 			    2020-12-16
#FileName:		    yanghui.sh
#URL: 			    www.neteagles.cn
#Description:		The test script
#Copyright (C): 	2020 All rights reserved
#********************************************************************
yanghui(){
    tmp=$1
    i=0
    while [ $i -ne `expr $tmp + 1` ];do
        if [ $i -eq $tmp ]||[ $i -eq 0 ];then
            echo -n 1  
        else
            echo -n $(expr $2 + $3)  
            shift
        fi
        echo -n " "  
        i=`expr $i + 1`
    done
}
if [ $# -ne 1 ];then
   read -p  "enter the Max number:"  COUNT
else
    COUNT=$1
fi
i=0
while [ $i -ne  $COUNT ];do
    tmp=(`yanghui $i ${tmp[*]}`)
    echo ${tmp[*]}  
    i=`expr $i + 1`
done 
:wq
root@ubuntu2004:~# bash yanghui.sh 
enter the Max number:5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
root@ubuntu2004:~# bash yanghui.sh 
enter the Max number:10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

第十部分

[root@centos8 ~]# cat reset_v4.sh
#!/bin/bash
#
#******************************************************************************
#Author:        zhanghui
#QQ:            19661891
#Date:          2021-09-05
#FileName:      reset_v4.sh
#URL:           www.cnblogs.com/neteagles
#Description:   reset for centos 6/7/8 & ubuntu 18.04/20.04
#Copyright (C): 2021 All rights reserved
#******************************************************************************
COLOR="echo -e \\033[01;31m"
END='\033[0m'

os(){
    if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release;then
        rpm -q redhat-lsb-core &> /dev/null || { ${COLOR}"安裝lsb_release工具"${END};yum -y install  redhat-lsb-core &> /dev/null; }
    fi
    OS_ID=`lsb_release -is`
    OS_RELEASE=`lsb_release -rs`
    OS_RELEASE_VERSION=`lsb_release -rs |awk -F'.' '{print $1}'`
    OS_CODENAME=`lsb_release -cs`
}

disable_selinux(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        if [ `getenforce` == "Enforcing" ];then
            sed -ri.bak 's/^(SELINUX=).*/\1disabled/' /etc/selinux/config
            ${COLOR}"${OS_ID} ${OS_RELEASE} SELinux已禁用,請重新啟動系統后才能生效!"${END}
        else
            ${COLOR}"${OS_ID} ${OS_RELEASE} SELinux已被禁用,不用設置!"${END}
        fi
    else
        ${COLOR}"${OS_ID} ${OS_RELEASE} SELinux默認沒有安裝,不用設置!"${END}
    fi
}

disable_firewall(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        rpm -q firewalld &> /dev/null && { systemctl disable --now firewalld &> /dev/null; ${COLOR}"${OS_ID} ${OS_RELEASE} Firewall防火牆已關閉!"${END}; } || ${COLOR}"${OS_ID} ${OS_RELEASE} 沒有firewall防火牆服務,不用關閉!"${END}
    else
        dpkg -s ufw &> /dev/null && { systemctl disable --now ufw &> /dev/null; ${COLOR}"${OS_ID} ${OS_RELEASE} ufw防火牆已關閉!"${END}; } || ${COLOR}"${OS_ID} ${OS_RELEASE}  沒有ufw防火牆服務,不用關閉!"${END}
    fi
}

optimization_sshd(){
    sed -i.bak -e 's/#UseDNS no/UseDNS no/' -e 's/GSSAPIAuthentication yes/GSSAPIAuthentication no/' /etc/ssh/sshd_config
    if [ ${OS_RELEASE_VERSION} == "6" ] &> /dev/null;then
        service sshd restart
    else
        systemctl restart sshd
    fi
    ${COLOR}"${OS_ID} ${OS_RELEASE} SSH已優化完成!"${END}
}

set_centos_alias(){
    cat >>~/.bashrc <<-EOF
alias cdnet="cd /etc/sysconfig/network-scripts"
alias vie0="vim /etc/sysconfig/network-scripts/ifcfg-eth0"
alias vie1="vim /etc/sysconfig/network-scripts/ifcfg-eth1"
alias scandisk="echo '- - -' > /sys/class/scsi_host/host0/scan;echo '- - -' > /sys/class/scsi_host/host1/scan;echo '- - -' > /sys/class/scsi_host/host2/scan"
EOF
    ${COLOR}"${OS_ID} ${OS_RELEASE} 系統別名已設置成功,請重新登陸后生效!"${END}
}

set_ubuntu_alias(){
    cat >>~/.bashrc <<-EOF
alias cdnet="cd /etc/netplan"
alias scandisk="echo '- - -' > /sys/class/scsi_host/host0/scan;echo '- - -' > /sys/class/scsi_host/host1/scan;echo '- - -' > /sys/class/scsi_host/host2/scan"
EOF
    ${COLOR}"${OS_ID} ${OS_RELEASE} 系統別名已設置成功,請重新登陸后生效!"${END}
}

set_alias(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        set_centos_alias
    else
        set_ubuntu_alias
    fi
}

set_vimrc(){
    read -p "請輸入作者名:" AUTHOR
    read -p "請輸入QQ號:" QQ
    read -p "請輸入網址:" V_URL
    cat >~/.vimrc <<-EOF  
set ts=4
set expandtab
set ignorecase
set cursorline
set autoindent
autocmd BufNewFile *.sh exec ":call SetTitle()"
func SetTitle()
    if expand("%:e") == 'sh'
    call setline(1,"#!/bin/bash")
    call setline(2,"#")
    call setline(3,"#**********************************************************************************************")
    call setline(4,"#Author:        ${AUTHOR}")
    call setline(5,"#QQ:            ${QQ}")
    call setline(6,"#Date:          ".strftime("%Y-%m-%d"))
    call setline(7,"#FileName:      ".expand("%"))
    call setline(8,"#URL:           ${V_URL}")
    call setline(9,"#Description:   The test script")
    call setline(10,"#Copyright (C): ".strftime("%Y")." All rights reserved")
    call setline(11,"#*********************************************************************************************")
    call setline(12,"")
    endif
endfunc
autocmd BufNewFile * normal G
EOF
    ${COLOR}"${OS_ID} ${OS_RELEASE} vimrc設置完成,請重新系統啟動才能生效!"${END}
}

aliyun(){
    URL=mirrors.aliyun.com
}

huawei(){
    URL=repo.huaweicloud.com
}

tencent(){
    URL=mirrors.cloud.tencent.com
}

tuna(){
    URL=mirrors.tuna.tsinghua.edu.cn
}

netease(){
    URL=mirrors.163.com
}

sohu(){
    URL=mirrors.sohu.com
}

fedora(){
    URL=archives.fedoraproject.org
}

set_yum_centos8(){
    [ -d /etc/yum.repos.d/backup ] || mkdir /etc/yum.repos.d/backup
    mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup
    cat > /etc/yum.repos.d/base.repo <<-EOF
[BaseOS]
name=BaseOS
baseurl=https://${URL}/centos/\$releasever/BaseOS/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial

[AppStream]
name=AppStream
baseurl=https://${URL}/centos/\$releasever/AppStream/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial

[extras]
name=extras
baseurl=https://${URL}/centos/\$releasever/extras/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
enabled=1

[centosplus]
name=centosplus
baseurl=https://${URL}/centos/\$releasever/centosplus/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial

[PowerTools]
name=PowerTools
baseurl=https://${URL}/centos/8/PowerTools/x86_64/os/
gpgcheck=1
etpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
EOF
    dnf clean all &> /dev/null
    dnf repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} YUM源設置完成!"${END}
}

set_epel_centos8(){
    cat > /etc/yum.repos.d/epel.repo <<-EOF
[EPEL]
name=EPEL
baseurl=https://${URL}/epel/\$releasever/Everything/\$basearch/
gpgcheck=1
gpgkey=https://${URL}/epel/RPM-GPG-KEY-EPEL-\$releasever
EOF
    dnf clean all &> /dev/null
    dnf repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} EPEL源設置完成!"${END}
}

set_epel_2_centos8(){
    cat > /etc/yum.repos.d/epel.repo <<-EOF
[EPEL]
name=EPEL
baseurl=https://${URL}/fedora-epel/\$releasever/Everything/\$basearch/
gpgcheck=1
gpgkey=https://${URL}/fedora-epel/RPM-GPG-KEY-EPEL-\$releasever
EOF
    dnf clean all &> /dev/null
    dnf repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} EPEL源設置完成!"${END}
}

set_yum_centos7(){
    [ -d /etc/yum.repos.d/backup ] || mkdir /etc/yum.repos.d/backup
    mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup
    cat > /etc/yum.repos.d/base.repo <<-EOF
[base]
name=base
baseurl=https://${URL}/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[extras]
name=extras
baseurl=https://${URL}/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[updates]
name=updates
baseurl=https://${URL}/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[centosplus]
name=centosplus
baseurl=https://${URL}/centos/\$releasever/centosplus/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
EOF
    yum clean all &> /dev/null
    yum repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} YUM源設置完成!"${END}
}

set_epel_centos7(){
    cat > /etc/yum.repos.d/epel.repo <<-EOF
[epel]
name=epel
baseurl=https://${URL}/epel/\$releasever/\$basearch/
gpgcheck=1
gpgkey=https://${URL}/epel/RPM-GPG-KEY-EPEL-\$releasever
EOF
    yum clean all &> /dev/null
    yum repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} EPEL源設置完成!"${END}
}

set_epel_2_centos7(){
    cat > /etc/yum.repos.d/epel.repo <<-EOF
[epel]
name=epel
baseurl=https://${URL}/fedora-epel/\$releasever/\$basearch/
gpgcheck=1
gpgkey=https://${URL}/fedora-epel/RPM-GPG-KEY-EPEL-\$releasever
EOF
    yum clean all &> /dev/null
    yum repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} EPEL源設置完成!"${END}
}

set_yum_centos6(){
    [ -d /etc/yum.repos.d/backup ] || mkdir /etc/yum.repos.d/backup
    mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup
    cat > /etc/yum.repos.d/base.repo <<-EOF
[base]
name=base
baseurl=https://${URL}/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[extras]
name=extras
baseurl=https://${URL}/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[updates]
name=updates
baseurl=https://${URL}/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[centosplus]
name=centosplus
baseurl=https://${URL}/centos/\$releasever/centosplus/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
EOF
    yum clean all &> /dev/null
    yum repolist  &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} YUM源設置完成!"${END}
}

set_yum_2_centos6(){
    [ -d /etc/yum.repos.d/backup ] || mkdir /etc/yum.repos.d/backup
    mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup
    cat > /etc/yum.repos.d/base.repo <<-EOF
[base]
name=base
baseurl=https://${URL}/centos-vault/\$releasever.10/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[extras]
name=extras
baseurl=https://${URL}/centos-vault/\$releasever.10/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[updates]
name=updates
baseurl=https://${URL}/centos-vault/\$releasever.10/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever

[centosplus]
name=centosplus
baseurl=https://${URL}/centos-vault/\$releasever.10/centosplus/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
EOF
    yum clean all &> /dev/null
    yum repolist  &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} YUM源設置完成!"${END}
}

set_epel_centos6(){
    cat > /etc/yum.repos.d/epel.repo <<-EOF
[epel]
name=epel
baseurl=https://${URL}/epel/\$releasever/\$basearch/
gpgcheck=1
gpgkey=https://${URL}/epel/RPM-GPG-KEY-EPEL-\$releasever
EOF
    yum clean all &> /dev/null
    yum repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} EPEL源設置完成!"${END}
}

set_epel_2_centos6(){
    cat > /etc/yum.repos.d/epel.repo <<-EOF
[epel]
name=epel
baseurl=https://${URL}/pub/archive/epel/\$releasever/\$basearch/
gpgcheck=1
gpgkey=https://$(tencent)/epel/RPM-GPG-KEY-EPEL-\$releasever
EOF
    yum clean all &> /dev/null
    yum repolist &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} EPEL源設置完成!"${END}
}

centos8_base_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)阿里鏡像源
2)華為鏡像源
3)騰訊鏡像源
4)清華鏡像源
5)網易鏡像源
6)搜狐鏡像源
7)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-7)" NUM
        case ${NUM} in
        1)
            aliyun
            set_yum_centos8
            ;;
        2)
            huawei
            set_yum_centos8
            ;;
        3)
            tencent
            set_yum_centos8
            ;;
        4)
            tuna
            set_yum_centos8
            ;;
        5)
            netease
            set_yum_centos8
            ;;
        6)
            sohu
            set_yum_centos8
            ;;
        7)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-7)!"${END}
            ;;
        esac
    done
}

centos7_base_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)阿里鏡像源
2)華為鏡像源
3)騰訊鏡像源
4)清華鏡像源
5)網易鏡像源
6)搜狐鏡像源
7)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-7)" NUM
        case ${NUM} in
        1)
            aliyun
            set_yum_centos7
            ;;
        2)
            huawei
            set_yum_centos7
            ;;
        3)
            tencent
            set_yum_centos7
            ;;
        4)
            tuna
            set_yum_centos7
            ;;
        5)
            netease
            set_yum_centos7
            ;;
        6)
            sohu
            set_yum_centos7
            ;;
        7)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-7)!"${END}
            ;;
        esac
    done
}

centos6_base_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)騰訊鏡像源
2)搜狐鏡像源
3)阿里鏡像源
4)清華鏡像源
5)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-5)" NUM
        case ${NUM} in
        1)
            tencent
            set_yum_centos6
            ;;
        2)
            sohu
            set_yum_centos6
            ;;
        3)
            aliyun
            set_yum_2_centos6
            ;;
        4)
            tuna
            set_yum_2_centos6
            ;;
        5)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-5)!"${END}
            ;;
        esac
    done
}

centos8_epel_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)阿里鏡像源
2)華為鏡像源
3)騰訊鏡像源
4)清華鏡像源
5)搜狐鏡像源
6)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-6)" NUM
        case ${NUM} in
        1)
            aliyun
            set_epel_centos8
            ;;
        2)
            huawei
            set_epel_centos8
            ;;
        3)
            tencent
            set_epel_centos8
            ;;
        4)
            tuna
            set_epel_centos8
            ;;
        5)
            sohu
            set_epel_2_centos8
            ;;
        6)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-6)!"${END}
            ;;
        esac
    done
}

centos7_epel_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)阿里鏡像源
2)華為鏡像源
3)騰訊鏡像源
4)清華鏡像源
5)搜狐鏡像源
6)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-6)" NUM
        case ${NUM} in
        1)
            aliyun
            set_epel_centos7
            ;;
        2)
            huawei
            set_epel_centos7
            ;;
        3)
            tencent
            set_epel_centos7
            ;;
        4)
            tuna
            set_epel_centos7
            ;;
        5)
            sohu
            set_epel_2_centos7
            ;;
        6)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-6)!"${END}
            ;;
        esac
    done
}

centos6_epel_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)騰訊鏡像源
2)Fedora鏡像源
3)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-3)" NUM
        case ${NUM} in
        1)
            tencent
            set_epel_centos6
            ;;
        2)
            fedora
            set_epel_2_centos6
            ;;
        3)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-3)!"${END}
            ;;
        esac
    done
}

centos_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)base倉庫
2)EPEL倉庫
3)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-3)" NUM
        case ${NUM} in
        1)
            if [ ${OS_RELEASE_VERSION} == "8" ] &> /dev/null;then
                centos8_base_menu
            elif [ ${OS_RELEASE_VERSION} == "7" ] &> /dev/null;then
                centos7_base_menu
            else
                centos6_base_menu
            fi
            ;;
        2)
            if [ ${OS_RELEASE_VERSION} == "8" ] &> /dev/null;then
                centos8_epel_menu
            elif [ ${OS_RELEASE_VERSION} == "7" ] &> /dev/null;then
                centos7_epel_menu
            else
                centos6_epel_menu
            fi
            ;;
        3)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-3)!"${END}
            ;;
        esac
    done
}

set_apt(){
    mv /etc/apt/sources.list /etc/apt/sources.list.bak
    cat > /etc/apt/sources.list <<-EOF
deb http://${URL}/ubuntu/ ${OS_CODENAME} main restricted universe multiverse
deb-src http://${URL}/ubuntu/ ${OS_CODENAME} main restricted universe multiverse

deb http://${URL}/ubuntu/ ${OS_CODENAME}-security main restricted universe multiverse
deb-src http://${URL}/ubuntu/ ${OS_CODENAME}-security main restricted universe multiverse

deb http://${URL}/ubuntu/ ${OS_CODENAME}-updates main restricted universe multiverse
deb-src http://${URL}/ubuntu/ ${OS_CODENAME}-updates main restricted universe multiverse

deb http://${URL}/ubuntu/ ${OS_CODENAME}-proposed main restricted universe multiverse
deb-src http://${URL}/ubuntu/ ${OS_CODENAME}-proposed main restricted universe multiverse

deb http://${URL}/ubuntu/ ${OS_CODENAME}-backports main restricted universe multiverse
deb-src http://${URL}/ubuntu/ ${OS_CODENAME}-backports main restricted universe multiverse
EOF
    apt update
    ${COLOR}"${OS_ID} ${OS_RELEASE} APT源設置完成!"${END}
}

apt_menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)阿里鏡像源
2)華為鏡像源
3)騰訊鏡像源
4)清華鏡像源
5)網易鏡像源
6)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入鏡像源編號(1-6)" NUM
        case ${NUM} in
        1)
            aliyun
            set_apt
            ;;
        2)
            huawei
            set_apt
            ;;
        3)
            tencent
            set_apt
            ;;
        4)
            tuna
            set_apt
            ;;
        5)
            netease
            set_apt
            ;;
        6)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-6)!"${END}
            ;;
        esac
    done
}

set_package_repository(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        centos_menu
    else
        apt_menu
    fi
}

centos_minimal_install(){
    ${COLOR}'開始安裝“Minimal安裝建議安裝軟件包”,請稍等......'${END}
    yum -y install gcc make autoconf gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel zlib-devel vim lrzsz tree tmux lsof tcpdump wget net-tools iotop bc bzip2 zip unzip nfs-utils man-pages &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} Minimal安裝建議安裝軟件包已安裝完成!"${END}
}

ubuntu_minimal_install(){
    ${COLOR}'開始安裝“Minimal安裝建議安裝軟件包”,請稍等......'${END}
    apt -y install iproute2 ntpdate tcpdump telnet traceroute nfs-kernel-server nfs-common lrzsz tree openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev gcc openssh-server iotop unzip zip
    ${COLOR}"${OS_ID} ${OS_RELEASE} Minimal安裝建議安裝軟件包已安裝完成!"${END}
}

minimal_install(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        centos_minimal_install
    else
        ubuntu_minimal_install
    fi
}

set_mail(){                                                                                                 
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        rpm -q mailx &> /dev/null || yum -y install mailx &> /dev/null
        read -p "請輸入郵箱地址:" MAIL
        read -p "請輸入郵箱授權碼:" AUTH
        SMTP=`echo ${MAIL} |awk -F"@" '{print $2}'`
        cat >~/.mailrc <<-EOF
set from=${MAIL}
set smtp=smtp.${SMTP}
set smtp-auth-user=${MAIL}
set smtp-auth-password=${AUTH}
set smtp-auth=login
set ssl-verify=ignore
EOF
    else
        dpkg -s mailutils &> /dev/null || apt -y install mailutils
    fi
    ${COLOR}"${OS_ID} ${OS_RELEASE} 郵件設置完成,請重新登錄后才能生效!"${END}
}

set_sshd_port(){
    disable_selinux
    disable_firewall
    read -p "請輸入端口號:" PORT
    sed -i 's/#Port 22/Port '${PORT}'/' /etc/ssh/sshd_config
    ${COLOR}"${OS_ID} ${OS_RELEASE} 更改SSH端口號已完成,請重啟系統后生效!"${END}
}

set_centos_eth(){
    ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
    #修改網卡名稱配置文件
    sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@ net.ifnames=0"@' /etc/default/grub
    grub2-mkconfig -o /boot/grub2/grub.cfg >& /dev/null

    #修改網卡文件名
    mv /etc/sysconfig/network-scripts/ifcfg-${ETHNAME} /etc/sysconfig/network-scripts/ifcfg-eth0
    ${COLOR}"${OS_ID} ${OS_RELEASE} 網卡名已修改成功,請重新啟動系統后才能生效!"${END}
}

set_ubuntu_eth(){
    #修改網卡名稱配置文件
    sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@ net.ifnames=0"@' /etc/default/grub
    grub-mkconfig -o /boot/grub/grub.cfg >& /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} 網卡名已修改成功,請重新啟動系統后才能生效!"${END}
}

set_eth(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        if [ ${OS_RELEASE_VERSION} == 6 ];then
            ${COLOR}"${OS_ID} ${OS_RELEASE} 不用修改網卡名"${END}
        else
            set_centos_eth
        fi
    else
        set_ubuntu_eth
    fi
}

check_ip(){
    local IP=$1
    VALID_CHECK=$(echo ${IP}|awk -F. '$1<=255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
    if echo ${IP}|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" >/dev/null; then
        if [ ${VALID_CHECK} == "yes" ]; then
            echo "IP ${IP}  available!"
            return 0
        else
            echo "IP ${IP} not available!"
            return 1
        fi
    else
        echo "IP format error!"
        return 1
    fi
}

set_centos_ip(){
    while true; do
        read -p "請輸入IP地址:"  IP
        check_ip ${IP}
        [ $? -eq 0 ] && break
    done
	read -p "請輸入子網掩碼位數:"  C_PREFIX
    while true; do
        read -p "請輸入網關地址:"  GATEWAY
        check_ip ${GATEWAY}
        [ $? -eq 0 ] && break
    done
    cat > /etc/sysconfig/network-scripts/ifcfg-eth0 <<-EOF
DEVICE=eth0
NAME=eth0
BOOTPROTO=none
ONBOOT=yes
IPADDR=${IP}
PREFIX=${C_PREFIX}
GATEWAY=${GATEWAY}
DNS1=223.5.5.5
DNS2=180.76.76.76
EOF
    ${COLOR}"${OS_ID} ${OS_RELEASE} IP地址和網關地址已修改成功,請重新啟動系統后生效!"${END}
}

set_ubuntu_ip(){
    while true; do
        read -p "請輸入IP地址:"  IP
        check_ip ${IP}
        [ $? -eq 0 ] && break
    done
	read -p "請輸入子網掩碼位數:"  U_PREFIX
    while true; do
        read -p "請輸入網關地址:"  GATEWAY
        check_ip ${GATEWAY}
        [ $? -eq 0 ] && break
    done
    cat > /etc/netplan/01-netcfg.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      addresses: [${IP}/${U_PREFIX}] 
      gateway4: ${GATEWAY}
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
    ${COLOR}"${OS_ID} ${OS_RELEASE} IP地址和網關地址已修改成功,請重新啟動系統后生效!"${END}
}

set_ip(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        set_centos_ip
    else
        set_ubuntu_ip
    fi
}

set_hostname_all(){
    read -p "請輸入主機名:"  HOST
    hostnamectl set-hostname ${HOST}
    ${COLOR}"${OS_ID} ${OS_RELEASE} 主機名設置成功,請重新登錄生效!"${END}
}

set_hostname6(){
    read -p "請輸入主機名:"  HOST
    sed -i.bak -r '/^HOSTNAME/s#^(HOSTNAME=).*#\1'${HOST}'#' /etc/sysconfig/network
    ${COLOR}"${OS_ID} ${OS_RELEASE} 主機名設置成功,請重新登錄生效!"${END}
}

set_hostname(){
    if [ ${OS_RELEASE_VERSION} == 6 ] &> /dev/null;then
        set_hostname6
    else
        set_hostname_all
    fi
}

red(){
    P_COLOR=31
}

green(){
    P_COLOR=32
}

yellow(){
    P_COLOR=33
}

blue(){
    P_COLOR=34
}

violet(){
    P_COLOR=35
}

cyan_blue(){
    P_COLOR=36
}

random_color(){
    P_COLOR="$[RANDOM%7+31]"
}

centos_ps1(){
    C_PS1=`echo "PS1='\[\e[1;${P_COLOR}m\][\u@\h \W]\\$ \[\e[0m\]'" > /etc/profile.d/env.sh`
}

set_centos_ps1(){
    TIPS="${COLOR}${OS_ID} ${OS_RELEASE} PS1已設置完成,請重新登錄生效!${END}"
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)31 紅色
2)32 綠色
3)33 黃色
4)34 藍色
5)35 紫色
6)36 青色
7)隨機顏色
8)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入顏色編號(1-8)" NUM
        case ${NUM} in
        1)
            red
            centos_ps1
            ${TIPS}
            ;;
        2)
            green
            centos_ps1
            ${TIPS}
            ;;
        3)
            yellow
            centos_ps1
            ${TIPS}
            ;;
        4)
            blue
            centos_ps1
            ${TIPS}
            ;;
        5)
            violet
            centos_ps1
            ${TIPS}
            ;;
        6)
            cyan_blue
            centos_ps1
            ${TIPS}
            ;;
        7)
            random_color
            centos_ps1
            ${TIPS}
            ;;
        8)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-9)!"${END}
            ;;
        esac
    done
}

ubuntu_ps1(){
    U_PS1=`echo "PS1='\[\e[1;${P_COLOR}m\]${debian_chroot:+($debian_chroot)}\u@\h:\W\\$ \[\e[0m\]'" >> ~/.bashrc`
}

unsetps1(){
    CURRENTPS1SET=`awk -F"=" '/^PS1/{print $1}' ~/.bashrc | head -1`
    if [ ${CURRENTPS1SET} == "PS1" ] &> /dev/null;then
        sed -i "/^PS1.*/d" ~/.bashrc
        ${COLOR}已清空PS1設置,請重新設置!${END}
    else
        ${COLOR}沒有設置PS1,請直接設置!${END}
    fi
}

set_ubuntu_ps1(){
    TIPS="${COLOR}${OS_ID} ${OS_RELEASE} PS1已設置完成,請重新登錄生效!${END}"
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
1)31 紅色
2)32 綠色
3)33 黃色
4)34 藍色
5)35 紫色
6)36 青色
7)隨機顏色
8)清空PS1設置
9)退出
EOF
        echo -e '\E[0m'

        read -p "請輸入顏色編號(1-9)" NUM
        case ${NUM} in
        1)
            red
            ubuntu_ps1
            ${TIPS}
            ;;
        2)
            green
            ubuntu_ps1
            ${TIPS}
            ;;
        3)
            yellow
            ubuntu_ps1
            ${TIPS}
            ;;
        4)
            blue
            ubuntu_ps1
            ${TIPS}
            ;;
        5)
            violet
            ubuntu_ps1
            ${TIPS}
            ;;
        6)
            cyan_blue
            ubuntu_ps1
            ${TIPS}
            ;;
        7)
            random_color
            ubuntu_ps1
            ${TIPS}
            ;;
        8)
            unsetps1 
            ;;
        9)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-9)!"${END}
            ;;
        esac
    done
}

set_ps1(){
    if [ ${OS_ID} == "CentOS" ] &> /dev/null;then
        set_centos_ps1
    else
        set_ubuntu_ps1
    fi
}

set_swap(){
    sed -ri 's/.*swap.*/#&/' /etc/fstab
    swapoff -a
    ${COLOR}"${OS_ID} ${OS_RELEASE} 禁用swap成功!"${END}
}

set_kernel(){
    cat > /etc/sysctl.conf <<-EOF
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 1

# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0

# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1

# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.
net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0

# Controls the default maxmimum size of a mesage queue
kernel.msgmnb = 65536

# # Controls the maximum size of a message, in bytes
kernel.msgmax = 65536

# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736

# # Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296

# TCP kernel paramater
net.ipv4.tcp_mem = 786432 1048576 1572864
net.ipv4.tcp_rmem = 4096        87380   4194304
net.ipv4.tcp_wmem = 4096        16384   4194304
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1

# socket buffer
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 20480
net.core.optmem_max = 81920


# TCP conn
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_retries1 = 3
net.ipv4.tcp_retries2 = 15

# tcp conn reuse
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_timestamps = 0

net.ipv4.tcp_max_tw_buckets = 20000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syncookies = 1

# keepalive conn
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.ip_local_port_range = 10001    65000

# swap
vm.overcommit_memory = 0
vm.swappiness = 10

#net.ipv4.conf.eth1.rp_filter = 0
#net.ipv4.conf.lo.arp_ignore = 1
#net.ipv4.conf.lo.arp_announce = 2
#net.ipv4.conf.all.arp_ignore = 1
#net.ipv4.conf.all.arp_announce = 2
EOF
    sysctl -p &> /dev/null
    ${COLOR}"${OS_ID} ${OS_RELEASE} 優化內核參數成功!"${END}
}

set_limits(){
    cat >> /etc/security/limits.conf <<-EOF
root     soft   core     unlimited
root     hard   core     unlimited
root     soft   nproc    1000000
root     hard   nproc    1000000
root     soft   nofile   1000000
root     hard   nofile   1000000
root     soft   memlock  32000
root     hard   memlock  32000
root     soft   msgqueue 8192000
root     hard   msgqueue 8192000
EOF
    ${COLOR}"${OS_ID} ${OS_RELEASE} 優化資源限制參數成功!"${END}
}

set_root_login(){
    PASSWORD=123456
    echo ${PASSWORD} |sudo -S sed -ri 's@#(PermitRootLogin )prohibit-password@\1yes@' /etc/ssh/sshd_config
    sudo systemctl restart sshd
    sudo -S passwd root <<-EOF
${PASSWORD}
${PASSWORD}
EOF
    ${COLOR}"${OS_ID} ${OS_RELEASE} root用戶登錄已設置完成,請重新登錄后生效!"${END}
}

ubuntu_remove(){
    apt purge ufw lxd lxd-client lxcfs liblxc-common
    ${COLOR}"${OS_ID} ${OS_RELEASE} 無用軟件包卸載完成!"${END}
}

menu(){
    while true;do
        echo -e "\E[$[RANDOM%7+31];1m"
        cat <<-EOF
*********************************************************
*                    初始化腳本菜單                     *
* 1.禁用SELinux              12.修改IP地址和網關地址    *
* 2.關閉防火牆               13.設置主機名              *
* 3.優化SSH                  14.設置PS1(請進入選擇顏色) *
* 4.設置系統別名             15.禁用SWAP                *
* 5.1-4全設置                16.優化內核參數            *
* 6.設置vimrc配置文件        17.優化資源限制參數        *
* 7.設置軟件包倉庫           18.Ubuntu設置root用戶登錄  *
* 8.Minimal安裝建議安裝軟件  19.Ubuntu卸載無用軟件包    *
* 9.安裝郵件服務並配置郵件   20.重啟系統                *
* 10.更改SSH端口號           21.退出                    *
* 11.修改網卡名                                         *
*********************************************************
EOF
        echo -e '\E[0m'

        read -p "請選擇相應的編號(1-21): " choice
        case ${choice} in
        1)
            disable_selinux
            ;;
        2)
            disable_firewall
            ;;
        3)
            optimization_sshd
            ;;
        4)
            set_alias
            ;;
        5)
            disable_selinux
            disable_firewall
            optimization_sshd
            set_alias
            ;;
        6)
            set_vimrc
            ;;
        7)
            set_package_repository
            ;;
        8)
            minimal_install
            ;;
        9)
            set_mail
            ;;
        10)
            set_sshd_port
            ;;
        11)
            set_eth
            ;;
        12)
            set_ip
            ;;
        13)
            set_hostname
            ;;
        14)
            set_ps1
            ;;
        15)
            set_swap
            ;;
        16)
            set_kernel
            ;;
        17)
            set_limits
            ;;
        18)
            set_root_login
            ;;
        19)
            ubuntu_remove
            ;;
        20)
            reboot
            ;;
        21)
            break
            ;;
        *)
            ${COLOR}"輸入錯誤,請輸入正確的數字(1-21)!"${END}
            ;;
        esac
    done
}

main(){
    os
    menu
}

main


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM