最小化安裝Linux系統初始化腳本

来源:https://www.cnblogs.com/waluna/archive/2023/08/21/init-linux.html
-Advertisement-
Play Games

[toc] # 最小化安裝Linux系統初始化腳本 **註:此腳本適用於centos 7/8、Ubuntu1804,具體需要根據實際情況進行測試調整。** 此腳本包含的功能: 1. 允許 root 用戶使用 ssh 登錄 2. 關閉 selinux 3. 關閉防火牆 4. 設置 ps1 5. 設置默 ...


目錄

最小化安裝Linux系統初始化腳本

註:此腳本適用於centos 7/8、Ubuntu1804,具體需要根據實際情況進行測試調整。

此腳本包含的功能:

  1. 允許 root 用戶使用 ssh 登錄
  2. 關閉 selinux
  3. 關閉防火牆
  4. 設置 ps1
  5. 設置預設編輯器為 vim
  6. 自定義 vim
  7. 自定義歷史命令
  8. 修改內核參數
  9. 設置資源限制
  10. 修改軟體源
  11. 安裝常用包
  12. 設置時間同步
  13. 修改網卡為傳統命令格式
  14. 設置IP地址等
[root@centos8 ~]# cat init_v1.sh
#!/bin/bash
#
#**************************************************
#Author:                Xan_Yum
#QQ:                    7993167
#Email:                 [email protected]
#Version:               1.0
#Date:                  2021-11-03
#FileName:              init_v1.sh
#Description:           system init
#URL:                   https://blog.waluna.top
#Copyroght (C):         2021 ALL rights reserved
#**************************************************

OS=`awk -F'"' '/PRETTY_NAME/{print $2}' /etc/os-release|tr ' ' '-'`

#1
set_ssh () {
    if [[ $OS == Ubuntu-18.04* ]];then
        sed -i.bak '/#PermitRootLogin/a PermitRootLogin yes' /etc/ssh/sshd_config
        systemctl restart sshd
    fi
    echo -e "\e[32;1mPermit root login set complete\e[0m"
}

#2
disable_selinux () {
    if [[ $OS == CentOS* ]];then
        sed -i.bak 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
    fi
    echo -e "\e[32;1mSElinux already disabled,Restart to take effect\e[0m"

}

#3
disbale_firewall () {
    systemctl disable --now firewalld &> /dev/null
    echo -e "\e[32;1mFirewall already disabled\e[0m"
}

#4
set_ps1 () {
    if [[ $OS == CentOS* ]];then
        echo "PS1='\[\e[1;36m\][\u@\h \W]\\$ \[\e[0m\]'" >> /etc/profile.d/env.sh
        . /etc/profile.d/env.sh
    elif [[ $OS == Ubuntu* ]];then
        echo 'PS1="\[\e[1;32m\][${debian_chroot:+($debian_chroot)}\u@\h \w]\\$ \[\e[0m\]"' >> .bashrc
        . .bashrc
    fi
    echo -e "\e[32;1mPS1 already modify,Please login again\e[0m"

}

#5
set_default_text_editor_vim () {
    echo "export EDITOR=vim" >> /etc/profile.d/env.sh
    . /etc/profile.d/env.sh
    echo -e "\e[32;1mdefault_text_editor already modify vim,Please login again\e[0m"
}

#6
set_vim () {
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:                Xan_Yum")
    call setline(5,"#QQ:                    7993167")
    call setline(6,"#Email:                 [email protected]")
    call setline(7,"#Version:               1.0")
    call setline(8,"#Date:                  ".strftime("%Y-%m-%d"))
    call setline(9,"#FileName:              ".expand("%"))
    call setline(10,"#Description:           The test script")
    call setline(11,"#URL:                   https://blog.waluna.top")
    call setline(12,"#Copyroght (C):         ".strftime("%Y")." ALL rights reserved")
    call setline(13,"#**************************************************")
    endif
endfunc
autocmd BufNewFile * normal G
EOF
    echo -e "\e[32;1mVim already modify\e[0m"
}

#7
set_history () {
    echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >> /etc/profile.d/env.sh
    echo -e "\e[32;1mHistory modify\e[0m"
}

#8
modify_kernel_parameters () {
    mv /etc/sysctl.conf{,.bak}
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
# 表示是否打開TCP同步標簽(syncookie),內核必須打開了CONFIG_SYN_COOKIES項進行編譯,同步標簽可以防止一個套接字在有過多試圖連接到達時引起過載。	
net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.
# net.bridge.bridge-nf-call-arptables:是否在arptables的FORWARD中過濾網橋的ARP包
# net.bridge.bridge-nf-call-ip6tables:是否在ip6tables鏈中過濾IPv6包
# net.bridge.bridge-nf-call-iptables:是否在iptables鏈中過濾IPv4包
# net.bridge.bridge-nf-filter-vlan-tagged:是否在iptables/arptables中過濾打了vlan標簽的包

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 = 1
net.ipv4.tcp_fin_timeout = 1

net.ipv4.tcp_max_tw_buckets = 20000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_timestamps = 1 #?
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
    echo -e "\e[32;1mKernel parameters modify complete\e[0m"
}

#9
modify_resource_limits () {
cat >> /etc/security/limits.conf <<EOF

*	-	core		unlimited
*	-	nproc		1000000
*	-	nofile		1000000
*	-	memlock		32000
*	-	msgqueue	8192000
root    -       core            unlimited
root    -       nproc           1000000
root    -       nofile          1000000
root    -       memlock         32000
root    -       msgqueue        8192000
EOF
    echo -e "\e[32;1mResource limits modify complete\e[0m"
}

#10
set_software_source () {
    if [[ $OS == CentOS-Linux-7* ]];then
        mkdir /etc/yum.repos.d/backup && mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup
        curl -o /etc/yum.repos.d/Centos-7.repo https://mirrors.aliyun.com/repo/Centos-7.repo
        curl -o /etc/yum.repos.d/epel-7.repo https://mirrors.aliyun.com/repo/epel-7.repo
        yum clean all && yum makecache
    elif [[ $OS == CentOS-Linux-8* ]];then
        mkdir /etc/yum.repos.d/backup && mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup
        curl -o /etc/yum.repos.d/Centos-8.repo https://mirrors.aliyun.com/repo/Centos-8.repo
        yum clean all && yum makecache
        yum install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm
        sed -i 's|^#baseurl=https://download.example/pub|baseurl=https://mirrors.aliyun.com|' /etc/yum.repos.d/epel*
        sed -i 's|^metalink|#metalink|' /etc/yum.repos.d/epel*
    elif [[ $OS == Ubuntu-18.04* ]];then
        mkdir /etc/apt/backup && mv /etc/apt/sources.list /etc/apt/backup
cat > /etc/apt/sources.list <<EOF
deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse

deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
EOF
        rm -f /var/lib/apt/lists/lock && apt update
    fi
    echo -e "\e[32;1mSoftware source set complete\e[0m"

}

#11
install_package () {
    if [[ $OS == CentOS-Linux-7* ]];then
        yum install bash-completion vim-enhanced tree psmisc wget bc iotop gcc make gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel zip unzip zlib-devel net-tools lrzsz ntpdate telnet lsof tcpdump libevent libevent-devel openssh-server openssh-clients postfix -y
    elif [[ $OS == CentOS-Linux-8* ]];then
        dnf install bash-completion vim-enhanced tree psmisc wget bc iotop gcc make gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel zip unzip zlib-devel net-tools lrzsz chrony telnet lsof tcpdump libevent libevent-devel openssh-server openssh-clients postfix -y
	elif [[ $OS == Ubuntu-18.04* ]];then
        apt install make gcc iproute2 ntpdate tcpdump telnet traceroute nfs-kernel-server nfs-common lrzsz tree zip unzip openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev iotop libreadline-dev libsystemd-dev -y
    fi
    echo -e "\e[32;1mCommon Package already install\e[0m"
}

#12
set_time_sync () {
    if [[ $OS == CentOS-Linux-7* ]];then
        echo '*/5 * * * * ntpdate time1.aliyun.com &> /dev/null && hwclock -w' >> /var/spool/cron/root
        systemctl restart crond
    elif [[ $OS == CentOS-Linux-8* ]];then
        sed -i.bak '/^pool /c pool time1.aliyun.com iburst' /etc/chrony.conf
        systemctl restart chronyd && systemctl enable chronyd
        echo '*/5 * * * * chronyc -a makestep &> /dev/null && hwclock -w' >> /var/spool/cron/root
        systemctl restart crond
    elif [[ $OS == Ubuntu-18.04* ]];then
        echo '*/5 * * * * ntpdate time1.aliyun.com &> /dev/null && hwclock -w' >> /var/spool/cron/root
        systemctl restart cron
    fi
    echo -e "\e[32;1mTime sync complete\e[0m"
}

#13
set_eth () {
    if [[ $OS == CentOS* ]];then
        sed -i.bak '/GRUB_CMDLINE_LINUX/s#"$# net.ifnames=0"#' /etc/default/grub
        grub2-mkconfig -o /boot/grub2/grub.cfg &> /dev/null
    elif [[ $OS == Ubuntu-18.04* ]];then
        sed -i.bak '/GRUB_CMDLINE_LINUX/s#"$#net.ifnames=0"#' /etc/default/grub
        grub-mkconfig -o /boot/grub/grub.cfg &> /dev/null
    fi
    
    echo -e "\e[32;1mNetname already modify,Restart to take effect\e[0m"
}

set_eth0 () {
    if [[ $OS == Ubuntu-18.04* ]];then
        mv /etc/netplan/01-netcfg.yaml{,.bak}
cat > /etc/netplan/01-netcfg.yaml <<EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      addresses: [10.0.0.9/24]
      gateway4: 10.0.0.2
      nameservers:
        addresses: [223.5.5.5,114.114.114.114]
EOF
    fi
    echo -e "\e[32;1mIP already set\e[0m"
}

#14
set_ip () {
    if [[ $OS == CentOS-Linux-8* ]];then
        mv /etc/sysconfig/network-scripts/ifcfg-ens160{,.bak}
    read -p "Please input IP: " IP
    read -p "Please input Prefix: " PREFIX
    read -p "Please input Gateway: " GATEWAY
    read -p "Please input DNS1: " DNS1
    read -p "Please input DNS2: " DNS2
cat > /etc/sysconfig/network-scripts/ifcfg-eth0 <<EOF
TYPE=Ethernet
NAME=eth0
DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
IPADDR=$IP
PREFIX=$PREFIX
GATEWAY=$GATEWAY
DNS1=$DNS1
DNS2=$DNS2
EOF
    elif [[ $OS == CentOS-Linux-7* ]];then
        mv /etc/sysconfig/network-scripts/ifcfg-ens33{,.bak}
    read -p "Please input IP: " IP
    read -p "Please input Prefix: " PREFIX
    read -p "Please input Gateway: " GATEWAY
    read -p "Please input DNS1: " DNS1
    read -p "Please input DNS2: " DNS2
cat > /etc/sysconfig/network-scripts/ifcfg-eth0 <<EOF
TYPE=Ethernet
NAME=eth0
DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
IPADDR=$IP
PREFIX=$PREFIX
GATEWAY=$GATEWAY
DNS1=$DNS1
DNS2=$DNS2
EOF
    elif [[ $OS == Ubuntu-18.04* ]];then
        mv /etc/netplan/01-netcfg.yaml{,.bak}
        read -p "Please input IP/PREFIX: " IP_MASK
        read -p "Please input Gateway: " GATEWAY
        read -p "Please input DNS: " DNS
cat > /etc/netplan/01-netcfg.yaml <<EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      addresses: [$IP_MASK]
      gateway4: $GATEWAY
      nameservers:
        addresses: [$DNS]
EOF
    fi
    echo -e "\e[32;1mIP already set\e[0m"
}



echo -en "\e[32;1m"
cat <<EOF

This script applies to centos7 centos8 ubuntu1804!!!

Please select: 
1)Perimtrootlogin
2)Disable SElinux
3)Disable Firewall
4)Modify PS1
5)Set default text editor
6)Modify vim
7)Set History
8)Modify kernel parameters
9)Modify resource limits
10)set_software_source
11)Install Common Package
12)Set Time Sync
13)Modify NetName
14)Set IP
15)All realized
EOF
echo -en '\e[0m'
read -p "Please input number 1-15: " MENU
case $MENU in
1)
    set_ssh
    ;;
2)
    disable_selinux
    ;;
3)
    disbale_firewall
    ;;
4)
    set_ps1
    ;;
5)
    set_default_text_editor_vim
    ;;
6)
    set_vim
    ;;
7)
    set_history
    ;;
8)
    modify_kernel_parameters
    ;;
9)
    modify_resource_limits
    ;;
10)
    set_software_source
    ;;
11)
    install_package
    ;;
12)
    set_time_sync
    ;;
13)
    set_eth
    set_eth0
    ;;
14)
    set_ip
    ;;
15)
    #set_ssh
    disable_selinux
    disbale_firewall
    set_ps1
    set_default_text_editor_vim
    set_vim
    set_history
    modify_kernel_parameters
    modify_resource_limits
    set_software_source
    install_package
    set_time_sync
    set_eth
    set_eth0
    #set_ip
    echo -e "\e[32;1mAll done\e[0m"
    ;;
*)
    echo -e "\e[32;1mINPUY FLASE!\e[0m"
    ;;
esac

關於我
全網可搜《阿賢Linux》
CSDN、知乎、嗶哩嗶哩、博客園、51CTO、開源中國、思否、掘金、阿裡雲、騰訊雲、華為雲、今日頭條、GitHub、個人博客
公眾號:阿賢Linux
個人博客:blog.waluna.top
https://blog.waluna.top/


原文鏈接: 最小化安裝系統初始化腳本.


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • GitHub的Codespaces為個人用戶提供了免費的4核8G伺服器資源,今天就來實戰如何用桌面版vscode連接codespace伺服器做遠程開發,把編譯運行下載等耗時耗資源的操作都轉移到雲端進行,還能為應用創建各種docker服務,這都不要錢! ...
  • 先決條件 Visual Studio 2019 v16.9 預覽版1或更高版本(通過WSL可選組件進行.NET調試)。若要檢查 WSL 組件,請選擇 “工具” > “獲取工具和功能” 。 在 Visual Studio 安裝程式中,選擇 “單個組件”,然後鍵入 “WSL” 搜索安裝組件 。 安裝WS ...
  • ## 中台框架後端項目 Admin.Core 的介紹與配置說明 > 中台admin是前後端分離許可權管理系統,Admin.Core為後端項目,基於.NET 7.0開發。 > 支持多租戶、數據許可權、動態 Api、任務調度、OSS 文件上傳、滑塊拼圖驗證、多資料庫,分散式緩存、分散式事務等 - 項目地址 ...
  • ## 背景 ​ 我們寫博客難免需要大量圖片,如果把圖片一張張上傳到博客相冊再引用圖片鏈接,就很麻煩。所以需要一種手段,讓我們可以在本地寫完博客內容後,自動把博客引用的圖片傳到網上,併在網上發佈。 ​ 這時候就需要***dotnet-cnblog*** :博客園文章快捷發佈工具 ## 環境準備 ### ...
  • 整體統一前端框架,使用VUE重新寫,支持Windows模式和傳統菜單導航模式切換。整體框架支持租戶,全面支持雲端部署與應用。全新界面設計,提升用戶的易用性。 ...
  • Woa(Wechat Official Account)是一個基於.net 7開發的微信公眾平臺介面項目,利用Supabase作為數據存儲和消息通信服務,同時提供了ChatGPT和Claude2等目前熱門的生成式AI會話功能接入。 ...
  • # ansible、Ad-Hoc、YAML劇本 ## 1.簡介 ansible是新出現的自動化運維工具,基於Python開發,集合了眾多運維工具(puppet、cfengine、chef、func、fabric)的優點,實現了批量系統配置、批量程式部署、批量運行命令等功能。 ## 2.部署 1.dn ...
  • 哈嘍大家好,我是鹹魚 文章《[SELinux 導致 Keepalived 檢測腳本無法執行](https://mp.weixin.qq.com/s?__biz=MzkzNzI1MzE2Mw==&mid=2247486319&idx=1&sn=4932d10d7ad39d02d2536be1a70b1 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...