本文最后更新于139 天前,其中的信息可能已经过时,如有错误请发送邮件到[email protected]
## 注: ntp函数还有点问题,后续更改
## 禁用root函数默认没有开,开的话在脚本最后面加上函数名即可,不过要记住创建的普通用户及密码,不然登不上去了
#!bin/bash
echo -e "\033[46;35m==========欢迎使用多功能系统脚本文件==========\033[0m\n"
echo -e "\033[46;35m ==========此脚本用于初始化服务器=========\033[0m\n"
echo -e "\033[35m=========脚本初始化内容包括=========\n
1.禁止root用户使用ssh登陆服务器,必须通过一个新建用户来sudo授权达到执行root用户的权利\n2.关闭selinux及防火墙配置(手动选择是否关闭网络守护进程服务)\n3.配置yum源信息(网络配置用PXE或Cobbler)\n4.系统加固配置\n5.设置时间同步\n6.设置内核参数及历史命令保存条目(历史命令执行时间)\n7.安装常用工具(yum安装)\n8.配置ssh加速登陆\n
\033[0m"
echo -e "\033[31m下面请连续两次输入回车即开始初始化\033[0m"
read -p "请点击我!" click_one
read -p "请再次点击我!" click_two
# 1.禁用root直连---授权普通用户sudo
disable_ssh_root(){
echo -e "\033[32m======================禁用root直连---授权普通用户sudo======================\033[0m"
grep_string=("/" "." "%" "!" "@" "#" "^" "*" "(" ")")
sed -i '/^#PermitRootLogin/a \PermitRootLogin no' /etc/ssh/sshd_config
systemctl restart sshd&>/dev/null
sed -i 's/^%wheel/#%wheel/g' /etc/sudoers
sed -i 's/^# %wheel/%wheel/g' /etc/sudoers
read -p "请输入一个测试用户用于远程登陆系统并可以授权使用root权限?(sudo su)---: " empower_user
if [ -z "${empower_user}" ];then
echo -e "\033[31m您输入的内容为空,请重新输入\033[0m"
elif [ -n "${empower_user}" ];then
for i in _
do
echo "${empower_user}" | grep -E '^[A-Z]|\W'&>/dev/null
#echo "${empower_user}" | egrep '^[A-Z]|${i}'&>/dev/null
if [ $? -ne 0 ];then
useradd -g wheel ${empower_user}&>/dev/null
pwd_random=$(< /dev/urandom tr -dc 'A-Za-z' | fold -w 10 | head -n 1)
text_random=$(< /dev/urandom tr -dc 'A-Za-z' | fold -w 10 | head -n 1)
echo $pwd_random | passwd --stdin "${empower_user}"&>/dev/null
echo $pwd_random >> /home/"${empower_user}"/"${text_random}.txt"
if [ $? -eq 0 ];then
echo -e "\033[37m添加用户并把新用户添加到组中成功\033[0m"
echo -e "\033[33m新用户密码保存在/home/${empower_user}/${text_random}.txt文件中"
break
fi
else
echo -e "\033[31m您输入的用户字符串中带有一些特殊符号或开头字母为大写,请重新输入!\033[0m"
exit 110
fi
done
fi
}
# 通用配置other
disable_General_configuration_other(){
ufw disable
if [ -f /etc/selinux/config ];then
read -p "确定要安装selinux软件工具包吗(y/n)? " install_utils
case "${install_utils}" in
Y|y)
apt install policycoreutils policycoreutils-python-utils selinux-policy-targeted&>/dev/null
setenforce 0 && sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
;;
N|n)
echo -e "\033[32m您不需要安装软件工具包!\033[0m"
setenforce 0 && sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
;;
*)
echo -e "\033[31m输入错误!\033[0m"
exit 111
esac
fi
read -p "确定将网络守护进程(NetworkManager)关闭吗?(y/n)" NetworkManager
case "${NetworkManager}" in
y|Y)
systemctl stop NetworkManager && systemctl disable NetworkManager&>/dev/null
;;
N|n)
echo -e "\033[32m您不需要关闭网络守护进程!\033[0m"
;;
*)
echo -e "\033[31m输入错误,请重新输入\033[0m"
exit 111
esac
}
# 通用配置centos
disable_General_configuration_centos(){
systemctl stop firewalld && systemctl disable firewalld&>/dev/null
if [ -f /etc/selinux/config ];then
read -p "确定要安装selinux软件工具包吗(y/n)? " install_utils
case "${install_utils}" in
Y|y)
yum -y install policycoreutils policycoreutils-python-utils selinux-policy-targeted&>/dev/null
setenforce 0 && sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
;;
N|n)
echo -e "\033[32m您不需要安装软件工具包!\033[0m"
setenforce 0 && sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
;;
*)
echo -e "\033[31m输入错误,请重新输入!\033[0m"
exit 111
esac
fi
read -p "确定将网络守护进程(NetworkManager)关闭吗?(y/n)" NetworkManager
case "${NetworkManager}" in
y|Y)
systemctl stop NetworkManager && systemctl disable NetworkManager&>/dev/null
;;
N|n)
echo -e "\033[32m您不需要关闭网络守护进程!\033[0m"
;;
*)
echo -e "\033[31m输入错误,请重新输入\033[0m"
exit 111
esac
}
# 2.禁用selinux和防火墙配置(不同操作系统)
disable_selinux_firewalld(){
echo -e "\033[32m======================关闭selinux和防火墙配置======================\033[0m"
# 判断ubuntu和centos和debian
if [ -f /etc/os-release ];then
os_release=$(cat /etc/os-release | grep "ID" | head -n1 |awk -F "=" '{print $2}' | grep -Eo "\w+")
if [[ ${os_release} == "centos" ]];then
disable_General_configuration_centos
elif [[ ${os_release} == "ubuntu" ]];then
disable_General_configuration_other
fi
# 判断redhat
elif [ -f /etc/redhat-release ];then
disable_General_configuration_centos
# 判断SuSE和fedora
elif [ -f /etc/SuSE-release ] || [ -f /etc/fedora-release ];then
disable_General_configuration_other
fi
}
# 3.配置yum信息及网络配置
# 华为epel源
OS_RELEASE=$(cat /etc/os-release | grep "ID" | head -n1 |awk -F "=" '{print $2}' | grep -Eo "\w+")
VERSION_ID=$(cat /etc/os-release | grep "VERSION_ID" | awk -F "=" '{print $2}' | grep -Eo "\w")
configuration_yum_network(){
echo -e "\033[32m======================配置yum信息及网络配置======================\033[0m"
# 宿主机操作系统版本号和发行版本
# 厂商epel源函数
epel_yum_huawei=(
"https://mirrors.huaweicloud.com/repository/conf/CentOS-"${VERSION_ID}"-anon.repo"
)
epel_yum_aliyun=(
"https://mirrors.aliyun.com/repo/Centos-"${VERSION_ID}".repo"
"http://mirrors.aliyun.com/repo/fedora.repo"
"http://mirrors.aliyun.com/repo/fedora-updates.repo"
)
#epel_yum_163=(
# "http://mirrors.163.com/.help/CentOS"${VERSION_ID}"-Base-163.repo"
# "http://mirrors.163.com/.help/fedora-163.repo"
# "http://mirrors.163.com/.help/fedora-updates-163.repo"
#)
# 截取厂商字段
huawei_cloud=$(echo "https://mirrors.huaweicloud.com/repository/conf/CentOS-8-anon.repo" | awk -F 'mirrors.' '{print $2}' | awk -F '.com' '{print $1}')
aliyun_cloud=$(echo "http://mirrors.aliyun.com/repo/fedora.repo" | awk -F "mirrors." '{print $2}' | awk -F ".com/" '{print $1}')
#wy163_cloud=$(echo "http://mirrors.163.com/.help/CentOS7-Base-163.repo" | awk -F "mirrors." '{print $2}' | awk -F ".com" '{print $1}')
read -p "请输入您是要选择网络yum源或者是本地yum源!(1网络|2本地)---:" Base_Media
case "${Base_Media}" in
1)
if [ "${OS_RELEASE}" == "centos" ] || [ -f /etc/redhat-release ];then
mkdir -p /etc/yum.repos.d/backs
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backs&>/dev/null
for i in "${epel_yum_huawei[@]}";do
curl -o /etc/yum.repos.d/CentOS-Base-"${huawei_cloud}".repo "${i}"&>/dev/null
done
for j in "${epel_yum_aliyun[@]}";do
if [[ "${j}" =~ "Centos" ]];then
curl -o /etc/yum.repos.d/CentOS-Base-"${aliyun_cloud}".repo "${j}"&>/dev/null
sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base-"${aliyun_cloud}".repo
fi
done
#for k in "${epel_yum_163[@]}";do
# if [[ "${k}" =~ "CentOS" ]];then
# curl -o /etc/yum.repos.d/CentOS-Base-"${wy163_cloud}"-epel.repo "${k}"&>/dev/null
# yum clean all&>/dev/null && yum makecache&>/dev/null
# fi
#done
elif [ "${OS_RELEASE}" == "ubuntu" ];then
cp -a /etc/apt/sources.list /etc/apt/sources.list.bak
sed -i "s@http://.*archive.ubuntu.com@http://mirrors.huaweicloud.com@g" /etc/apt/sources.list
sed -i "s@http://.*security.ubuntu.com@http://mirrors.huaweicloud.com@g" /etc/apt/sources.list
apt-get update&>/dev/null
elif [ "${OS_RELEASE}" == "debian" ];then
cp -a /etc/apt/sources.list /etc/apt/sources.list.bak
sed -i "s@http://ftp.debian.org@https://mirrors.huaweicloud.com@g" /etc/apt/sources.list
sed -i "s@http://security.debian.org@https://mirrors.huaweicloud.com@g" /etc/apt/sources.list
sed -i 's/deb.debian.org/mirrors.huaweicloud.com/g' /etc/apt/sources.list.d/debian.sources
apt-get install apt-transport-https ca-certificates&>/dev/null && apt-get update
elif [ "${OS_RELEASE}" == "fedora" ];then
mv /etc/yum.repos.d/fedora.repo /etc/yum.repos.d/fedora.repo.backup
mv /etc/yum.repos.d/fedora-updates.repo /etc/yum.repos.d/fedora-updates.repo.backup
for i in "${epel_yum_aliyun}";do
if [[ "${i}" =~ "fedora" ]];then
curl -o /etc/yum.repos.d/fedora-"${aliyun_cloud}".repo "${i}"&>/dev/null
curl -o /etc/yum.repos.d/fedora-updates-"${aliyun_cloud}".repo "${i}"&>/dev/null
yum clean all&>/dev/null && yum makecache&>/dev/null
fi
done
for j in "${epel_yum_163}";do
if [[ "${j}" =~ "fedora" ]];then
curl -o /etc/yum.repos.d/fedora-"${wy163_cloud}".repo "${j}"&>/dev/null
curl -o /etc/yum.repos.d/fedora-updates-"${wy163_cloud}".repo "${j}"&>/dev/null
yum clean all&>/dev/null && yum makecache&>/dev/null
fi
done
fi
;;
2)
echo "暂时先不想写,感觉没什么必要脚本挂本地镜像"
;;
*)
echo -e "\033[31m输入错误,请重新输入\033[0m"
esac
}
ip_config=$(ifconfig | grep inet| awk '{print $2}' | sed -nr 's/^([0-9]{3}\W)([0-9]{3}\W)([0-9]{1,3}\W)([0-9]{3})/\1\2\3\4/p')
# 4.配置时间ntp服务
configure_ntp_service(){
echo -e "\033[32m======================配置时间ntp服务======================\033[0m"
if [ -f /etc/os-release ];then
if [[ "${OS_RELEASE}" == "centos" ]];then
yum -y install chrony&>/dev/null && systemctl enable --now chronyd&>/dev/null
IFS='.' read -r oct1 oct2 oct3 oct4 <<< "${ip_config}"
sed -i '/driftfile/a \server ntp.aliyun.com iburst' /etc/chrony.conf
sed -i '/driftfile/a \server ntp1.aliyun.com iburst' /etc/chrony.conf
sed -i "/driftfile/a \allow ${oct1}.${oct2}.${oct3}.0/24" /etc/chrony.conf
systemctl restart chronyd&>/dev/null
elif [[ "${OS_RELEASE}" == "ubuntu" ]] || [[ "${OS_RELEASE}" == "debian" ]];then
cp /etc/ntp.conf{,.bak}
cat > /etc/ntp.conf << EOF
driftfile /var/lib/ntp/ntp.drift
leapfile /usr/share/zoneinfo/leap-seconds.list
statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable
restrict -4 default kod notrap nomodify nopeer noquery limited
restrict -6 default kod notrap nomodify nopeer noquery limited
restrict 127.0.0.1
restrict ::1
restrict source notrap nomodify noquery
server 0.uk.pool.ntp.org iburst
server 1.uk.pool.ntp.org iburst
server 2.uk.pool.ntp.org iburst
server 3.uk.pool.ntp.org iburst
server 127.127.1.0 #local clock
fudge 127.127.1.0 stratum 10
EOF
fi
fi
if [ -f /etc/os-release ];then
yum -y install chrony&>/dev/null && systemctl start chronyd&>/dev/null && systemctl enable chronyd&>/dev/null
IFS='.' read -r oct1 oct2 oct3 oct4 <<< "${ip_config}"
sed -i '/#server 3/a \server ntp.sjtu.edu.cn iburst' /etc/chrony.conf
sed -i '/server ntp/a \server ntp1.aliyun.com iburst' /etc/chrony.conf
sed -i "/server ntp1/a \allow ${oct1}.${oct2}.${oct3}.0/24" /etc/chrony.conf
systemctl restart chronyd&>/dev/null
fi
}
# 5.系统加固配置
system_reinforcement_configure(){
echo -e "\033[32m======================系统加固配置======================\033[0m"
# 设置口令锁定
sed -i '/pam_tally2.so/s/^/#/g' /etc/pam.d/system-auth
sed -i '/pam_env.so/a \auth required pam_tally2.so deny=5 unlock_time=300 onerr=fail even_deny_root root_unlock_time=100' /etc/pam.d/system-auth
sed -i '/pam_permit.so/i \account required pam_tally2.so' /etc/pam.d/system-auth
#设置密码复杂度
sed -i '/pam_cracklib.so/s/^/#/g' /etc/pam.d/system-auth
sed -i '/pam_permit.so/a \password requisite pam_cracklib.so minlen=12 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1 enforce_for_root' /etc/pam.d/system-auth
#设置密码更新时间
sed -i '/PASS_/s/^/#/g' /etc/login.defs
sed -i '/automatic uid/i \PASS_MAX_DAYS 90' /etc/login.defs
sed -i '/automatic uid/i \PASS_MIN_DAYS 10' /etc/login.defs
sed -i '/automatic uid/i \PASS_MIN_LEN 5' /etc/login.defs
sed -i '/automatic uid/i \PASS_WARN_AGE 7' /etc/login.defs
# 删除无用用户
other_user=(lp sync halt news uucp operator games gopher smmsp nfsnobody nobody)
usernum=$((${#other_user[@]}-1))
for (( i=0;i<="${usernum}";i++ ));do
echo "删除的用户为: ${other_user[$i]}"
userdel "${other_user[$i]}"
done
# ssh连接超时时间
client_ssh_timeout=$(cat /etc/ssh/sshd_config | awk '{if($1 == "ClientAliveInterval")print NR}')
client_ssh_timeout_config_second="ClientAliveInterval 600"
if [ -n "${cleant_ssh_timeout}" ];then
sed -i '${client_ssh_timeout} c ${client_ssh_timeout_config_second}' /etc/ssh/sshd_config
else
echo "${client_ssh_timeout_config_second}" >> /etc/ssh/sshd_config
fi
systemctl restart sshd
#禁止IP路由
for f in /proc/sys/net/ipv4/conf/*/accept_source_route
do
echo 0 > $f
done
echo "" >> /etc/rc.local
echo "for f in /proc/sys/net/ipv4/conf/*/accept_source_route
do
echo 0 > \$f
done" >> /etc/rc.local
#设置登陆超时
sed -i '/TMOUT/s/^/#/g' /etc/profile
echo "TMOUT=300" >>/etc/profile
echo "export TMOUT" >>/etc/profile
#设置用户文件默认权限
sed -i 's/umask 022/umask 027/g' /etc/profile
sed -i 's/umask 002/umask 027/g' /etc/profile
sed -i 's/umask 022/umask 027/g' /etc/bashrc
sed -i 's/umask 002/umask 027/g' /etc/bashrc
source /etc/profile && source /etc/bashrc
#ulimit优化
echo "" >> /etc/security/limits.conf
echo "* soft nproc 65535" >> /etc/security/limits.conf
echo "* hard nproc 65535" >> /etc/security/limits.conf
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
# 删除潜在危险文件
find_warning_file=$(find / -name .rhosts && find / -name .netrc && find / -name hosts.equiv)
warning_file_list=()
if [ -n "${find_warning_file}" ];then
warning_file_list+=("${find_warning_file}")
fi
for i in "${warning_file_list[@]}"
do
mv $i $i.bak
done
#关闭无关服务自启,需重启生效
/sbin/chkconfig --level 2345 avahi-daemon off
/sbin/chkconfig --level 2345 acpid off
/sbin/chkconfig --level 2345 auditd off
/sbin/chkconfig --level 2345 atd off
/sbin/chkconfig --level 2345 bluetooth off
/sbin/chkconfig --level 2345 cpuspeed off
/sbin/chkconfig --level 2345 cups off
/sbin/chkconfig --level 2345 hidd off
/sbin/chkconfig --level 2345 hplip off
/sbin/chkconfig --level 2345 ip6tables off
/sbin/chkconfig --level 2345 iptables off
/sbin/chkconfig --level 2345 isdn off
/sbin/chkconfig --level 2345 kudzu off
/sbin/chkconfig --level 2345 libvirtd off
/sbin/chkconfig --level 2345 lm_sensors off
/sbin/chkconfig --level 2345 lvm2-monitor off
/sbin/chkconfig --level 2345 mcstrans off
/sbin/chkconfig --level 2345 mdmonitor off
/sbin/chkconfig --level 2345 modclusterd off
/sbin/chkconfig --level 2345 nfslock off
/sbin/chkconfig --level 2345 nfs off
#/sbin/chkconfig --level 2345 ntpd off
/sbin/chkconfig --level 2345 openibd off
/sbin/chkconfig --level 2345 pcscd off
/sbin/chkconfig --level 2345 portmap off
/sbin/chkconfig --level 2345 restorecond off
/sbin/chkconfig --level 2345 ricci off
/sbin/chkconfig --level 2345 rpcgssd off
/sbin/chkconfig --level 2345 rpcbind off
/sbin/chkconfig --level 2345 rpcidmapd off
/sbin/chkconfig --level 2345 sendmail off
/sbin/chkconfig --level 2345 postfix off
/sbin/chkconfig --level 2345 setroubleshoot off
/sbin/chkconfig --level 2345 smartd off
/sbin/chkconfig --level 2345 xend off
/sbin/chkconfig --level 2345 xendomains off
/sbin/chkconfig --level 2345 yum-updatesd off
/sbin/chkconfig --level 2345 portreserve off
/usr/bin/systemctl stop irqbalance.service
/usr/bin/systemctl stop abrt*.service
/usr/bin/systemctl stop kdump.service
/usr/bin/systemctl stop tuned.service
/usr/bin/systemctl stop sysstat.service
/usr/bin/systemctl disable irqbalance.service
/usr/bin/systemctl disable abrt*.service
/usr/bin/systemctl disable kdump.service
/usr/bin/systemctl disable tuned.service
/usr/bin/systemctl disable sysstat.service
}
# 6. 设置内核参数及历史命令
kernel_parameter_history_entry(){
echo -e "\033[32m======================设置内核参数及历史命令======================\033[0m"
# 设置路由转发
ip_forward=$(cat /proc/sys/net/ipv4/ip_forward)
if [ $ip_forward -ne 1 ];then
echo "1" >> /proc/sys/net/ipv4/ip_forward
else
echo ""
fi
chk_nf=`cat /etc/sysctl.conf | grep conntrack |wc -l`
if [ $chk_nf -eq 0 ];then
cat >>/etc/sysctl.conf<<EOF
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.ip_local_port_range = 4000 65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 0
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_orphans = 16384
net.netfilter.nf_conntrack_max = 25000000
net.netfilter.nf_conntrack_tcp_timeout_established = 180
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120
EOF
sysctl -p
else
echo "优化项已存在。"
fi
source /etc/init.d/functions
action "内核调优完成" /bin/true
echo "==========================================================="
sleep 2
# 临时关闭查看历史命令
export HISTSIZE=0
export HISTFILESIZE=0
# 永久关闭查看历史命令
sed -i '/HISTSIZE/s/^/#/g' /etc/profile
sed -i '/#HISTSIZE/a \export HISTSIZE=0' /etc/profile
sed -i '/#HISTSIZE/a \export HISTFILESIZE=0' /etc/profile
sed -i '/#HISTSIZE/a \HISTTIMEFORMAT="%F %T"' /etc/profile
source /etc/profile
}
#7. 安装常用工具
install_software_plug(){
echo -e "\033[32m======================安装常用工具======================\033[0m"
software_plug_list=(wget curl git unzip vim nano net-tools iproute telnet nmap gzip bzip2 zip tree ncdu openssh openssh-server htop iftop istop sysstat fail2ban)
software_plug_devel_list=(Development Tools gcc make cmake)
for i in "${software_plug_list[@]}"
do
yum -y install $i
done
for j in "${software_plug_devel_list[@]}"
do
yum -y install $j
done
}
# 8. 配置ssh加速
configure_ssh_accelerate(){
echo -e "\033[32m======================配置ssh登录速度======================\033[0m"
sed -i 's#^GSSAPIAuthentication yes$#GSSAPIAuthentication no#g' /etc/ssh/sshd_config
sed -i 's/#UseDNS yes/UseDNS no/g' /etc/ssh/sshd_config
systemctl restart sshd.service
echo "#grep GSSAPIAuthentication /etc/ssh/sshd_config"
grep GSSAPIAuthentication /etc/ssh/sshd_config
echo "#grep UseDNS /etc/ssh/sshd_config"
grep UseDNS /etc/ssh/sshd_config
source /etc/init.d/functions
action "完成加快ssh登录速度" /bin/true
echo "==========================================================="
sleep 2
}
disable_selinux_firewalld
system_reinforcement_configure
kernel_parameter_history_entry
configuration_yum_network
install_software_plug
configure_ntp_service
configure_ssh_accelerate