主頁 >  其他 > 如何利用Shell腳本進行Linux服務器之CentOS7系統初始化及其安全加固(適用于等保2.0)

如何利用Shell腳本進行Linux服務器之CentOS7系統初始化及其安全加固(適用于等保2.0)

2022-04-12 07:49:04 其他

CentOS7 系統初始化安全加固

描述: 適用于企業內部 CentOS7 系列服務器作業系統初始化、系統安全加固腳本,內容包含了,網路初始化設定,軟體更新源替換以及內核版本升級 ,時間時區初始化設定 系統安全加固(符合等保三級主機測評項) 安全運維設定 、系統內核引數優化、 常用軟體安裝等 一系列的操作直接開箱即用, 將跑過該腳本的機器可以克隆成為作為線上生產環境的基線模板,

原文鏈接: 完整的Windows與Linux服務器系統安全加固實踐和基線檢測腳本(等保2.0)( https://mp.weixin.qq.com/s/CDGzTzrAk9vJtbH4BisSlw )

CentOS7 安全加固效果
CentOS7 安全加固效果

專案地址: https://github.com/WeiyiGeek/SecOpsDev/tree/master/OS-作業系統/Linux/CentOS

【歡迎大家 Star 與 Fork 】


CentOS7 TLS Security Initiate
Link: https://github.com/WeiyiGeek/SecOpsDev/blob/master/OS-作業系統/Linux/CentOS/7/CentOS7-InitializeSecurity.sh

溫馨提示: 使用腳本時請按照你的需求呼叫相應函式即可,

#!/bin/bash
# @Author: WeiyiGeek
# @Description: CentOS7 TLS Security Initiate
# @Create Time:  2019年5月6日 11:04:42
# @Last Modified time: 2021-11-15 11:06:31
# @E-mail: [email protected]
# @Blog: https://www.weiyigeek.top
# @wechat: WeiyiGeeker
# @Github: https://github.com/WeiyiGeek/SecOpsDev/tree/master/OS-作業系統/Linux/
# @Version: 3.3
## ----------------------------------------- ##
# 腳本主要功能說明:
# (1) CentOS7系統初始化操作包括IP地址設定、基礎軟體包更新以及安裝加固,
# (2) CentOS7系統容器以及JDK相關環境安裝,
# (3) CentOS7系統中例外錯誤日志解決,
# (4) CentOS7系統中常規服務安裝配置,加入資料備份目錄,
# (4) CentOS7腳本錯誤解決和優化
## ----------------------------------------- ##

## 系統全域變數定義
# [系統配置]
HOSTNAME=CentOS-Security-Template
EXECTIME=$(date +%Y%m%d-%m%S)

# [網路配置]
IPADDR=192.168.1.2
NETMASK=225.255.255.0
GATEWAY=192.168.1.1
DNSIP=("223.5.5.5" "223.6.6.6")
SSHPORT=20211

# [用戶設定]
DefaultUser="WeiyiGeek"  # 系統創建的用戶名稱非root用戶
ROOTPASS=WeiyiGeek       # 密碼建議12位以上且包含數字、大小寫字母以及特殊字符,
APPPASS=WeiyiGeek

# [SNMP配置]
SNMP_user=WeiyiGeek
SNMP_group=testgroup
SNMP_view=testview
SNMP_password=dont_use_public
SNMP_ip=127.0.0.1

# [配置備份目錄]
BACKUPDIR=/var/log/.backups
if [ ! -d ${BACKUPDIR} ];then  mkdir -vp ${BACKUPDIR}; fi

# [配置記錄目錄]
HISDIR=/var/log/.history
if [ ! -d ${HISDIR} ];then  mkdir -vp ${HISDIR}; fi


## 名稱: err 、info 、warning
## 用途:全域Log資訊列印函式
## 引數: $@
log::err() {
  printf "[$(date +'%Y-%m-%dT%H:%M:%S')]: \033[31mERROR: $@ \033[0m\n"
}
log::info() {
  printf "[$(date +'%Y-%m-%dT%H:%M:%S')]: \033[32mINFO: $@ \033[0m\n"
}
log::warning() {
  printf "[$(date +'%Y-%m-%dT%H:%M:%S')]: \033[33mWARNING: $@ \033[0m\n"
}


## 名稱: os::Network
## 用途: 作業系統網路配置相關腳本包括(IP地址修改)
## 引數: 無
os::Network(){
  log::info "[-] 作業系統網路配置相關腳本,開始執行....."

 # (1) 靜態網路IP地址設定
tee /opt/network.sh <<'EOF'
#!/bin/bash
IPADDR="${1}"
NETMASK="${2}"
GATEWAY="${3}"
DEVNAME="ifcfg-ens192"
if [ "${4}" != "" ];then
  DEVNAME="ifcfg-${4}"
fi

if [[ $# -lt 3 ]];then
  echo -e "\e[32m[*] Usage: $0 IP-Address MASK Gateway \e[0m"
  echo -e "\e[32m[*] Usage: $0 192.168.1.99 255.255.255.0 192.168.1.1 \e[0m"
  exit 1
fi
NET_FILE="/etc/sysconfig/network-scripts/${DEVNAME}"
if [[ ! -f ${NET_FILE} ]];then
  log::err "[*] Not Found ${NET_FILE} File"
  exit 2
fi
cp ${NET_FILE}{,.bak}
sed -i -e 's/^ONBOOT=.*$/ONBOOT="yes"/' -e 's/^BOOTPROTO=.*$/BOOTPROTO="static"/' ${NET_FILE}
grep -q "^IPADDR=.*$" ${NET_FILE} &&  sed -i "s/^IPADDR=.*$/IPADDR=\"${IPADDR}\"/" ${NET_FILE} || echo "IPADDR=\"${IPADDR}\"" >> ${NET_FILE}
grep -q "^NETMASK=.*$" ${NET_FILE} &&  sed -i "s/^NETMASK=.*$/NETMASK=\"${NETMASK}\"/" ${NET_FILE} || echo "NETMASK=\"${NETMASK}\"" >> ${NET_FILE}
grep -q "^GATEWAY=.*$" ${NET_FILE} &&  sed -i "s/^GATEWAY=.*$/IPADDR=\"${GATEWAY}\"/" ${NET_FILE} || echo "GATEWAY=\"${GATEWAY}\"" >> ${NET_FILE}
EOF
chmod +x /opt/network.sh
/opt/network.sh ${IPADDR} ${NETMASK} ${GATEWAY}

# (2) 系統主機名與本地決議設定
sudo hostnamectl set-hostname ${HOSTNAME} 
# sed -i "s/127.0.1.1\s.\w.*$/127.0.1.1 ${NAME}/g" /etc/hosts
cp -a /etc/hosts  ${BACKUPDIR}/hosts.bak
grep -q "^\$(hostname -I)\s.\w.*$" /etc/hosts && sed -i "s/\$(hostname -I)\s.\w.*$/${IPADDR} ${HOSTNAME}" /etc/hosts || echo "${IPADDR} ${HOSTNAME}" >> /etc/hosts

# (3) 系統DNS域名決議服務設定
cp -a /etc/resolv.conf  ${BACKUPDIR}/resolv.conf.bak
for dns in  ${DNSIP[@]};do echo "nameserver ${dns}" >> /etc/resolv.conf;done

log::info "[*] network configure modifiy successful! restarting Network........."
service network restart && ip addr
}

## 名稱: os::Software
## 用途: 作業系統軟體包管理及更新源配置相關腳本
## 引數: 無
os::Software () {
  log::info "[-] 作業系統軟體包管理及更新源配置相關腳本,開始執行....."
  cp -a /etc/yum.repos.d/CentOS-Base.repo ${BACKUPDIR}/CentOS-Base.repo

# (1) CentOS 軟體倉庫鏡像源配置&&初始化更新
  log::info "[*] CentOS 軟體倉庫鏡像源配置&&初始化更新 "
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
curl -o /etc/yum.repos.d/CentOS-epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
sed -i "s#mirrors.cloud.aliyuncs.com#mirrors.aliyun.com#g" /etc/yum.repos.d/CentOS-Base.repo
rpm --import http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
yum clean all && yum makecache
yum --exclude=kernel* update -y && yum upgrade -y &&  yum -y install epel*


# (2) CentOS 作業系統內核升級(可選)
  cp -a /etc/grub2.cfg ${BACKUPDIR}/grub2.cfg.kernelupdate.bak
  log::info "[*] CentOS 作業系統內核升級(可選) "
rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
yum -y install https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm
yum --disablerepo="*" --enablerepo=elrepo-kernel repolist
yum --disablerepo="*" --enablerepo=elrepo-kernel list kernel*
# 內核安裝,服務器里我們選擇長期lt版本,安全穩定是我們最大的需求,除非有特殊的需求內核版本需求;
yum update -y --enablerepo=elrepo-kernel 
# 內核版本介紹, lt:longterm 的縮寫長期維護版, ml:mainline 的縮寫最新主線版本;
yum install -y --enablerepo=elrepo-kernel --skip-broken kernel-lt kernel-lt-devel kernel-lt-tools
# yum -y --enablerepo=elrepo-kernel --skip-broken install kernel-ml.x86_64 kernel-ml-devel.x86_64 kernel-ml-tools.x86_64
  log::warning "[*] 當前 CentOS 作業系統可切換的內核內核版本"
awk -F \' '$1=="menuentry " {print i++ " : " $2}' /etc/grub2.cfg
sudo grub2-set-default 0
#傳統引導
# grub2-mkconfig -o /boot/grub2/grub.cfg
# grubby --default-kernel
reboot

# (3) 安裝常用的運維軟體
# 編譯軟體
yum install -y gcc gcc-c++ g++ make jq libpam-cracklib openssl-devel bzip2-devel
# 常規軟體
yum install -y nano vim git unzip wget ntpdate dos2unix net-tools
yum install -y tree htop ncdu nload sysstat psmisc bash-completion fail2ban nfs-utils chrony
# 清空快取和已下載安裝的軟體包
yum clean all

  log::info "[*] Software configure modifiy successful!Please Happy use........."
}


## 名稱: os::TimedataZone
## 用途: 作業系統系統時間時區配置相關腳本
## 引數: 無
os::TimedataZone() {
  log::info "[*] 作業系統系統時間時區配置相關腳本,開始執行....."

# (1) 時區設定東8區
log::info "[*] 時區設定前的時間: $(date -R) "
timedatectl
cp -a /etc/localtime ${BACKUPDIR}/localtime.bak
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# (2) 時間同步軟體安裝
grep -q "192.168.12.254" /etc/chrony.conf || sudo tee -a /etc/chrony.conf <<'EOF'
pool 192.168.12.254 iburst maxsources 1
pool 192.168.10.254 iburst maxsources 1
pool 192.168.4.254 iburst maxsources 1
pool ntp.aliyun.com iburst maxsources 4
keyfile /etc/chrony.keys
driftfile /var/lib/chrony/chrony.drift
logdir /var/log/chrony
maxupdateskew 100.0
rtcsync
makestep 1.0 3
#stratumweight 0.05
#noclientlog
#logchange 0.5
EOF
systemctl enable chronyd && systemctl restart chronyd && systemctl status chronyd -l

# 將當前的 UTC 時間寫入硬體時鐘 (硬體時間默認為UTC)
sudo timedatectl set-local-rtc 0
# 啟用NTP時間同步:
timedatectl set-ntp yes
# 時間服務器連接查看
chronyc tracking
# 手動校準-強制更新時間
# chronyc -a makestep
# 硬體時鐘(系統時鐘同步硬體時鐘 )
hwclock --systohc 
# 備用方案: 采用 ntpdate 進行時間同步 ntpdate 192.168.10.254

# (3) 重啟依賴于系統時間的服務
sudo systemctl restart rsyslog.service crond.service

log::info "[*] Tie confmigure modifiy successful! restarting chronyd rsyslog.service crond.service........."
timedatectl
}


## 名稱: os::Security
## 用途: 作業系統安全加固配置腳本(符合等保要求-三級要求)
## 引數: 無
os::Security () {
  log::info "[-] 作業系統安全加固配置(符合等保要求-三級要求)"

# (0) 系統用戶及其終端核查配置
  log::info "[-] 鎖定或者洗掉多余的系統賬戶以及創建低權限用戶"
  # cat /etc/passwd | cut -d ":" -f 1 | tr '\n' ' '
defaultuser=(root bin daemon adm lp sync shutdown halt mail operator games ftp nobody systemd-network dbus polkitd sshd postfix chrony ntp rpc rpcuser nfsnobody)
for i in $(cat /etc/passwd | cut -d ":" -f 1,7);do
  flag=0; name=${i%%:*}; terminal=${i##*:}
  if [[ "${terminal}" == "/bin/bash" || "${terminal}" == "/bin/sh" ]];then
    log::warning "${i} 用戶,shell終端為 /bin/bash 或者 /bin/sh"
  fi
  for j in ${defaultuser[@]};do
    if [[ "${name}" == "${j}" ]];then
      flag=1
      break;
    fi
  done
  if [[ $flag -eq 0 ]];then
    log::warning "${i} 非默認用戶"
  fi
done
cp -a /etc/shadow ${BACKUPDIR}/shadow-${EXECTIME}.bak
passwd -l adm&>/dev/null 2&>/dev/null; passwd -l daemon&>/dev/null 2&>/dev/null; passwd -l bin&>/dev/null 2&>/dev/null; passwd -l sys&>/dev/null 2&>/dev/null; passwd -l lp&>/dev/null 2&>/dev/null; passwd -l uucp&>/dev/null 2&>/dev/null; passwd -l nuucp&>/dev/null 2&>/dev/null; passwd -l smmsplp&>/dev/null 2&>/dev/null; passwd -l mail&>/dev/null 2&>/dev/null; passwd -l operator&>/dev/null 2&>/dev/null; passwd -l games&>/dev/null 2&>/dev/null; passwd -l gopher&>/dev/null 2&>/dev/null; passwd -l ftp&>/dev/null 2&>/dev/null; passwd -l nobody&>/dev/null 2&>/dev/null; passwd -l nobody4&>/dev/null 2&>/dev/null; passwd -l noaccess&>/dev/null 2&>/dev/null; passwd -l listen&>/dev/null 2&>/dev/null; passwd -l webservd&>/dev/null 2&>/dev/null; passwd -l rpm&>/dev/null 2&>/dev/null; passwd -l dbus&>/dev/null 2&>/dev/null; passwd -l avahi&>/dev/null 2&>/dev/null; passwd -l mailnull&>/dev/null 2&>/dev/null; passwd -l nscd&>/dev/null 2&>/dev/null; passwd -l vcsa&>/dev/null 2&>/dev/null; passwd -l rpc&>/dev/null 2&>/dev/null; passwd -l rpcuser&>/dev/null 2&>/dev/null; passwd -l nfs&>/dev/null 2&>/dev/null; passwd -l sshd&>/dev/null 2&>/dev/null; passwd -l pcap&>/dev/null 2&>/dev/null; passwd -l ntp&>/dev/null 2&>/dev/null; passwd -l haldaemon&>/dev/null 2&>/dev/null; passwd -l distcache&>/dev/null 2&>/dev/null; passwd -l webalizer&>/dev/null 2&>/dev/null; passwd -l squid&>/dev/null 2&>/dev/null; passwd -l xfs&>/dev/null 2&>/dev/null; passwd -l gdm&>/dev/null 2&>/dev/null; passwd -l sabayon&>/dev/null 2&>/dev/null; passwd -l named&>/dev/null 2&>/dev/null


# (2) 用戶密碼設定和口令策略設定
log::info "[-]  配置滿足策略的root管理員密碼 "
echo "root:${ROOTPASS}" | chpasswd

log::info "[-] 配置滿足策略的app普通用戶密碼(根據需求配置)"
groupadd application
useradd -m -s /bin/bash -c "application primary user" -g application app 
echo "root:${APPPASS}" | chpasswd
 
log::info "[-] 強制用戶在下次登錄時更改密碼 "
chage -d 0 -m 0 -M 90 -W 15 root && passwd --expire root  
chage -d 0 -m 0 -M 90 -W 15 app && passwd --expire app
chage -d 0 -m 0 -M 90 -W 15 ${DefaultUser} && passwd --expire ${DefaultUser} 

log::info "[-] 用戶口令復雜性策略設定 (密碼過期周期0~90、到期前15天提示、密碼長度至少15、復雜度設定至少有一個大小寫、數字、特殊字符、密碼三次不能一樣、嘗試次數為三次)"
# 相關修改檔案備份
cp /etc/login.defs ${BACKUPDIR}/login.defs.bak;
cp /etc/pam.d/password-auth ${BACKUPDIR}/password-auth.bak
cp /etc/pam.d/system-auth ${BACKUPDIR}/system-auth.bak
egrep -q "^\s*PASS_MIN_DAYS\s+\S*(\s*#.*)?\s*$" /etc/login.defs && sed -ri "s/^(\s*)PASS_MIN_DAYS\s+\S*(\s*#.*)?\s*$/\PASS_MIN_DAYS  0/" /etc/login.defs || echo "PASS_MIN_DAYS  0" >> /etc/login.defs
egrep -q "^\s*PASS_MAX_DAYS\s+\S*(\s*#.*)?\s*$" /etc/login.defs && sed -ri "s/^(\s*)PASS_MAX_DAYS\s+\S*(\s*#.*)?\s*$/\PASS_MAX_DAYS  90/" /etc/login.defs || echo "PASS_MAX_DAYS  90" >> /etc/login.defs
egrep -q "^\s*PASS_WARN_AGE\s+\S*(\s*#.*)?\s*$" /etc/login.defs && sed -ri "s/^(\s*)PASS_WARN_AGE\s+\S*(\s*#.*)?\s*$/\PASS_WARN_AGE  15/" /etc/login.defs || echo "PASS_WARN_AGE  15" >> /etc/login.defs
egrep -q "^\s*PASS_MIN_LEN\s+\S*(\s*#.*)?\s*$" /etc/login.defs && sed -ri "s/^(\s*)PASS_MIN_LEN\s+\S*(\s*#.*)?\s*$/\PASS_MIN_LEN  15/" /etc/login.defs || echo "PASS_MIN_LEN  15" >> /etc/login.defs

egrep -q "^password\s.+pam_pwquality.so\s+\w+.*$" /etc/pam.d/password-auth && sed -ri '/^password\s.+pam_pwquality.so/{s/pam_pwquality.so\s+\w+.*$/pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=  minlen=15 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 difok=1 enforce_for_root/g;}' /etc/pam.d/password-auth
egrep -q "^password\s.+pam_unix.so\s+\w+.*$" /etc/pam.d/password-auth && sed -ri '/^password\s.+pam_unix.so/{s/pam_unix.so\s+\w+.*$/pam_unix.so sha512 shadow nullok try_first_pass use_authtok remember=3/g;}' /etc/pam.d/password-auth

egrep -q "^password\s.+pam_pwquality.so\s+\w+.*$" /etc/pam.d/system-auth && sed -ri '/^password\s.+pam_pwquality.so/{s/pam_pwquality.so\s+\w+.*$/pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=  minlen=15 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 difok=1 enforce_for_root/g;}' /etc/pam.d/system-auth
egrep -q "^password\s.+pam_unix.so\s+\w+.*$" /etc/pam.d/system-auth && sed -ri '/^password\s.+pam_unix.so/{s/pam_unix.so\s+\w+.*$/pam_unix.so sha512 shadow nullok try_first_pass use_authtok remember=3/g;}' /etc/pam.d/system-auth

log::info "[-] 存盤用戶密碼的檔案,其內容經過sha512加密,所以非常注意其權限"
# 解決首次登錄配置密碼時提示"passwd: Authentication token manipulation error"
touch /etc/security/opasswd && chown root:root /etc/security/opasswd && chmod 600 /etc/security/opasswd 


# (3) 設定用戶sudo權限以及重要目錄和檔案的新建默認權限
log::info "[-] 用戶sudo權限以及重要目錄和檔案的新建默認權限設定"
cp /etc/sudoers ${BACKUPDIR}/sudoers.bak
# 如CentOS安裝時您創建的用戶 WeiyiGeek 防止直接通過 sudo passwd 修改root密碼(此時必須要求輸入WeiyiGeek密碼后才可修改root密碼)
# Tips: Sudo允許授權用戶權限以另一個用戶(通常是root用戶)的身份運行程式, 
# DefaultUser="weiyigeek"
sed -i "/# Allows members of the/i ${DefaultUser} ALL=(ALL) PASSWD:ALL" /etc/sudoers

# 此引數需要根據業務來定,否則在使用時候會出現某些權限不足導致程式安裝報錯
log::info "[-] 配置用戶 umask 為022 "
cp -a /etc/profile ${BACKUPDIR}/profile
egrep -q "^\s*umask\s+\w+.*$" /etc/profile && sed -ri "s/^\s*umask\s+\w+.*$/umask 022/" /etc/profile || echo "umask 022" >> /etc/profile 
# log::info "[-] 設定用戶目錄創建默認權限, (初始為077比較嚴格)在未設定umask為027則默認為077"
# egrep -q "^\s*umask\s+\w+.*$" /etc/csh.login && sed -ri "s/^\s*umask\s+\w+.*$/umask 022/" /etc/csh.login || echo "umask 022" >> /etc/csh.login
# egrep -q "^\s*umask\s+\w+.*$" /etc/csh.cshrc && sed -ri "s/^\s*umask\s+\w+.*$/umask 022/" /etc/csh.cshrc || echo "umask 022" >> /etc/csh.cshrc
# egrep -q "^\s*(umask|UMASK)\s+\w+.*$" /etc/login.defs && sed -ri "s/^\s*(umask|UMASK)\s+\w+.*$/UMASK 027/" /etc/login.defs || echo "UMASK 027" >> /etc/login.defs

log::info "[-] 設定或恢復重要目錄和檔案的權限(設定日志檔案非全域可寫)"
chmod 600 ~/.ssh/authorized_keys;
chmod 755 /etc;
chmod 755 /etc/passwd; 
chmod 755 /etc/shadow; 
chmod 755 /etc/security; 
chmod 644 /etc/group; 
chmod 644 /etc/services; 
chmod 750 /etc/rc*.d;
chmod 755 /var/log/messages;
chmod 775 /var/log/spooler;
chmod 775 /var/log/cron;
chmod 775 /var/log/secure;
chmod 775 /var/log/maillog;
chmod 775 /var/log/mail&>/dev/null 2&>/dev/null; 
chmod 775 /var/log/localmessages&>/dev/null 2&>/dev/null

log::info "[-] 洗掉潛在威脅檔案 "
find / -maxdepth 3 -name hosts.equiv | xargs rm -rf
find / -maxdepth 3 -name .netrc | xargs rm -rf
find / -maxdepth 3 -name .rhosts | xargs rm -rf

# (4) SSHD 服務安全加固設定以及網路登陸Banner設定
log::info "[-] sshd 服務安全加固設定"
cp /etc/ssh/sshd_config ${BACKUPDIR}/sshd_config.bak
# 嚴格模式
sudo egrep -q "^\s*StrictModes\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^(#)?\s*StrictModes\s+.+$/StrictModes yes/" /etc/ssh/sshd_config || echo "StrictModes yes" >> /etc/ssh/sshd_config
# 默認的監聽埠更改
if [ -e ${SSHPORT} ];then export SSHPORT=20211;fi
sudo egrep -q "^\s*Port\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^(#)?\s*Port\s+.+$/Port ${SSHPORT}/" /etc/ssh/sshd_config || echo "Port ${SSHPORT}" >> /etc/ssh/sshd_config
# 禁用X11轉發以及埠轉發
sudo egrep -q "^\s*X11Forwarding\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^(#)?\s*X11Forwarding\s+.+$/X11Forwarding no/" /etc/ssh/sshd_config || echo "X11Forwarding no" >> /etc/ssh/sshd_config
sudo egrep -q "^\s*X11UseLocalhost\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^(#)?\s*X11UseLocalhost\s+.+$/X11UseLocalhost yes/" /etc/ssh/sshd_config || echo "X11UseLocalhost yes" >> /etc/ssh/sshd_config
sudo egrep -q "^\s*AllowTcpForwarding\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^(#)?\s*AllowTcpForwarding\s+.+$/AllowTcpForwarding no/" /etc/ssh/sshd_config || echo "AllowTcpForwarding no" >> /etc/ssh/sshd_config
sudo egrep -q "^\s*AllowAgentForwarding\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^(#)?\s*AllowAgentForwarding\s+.+$/AllowAgentForwarding no/" /etc/ssh/sshd_config || echo "AllowAgentForwarding no" >> /etc/ssh/sshd_config
# 關閉禁用用戶的 .rhosts 檔案  ~/.ssh/.rhosts 來做為認證: 預設IgnoreRhosts yes 
egrep -q "^(#)?\s*IgnoreRhosts\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^(#)?\s*IgnoreRhosts\s+.+$/IgnoreRhosts yes/" /etc/ssh/sshd_config || echo "IgnoreRhosts yes" >> /etc/ssh/sshd_config
# 禁止root遠程登錄(推薦配置-根據需求配置)
egrep -q "^\s*PermitRootLogin\s+.+$" /etc/ssh/sshd_config && sed -ri "s/^\s*PermitRootLogin\s+.+$/PermitRootLogin no/" /etc/ssh/sshd_config || echo "PermitRootLogin no" >> /etc/ssh/sshd_config
# 登陸前后歡迎提示設定
egrep -q "^\s*(banner|Banner)\s+\W+.*$" /etc/ssh/sshd_config && sed -ri "s/^\s*(banner|Banner)\s+\W+.*$/Banner \/etc\/issue/" /etc/ssh/sshd_config || \
echo "Banner /etc/issue" >> /etc/ssh/sshd_config
log::info "[-] 遠程SSH登錄前后提示警告Banner設定"
# SSH登錄前后提示警告Banner設定
sudo tee /etc/issue <<'EOF'
****************** [ 安全登陸 (Security Login) ] *****************
Authorized only. All activity will be monitored and reported.By Security Center.

EOF
# SSH登錄后提示Banner
# 藝術字B格: http://www.network-science.de/ascii/
sudo tee /etc/motd <<'EOF'

################## [ 安全運維 (Security Operation) ] ####################
            __          __  _       _  _____           _    
            \ \        / / (_)     (_)/ ____|         | |   
            \ \  /\  / /__ _ _   _ _| |  __  ___  ___| | __
              \ \/  \/ / _ \ | | | | | | |_ |/ _ \/ _ \ |/ /
              \  /\  /  __/ | |_| | | |__| |  __/  __/   < 
                \/  \/ \___|_|\__, |_|\_____|\___|\___|_|\_\
                              __/ |                        
                              |___/              
                                                    
Login success. Please execute the commands and operation data after carefully.By WeiyiGeek

EOF

# (5) 用戶遠程登錄失敗次數與終端超時設定 
log::info "[-] 用戶遠程連續登錄失敗10次鎖定帳號5分鐘包括root賬號"
cp /etc/pam.d/sshd ${BACKUPDIR}/sshd.bak
cp /etc/pam.d/login ${BACKUPDIR}/login.bak

# 遠程登陸
sed -ri "/^\s*auth\s+required\s+pam_tally2.so\s+.+(\s*#.*)?\s*$/d" /etc/pam.d/sshd 
sed -ri '2a auth required pam_tally2.so deny=10 unlock_time=300 even_deny_root root_unlock_time=300' /etc/pam.d/sshd 
# 宿主機控制臺登陸(可選)
# sed -ri "/^\s*auth\s+required\s+pam_tally2.so\s+.+(\s*#.*)?\s*$/d" /etc/pam.d/login
# sed -ri '2a auth required pam_tally2.so deny=10 unlock_time=300 even_deny_root root_unlock_time=300' /etc/pam.d/login

log::info "[-] 設定登錄超時時間為10分鐘 "
egrep -q "^\s*(export|)\s*TMOUT\S\w+.*$" /etc/profile && sed -ri "s/^\s*(export|)\s*TMOUT.\S\w+.*$/export TMOUT=600\nreadonly TMOUT/" /etc/profile || echo -e "export TMOUT=600\nreadonly TMOUT" >> /etc/profile
egrep -q "^\s*.*ClientAliveInterval\s\w+.*$" /etc/ssh/sshd_config && sed -ri "s/^\s*.*ClientAliveInterval\s\w+.*$/ClientAliveInterval 600/" /etc/ssh/sshd_config || echo "ClientAliveInterval 600" >> /etc/ssh/sshd_config

# (6) 切換用戶日志記錄和切換命令更改名稱為SU
log::info "[-] 切換用戶日志記錄和切換命令更改名稱為SU "
cp -a /etc/rsyslog.conf  ${BACKUPDIR}/rsyslog.conf-${EXECTIME}.bak
egrep -q "^\s*authpriv\.\*\s+.+$" /etc/rsyslog.conf && sed -ri "s/^\s*authpriv\.\*\s+.+$/authpriv.*  \/var\/log\/secure/" /etc/rsyslog.conf || echo "authpriv.*  /var/log/secure" >> /etc/rsyslog.conf
egrep -q "^(\s*)SULOG_FILE\s+\S*(\s*#.*)?\s*$" /etc/login.defs && sed -ri "s/^(\s*)SULOG_FILE\s+\S*(\s*#.*)?\s*$/\SULOG_FILE  \/var\/log\/.history\/sulog/" /etc/login.defs || echo "SULOG_FILE  /var/log/.history/sulog" >> /etc/login.defs
egrep -q "^\s*SU_NAME\s+\S*(\s*#.*)?\s*$" /etc/login.defs && sed -ri "s/^(\s*)SU_NAME\s+\S*(\s*#.*)?\s*$/\SU_NAME  SU/" /etc/login.defs || echo "SU_NAME  SU" >> /etc/login.defs
mkdir -vp /usr/local/bin
cp /usr/bin/su ${BACKUPDIR}/su.bak
mv /usr/bin/su /usr/bin/SU
chmod 777 /var/log/.history 
chattr -R +a /var/log/.history 
chattr +a /var/log/.backups 

# (7) 用戶終端執行的歷史命令記錄
log::info "[-] 用戶終端執行的歷史命令記錄 "
egrep -q "^HISTSIZE\W\w+.*$" /etc/profile && sed -ri "s/^HISTSIZE\W\w+.*$/HISTSIZE=101/" /etc/profile || echo "HISTSIZE=101" >> /etc/profile
sudo tee /etc/profile.d/history-record.sh <<'EOF'
# 歷史命令執行記錄檔案路徑
LOGTIME=$(date +%Y%m%d-%H-%M-%S)
export HISTFILE="/var/log/.history/${USER}.${LOGTIME}.history"
if [ ! -f ${HISTFILE} ];then
  touch ${HISTFILE}
fi
chmod 600 /var/log/.history/${USER}.${LOGTIME}.history
# 歷史命令執行檔案大小記錄設定
HISTFILESIZE=128
HISTTIMEFORMAT="%F_%T $(whoami)#$(who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'):"
EOF


# (8) GRUB 安全設定
  log::info "[-] 系統 GRUB 安全設定(防止物理接觸從grub選單中修改密碼) "
# Grub 關鍵檔案備份
cp -a /etc/grub.d/00_header ${BACKUPDIR}/'00_header'${EXECTIME}.bak
cp -a /etc/grub.d/10_linux ${BACKUPDIR}/'10_linux'${EXECTIME}.bak
# 設定Grub選單界面顯示時間
sed -i -e 's|set timeout_style=${style}|#set timeout_style=${style}|g' -e 's|set timeout=${timeout}|set timeout=3|g' /etc/grub.d/00_header
# sed -i -e 's|GRUB_TIMEOUT_STYLE=hidden|#GRUB_TIMEOUT_STYLE=hidden|g' -e 's|GRUB_TIMEOUT=0|GRUB_TIMEOUT=3|g' /etc/default/grub
# grub 用戶認證密碼創建
sudo grub2-mkpasswd-pbkdf2
# 輸入口令:
# Reeter password:n
PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.A4A6B06EFAB660C11DD8EBC3BE73C5AB5D763ED937060477DB533B3E7D60F1DE66C3AC12DA795B46762AB8C4A1911B69B94FFCD88FB4499938150405DCB116F8.35D290F5B8D2677AEE5E8BAB4DB133206D417F99A26B14EAB8D0A5379DCD3632F40037388C9D2CA3001E0D6A8B74837549970EEEAEC3420CE38E2236DE1A8565
# 設定認證用戶以及上面生成的password_pbkdf2認證密鑰
tee -a /etc/grub.d/00_header <<'END'
cat <<'EOF'
# GRUB Authentication
set superusers="grub"
password_pbkdf2 grub grub.pbkdf2.sha512.10000.A4A6B06EFAB660C11DD8EBC3BE73C5AB5D763ED937060477DB533B3E7D60F1DE66C3AC12DA795B46762AB8C4A1911B69B94FFCD88FB4499938150405DCB116F8.35D290F5B8D2677AEE5E8BAB4DB133206D417F99A26B14EAB8D0A5379DCD3632F40037388C9D2CA3001E0D6A8B74837549970EEEAEC3420CE38E2236DE1A8565
EOF
END
# 設定進入正式系統不需要認證如進入單用戶模式進行重置賬號密碼時需要進行認證, (高敏感資料庫系統不建議下述操作)
# 在 135 加入 -unrestricted ,例如, 此處與Ubuntu不同的是不加--user=grub
# 133 echo "menuentry $(echo "$title" | grub_quote)' ${CLASS} \$menuentry_id_option 'gnulinux-$version-$type-    $boot_device_id' {" | sed "s/^/$submenu_indentation/"
# 134   else
# 135 echo "menuentry --unrestricted '$(echo "$os" | grub_quote)' ${CLASS} \$menuentry_id_option 'gnulinux-simple-$boot_devic    e_id' {" | sed "s/^/$submenu_indentation/"
sed -i '/echo "$title" | grub_quote/ { s/menuentry /menuentry /;}' /etc/grub.d/10_linux
sed -i '/echo "$os" | grub_quote/ { s/menuentry /menuentry --unrestricted /;}' /etc/grub.d/10_linux
# CentOS 方式更新GRUB從而生成boot啟動檔案
grub2-mkconfig -o /boot/grub2/grub.cfg


# (9) 記錄安全事件日志
  log::info "[-] 記錄安全事件日志"
touch /var/log/.history/adm&>/dev/null; chmod 755 /var/log/.history/adm
semanage fcontext -a -t security_t '/var/log/.history/adm'
restorecon -v '/var/log/.history/adm'&>/dev/null
egrep -q "^\s*\*\.err;kern.debug;daemon.notice\s+.+$" /etc/rsyslog.conf && sed -ri "s/^\s*\*\.err;kern.debug;daemon.notice\s+.+$/*.err;kern.debug;daemon.notice  \/var\/log\/.history\/adm/" /etc/rsyslog.conf || echo "*.err;kern.debug;daemon.notice  /var/log/.history/adm" >> /etc/rsyslog.conf


# (10) 配置自動螢屏鎖定(適用于具備圖形界面的設備), 非圖形界面不需要執行
  log::info "[-] 對于有圖形界面的系統配置10分鐘螢屏鎖定"
# gconftool-2 --direct \
# --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory \
# --type bool \
# --set /apps/gnome-screensaver/idle_activation_enabled true \
# --set /apps/gnome-screensaver/lock_enabled true \
# --type int \
# --set /apps/gnome-screensaver/idle_delay 10 \
# --type string \
# --set /apps/gnome-screensaver/mode blank-only


# (10) 關閉CentOS服務器中 SELINUX 以及防火墻埠放行
  log::info "[-] SELINUX 禁用以及系統防火墻規則設定 "
sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config 
semanage port -m -t ssh_port_t -p tcp 20211 # 添加sshd服務20211埠到SELinux
firewall-cmd --zone=public --add-port=20211/tcp --permanent
firewall-cmd --zone=public --add-port=161/udp --permanent
firewall-cmd --reload
systemctl restart sshd
reboot
}


## 名稱: os::Operation 
## 用途: 作業系統安全運維設定相關腳本
## 引數: 無
os::Operation () {
  log::info "[-] 作業系統安全運維設定相關腳本"

# (0) 禁用ctrl+alt+del組合鍵對系統重啟 (必須要配置,我曾入過坑)
 log::info "[-] 禁用控制臺ctrl+alt+del組合鍵重啟"
mv /usr/lib/systemd/system/ctrl-alt-del.target ${BACKUPDIR}/ctrl-alt-del.target-${EXECTIME}.bak

# (1) 設定檔案洗掉回收站別名
  log::info "[-] 設定檔案洗掉回收站別名(防止誤刪檔案) "
sudo tee -a  /etc/profile.d/alias.sh <<'EOF'
# User specific aliases and functions
# 洗掉回收站
# find ~/.trash -delete
# 洗掉空目錄
# find ~/.trash -type d -delete
alias rm="sh /usr/local/bin/remove.sh"
EOF
sudo tee /usr/local/bin/remove.sh <<'EOF'
#!/bin/sh
# 定義回收站檔案夾目錄.trash
trash="/.trash"
deltime=$(date +%Y%m%d-%H-%M-%S)
TRASH_DIR="${HOME}${trash}/${deltime}"
# 建立回收站目錄當不存在的時候
if [ ! -e ${TRASH_DIR} ];then
   mkdir -p ${TRASH_DIR}
fi
for i in $*;do
  if [ "$i" = "-rf" ];then continue;fi
  # 防止誤操作
  if [ "$i" = "/" ];then echo '# Danger delete command, Not delete / directory!';exit -1;fi
	#定義秒時間戳
	STAMP=$(date +%s)
	#得到檔案名稱(非檔案夾),參考man basename
	fileName=$(basename $i)
	#將輸入的引數,對應檔案mv至.trash目錄,檔案后綴,為當前的時間戳
	mv $i ${TRASH_DIR}/${fileName}.${STAMP}
done
EOF
sudo chmod +775 /usr/local/bin/remove.sh /etc/profile.d/alias.sh /etc/profile.d/history-record.sh
sudo chmod a+x /usr/local/bin/remove.sh /etc/profile.d/alias.sh /etc/profile.d/history-record.sh
source /etc/profile.d/alias.sh  /etc/profile.d/history-record.sh

}



## 名稱: os::DisableService
## 用途: 禁用與設定作業系統中某些服務(需要根據實際環境進行)
## 引數: 無
os::DisableService () {
  log::info "[-] 禁用作業系統中某些服務(需要根據實際環境進行配置)"

  log::info "[-] 配置禁用telnet服務"
cp /etc/services ${BACKUPDIR}/'services-'${EXECTIME}.bak
egrep -q "^\s*telnet\s+\d*.+$" /etc/services && sed -ri "/^\s*telnet\s+\d*.+$/s/^/# /" /etc/services

  log::info "[-] 禁止匿名與root用戶用戶登錄FTP"
if [ -f /etc/vsftpd/vsftpd.conf ];then
cp /etc/vsftpd/vsftpd.conf /etc/vsftpd/'vsftpd.conf-'`date +%Y%m%d`.bak
systemctl list-unit-files|grep vsftpd > /dev/null && sed -ri "/^\s*anonymous_enable\s*\W+.+$/s/^/#/" /etc/vsftpd/vsftpd.conf && echo "anonymous_enable=NO" >> /etc/vsftpd/vsftpd.conf
systemctl list-unit-files|grep vsftpd > /dev/null && echo "root" >> /etc/vsftpd/ftpusers
  log::info "[-] 限制FTP用戶上傳的檔案所具有的權限"
systemctl list-unit-files|grep vsftpd > /dev/null && sed -ri "/^\s*write_enable\s*\W+.+$/s/^/#/" /etc/vsftpd/vsftpd.conf && echo "write_enable=NO" >> /etc/vsftpd/vsftpd.conf
systemctl list-unit-files|grep vsftpd > /dev/null && sed -ri "/^\s*ls_recurse_enable\s*\W+.+$/s/^/#/" /etc/vsftpd/vsftpd.conf && echo "ls_recurse_enable=NO" >> /etc/vsftpd/vsftpd.conf
systemctl list-unit-files|grep vsftpd > /dev/null && sed -ri "/^\s*anon_umask\s*\W+.+$/s/^/#/" /etc/vsftpd/vsftpd.conf && echo "anon_umask=077" >> /etc/vsftpd/vsftpd.conf
systemctl list-unit-files|grep vsftpd > /dev/null && sed -ri "/^\s*local_umask\s*\W+.+$/s/^/#/" /etc/vsftpd/vsftpd.conf && echo "local_umask=022" >> /etc/vsftpd/vsftpd.conf
  log::info "[-] 限制FTP用戶登錄后能訪問的目錄"
systemctl list-unit-files|grep vsftpd > /dev/null && sed -ri "/^\s*chroot_local_user\s*\W+.+$/s/^/#/" /etc/vsftpd/vsftpd.conf && echo "chroot_local_user=NO" >> /etc/vsftpd/vsftpd.conf
  log::info "[-] FTP Banner 設定"
systemctl list-unit-files|grep vsftpd > /dev/null && sed -ri "/^\s*ftpd_banner\s*\W+.+$/s/^/#/" /etc/vsftpd/vsftpd.conf && echo "ftpd_banner='Authorized only. All activity will be monitored and reported.'" >> /etc/vsftpd/vsftpd.conf

  log::info "[-] 限制不必要的服務 (根據實際環境配置)"
# systemctl disable rsh&>/dev/null 2&>/dev/null;systemctl disable talk&>/dev/null 2&>/dev/null;systemctl disable telnet&>/dev/null 2&>/dev/null;systemctl disable tftp&>/dev/null 2&>/dev/null;systemctl disable rsync&>/dev/null 2&>/dev/null;systemctl disable xinetd&>/dev/null 2&>/dev/null;systemctl disable nfs&>/dev/null 2&>/dev/null;systemctl disable nfslock&>/dev/null 2&>/dev/null
fi

  log::info "[-] 配置SNMP默認團體字"
if [ -f /etc/snmp/snmpd.conf ];then
cp /etc/snmp/snmpd.conf ${BACKUPDIR}/'snmpd.conf-'${EXECTIME}.bak
cat > /etc/snmp/snmpd.conf <<EOF
com2sec $SNMP_user  default    $SNMP_password   
group   $SNMP_group         v1           $SNMP_user
group   $SNMP_group         v2c          $SNMP_user
view    systemview      included        .1                      80
view    systemview      included        .1.3.6.1.2.1.1
view    systemview      included        .1.3.6.1.2.1.25.1.1
view    $SNMP_view        included        .1.3.6.1.4.1.2021.80
access  $SNMP_group         ""      any       noauth    exact  systemview none none
access  $SNMP_group         ""      any       noauth    exact  $SNMP_view   none none
dontLogTCPWrappersConnects yes
trapcommunity $SNMP_password
authtrapenable 1
trap2sink $SNMP_ip
agentSecName $SNMP_user
rouser $SNMP_user
defaultMonitors yes
linkUpDownNotifications yes
EOF
fi
}


## 名稱: os::optimizationn
## 用途: 作業系統優化設定(內核參數)
## 引數: 無
os::Optimizationn () {
log::info "[-] 正在進行作業系統內核引數優化設定......."

# (1) 系統內核引數的配置(/etc/sysctl.conf)
log::info "[-] 系統內核引數的配置/etc/sysctl.conf"

# /etc/sysctl.d/99-kubernetes-cri.conf
egrep -q "^(#)?net.ipv4.ip_forward.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv4.ip_forward.*|net.ipv4.ip_forward = 1|g"  /etc/sysctl.conf || echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
# egrep -q "^(#)?net.bridge.bridge-nf-call-ip6tables.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.bridge.bridge-nf-call-ip6tables.*|net.bridge.bridge-nf-call-ip6tables = 1|g" /etc/sysctl.conf || echo "net.bridge.bridge-nf-call-ip6tables = 1" >> /etc/sysctl.conf 
# egrep -q "^(#)?net.bridge.bridge-nf-call-iptables.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.bridge.bridge-nf-call-iptables.*|net.bridge.bridge-nf-call-iptables = 1|g" /etc/sysctl.conf || echo "net.bridge.bridge-nf-call-iptables = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.all.disable_ipv6.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.all.disable_ipv6.*|net.ipv6.conf.all.disable_ipv6 = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.default.disable_ipv6.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.default.disable_ipv6.*|net.ipv6.conf.default.disable_ipv6 = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.default.disable_ipv6 = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.lo.disable_ipv6.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.lo.disable_ipv6.*|net.ipv6.conf.lo.disable_ipv6 = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.lo.disable_ipv6 = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.all.forwarding.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.all.forwarding.*|net.ipv6.conf.all.forwarding = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.all.forwarding = 1"  >> /etc/sysctl.conf
egrep -q "^(#)?vm.max_map_count.*" /etc/sysctl.conf && sed -ri "s|^(#)?vm.max_map_count.*|vm.max_map_count = 262144|g" /etc/sysctl.conf || echo "vm.max_map_count = 262144"  >> /etc/sysctl.conf

tee -a /etc/sysctl.conf <<'EOF'
# 調整提升服務器負載能力之外,還能夠防御小流量的Dos、CC和SYN攻擊
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
# net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 60
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_fastopen = 3

# 優化TCP的可使用埠范圍及提升服務器并發能力(注意一般流量小的服務器上沒必要設定如下引數)
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.ip_local_port_range = 1024 65535

# 優化核套接字TCP的快取區
net.core.netdev_max_backlog = 8192
net.core.somaxconn = 8192
net.core.rmem_max = 12582912
net.core.rmem_default = 6291456
net.core.wmem_max = 12582912
net.core.wmem_default = 6291456
EOF


# (2) Linux 系統的最大行程數和最大檔案打開數限制
log::info "[-] Linux 系統的最大行程數和最大檔案打開數限制 "
egrep -q "^\s*ulimit -HSn\s+\w+.*$" /etc/profile && sed -ri "s/^\s*ulimit -HSn\s+\w+.*$/ulimit -HSn 65535/" /etc/profile || echo "ulimit -HSn 65535" >> /etc/profile
egrep -q "^\s*ulimit -HSu\s+\w+.*$" /etc/profile && sed -ri "s/^\s*ulimit -HSu\s+\w+.*$/ulimit -HSu 65535/" /etc/profile || echo "ulimit -HSu 65535" >> /etc/profile
sed -i "/# End/i *  soft  nofile  65535" /etc/security/limits.conf
sed -i "/# End/i *  hard  nofile  65535" /etc/security/limits.conf
sed -i "/# End/i *  soft  nproc   65535" /etc/security/limits.conf
sed -i "/# End/i *  hard  nproc   65535" /etc/security/limits.conf
sysctl -p

# 需重啟生效
reboot
}

## 名稱: os::Swap
## 用途: Liunx 系統創建SWAP交換磁區(默認2G)
## 引數: $1(幾G)
os::Swap () {
  if [ -e $1 ];then
    sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152   # 2G Swap 磁區 1024 * 1024 , centos 以 1000 為標準
  else
    number=$(echo "${1}*1024*1024"|bc)
    sudo dd if=/dev/zero of=/swapfile bs=1024 count=${number}   # 2G Swap 磁區 1024 * 1024 , centos 以 1000 為標準
  fi

  sudo mkswap /swapfile && sudo swapon /swapfile
  if [ $(grep -c "/swapfile" /etc/fstab) -eq 0 ];then
sudo tee -a /etc/fstab <<'EOF'
/swapfile swap swap default 0 0
EOF
fi
sudo swapon --show && sudo free -h
}


## 名稱: software::Java
## 用途: java 環境安裝與設定 
## 引數: 無
software::Java () {
  # 基礎變數
  JAVA_FILE="/root/Downloads/jdk-8u211-linux-x64.tar.gz"
  JAVA_SRC="https://www.cnblogs.com/usr/local/"
  JAVA_DIR="/usr/local/jdk"
  # 環境配置
  sudo tar -zxvf ${JAVA_FILE} -C ${JAVA_SRC}
  sudo rm -rf /usr/local/jdk 
  JAVA_SRC=https://www.cnblogs.com/WeiyiGeek/p/$(ls /usr/local/ | grep"jdk")
  sudo ln -s ${JAVA_SRC} ${JAVA_DIR}
  export PATH=${JAVA_DIR}/bin:${PATH}
  sudo cp /etc/profile /etc/profile.$(date +%Y%m%d-%H%M%S).bak
  sudo tee -a /etc/profile <<'EOF'
export JAVA_HOME=/usr/local/jdk
export JRE_HOME=/usr/local/jdk/jre
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$JAVA_HOME/bin:$PATH
EOF
  java -version
}

## 名稱: disk::Lvsmanager
## 用途: CentOS7 作業系統磁盤 LVS 邏輯卷添加與配置(擴容流程)
## 引數: 無
disk::lvsmanager () {
  echo "\n磁區資訊:"
  sudo df -Th
  sudo lsblk
  echo -e "\n 磁盤資訊:"
  sudo fdisk -l
  echo -e "\n PV物理卷查看:"
  sudo pvscan
  echo -e "\n vgs虛擬卷查看:"
  sudo vgs
  echo -e "\n lvscan邏輯卷掃描:"
  sudo lvscan
  echo -e "\n 磁區擴展"
  echo "CentOS \n lvextend -L +24G /dev/centos/root"
  echo "lsblk"
  echo -e "Centos \n # xfs_growfs /dev/mapper/centos-root"
}

# 安全加固程序臨時檔案清理為基線鏡像做準備
unalias rm
find ~/.trash/* -delete
find /home/ -type d -name .trash -exec find {} -delete \;
find /var/log -name "*.gz" -delete
find /var/log -name "*log.*" -delete
find /var/log -name "vmware-*.*.log" -delete
find /var/log -name "*.log" -exec truncate -s 0 {} \;
find /var/log -name "system@*" -delete
find /var/log -name "user-1000@*" -delete
find /tmp/* -delete

至此 CentOS7 安全加固腳本完畢,

原文地址: Linux與Windows服務器作業系統安全防御實踐指南 ( https://blog.weiyigeek.top/2020/10-13-585.html )


文章書寫不易,如果您覺得這篇文章還不錯的,請給這篇專欄 【點個贊、投個幣、收個藏、關個注,轉個發】(人間五大情),這將對我的肯定,謝謝!,

本文章來源 我的Blog站點 或 WeiyiGeek 公眾賬號 以及 我的BiliBili專欄 (技術交流、友鏈交換請郵我喲),謝謝支持!(?′?‵?) ?
歡迎各位志同道合的朋友一起學習交流,如文章有誤請留下您寶貴的知識建議,通過郵箱【master#weiyigeek.top】聯系我喲!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/458005.html

標籤:其他

上一篇:挖礦病毒分析(centos7)

下一篇:如何利用Shell腳本對Ubuntu作業系統進行常規初始化和系統優化及其安全加固(適用于等保2.0)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more