服务器上线之一键优化Linux服务器性能
以下是一个简单的Shell脚本,用于执行服务器上线优化的一些基本步骤。请注意,这个脚本是基于一个通用的Linux服务器配置,您可能需要根据您的具体需求和环境进行调整。
功能如下:
1.关闭SELINUX2.修改默认启动级别为33.关闭不必要的开机启动项4.sshd优化5.时间同步服务6.修改系统连接数7.内核参数优化10.退出
脚本如下:
#!/bin/bash
function ChoiceInterface(){clearcat <<EOF+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 欢迎使用服务器上线优化功能 ++ 请选择优化操作 ++ 1.关闭SELINUX ++ 2.修改默认启动级别为3 ++ 3.关闭不必要的开机启动项 ++ 4.sshd优化 ++ 5.时间同步服务 ++ 6.修改系统连接数 ++ 7.内核参数优化 ++ ++ 10.退出 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++EOF}#定义数字检测函数 判断是否输入回车或者非数字字符 承担解包作用function NumberLegalChecker(){num_wait2check=$1num_wait2check_unpacked=`echo ${num_wait2check}|sed 's/[0-9]//g'`#如果匹配到连续模式连接符号 -if [[ ${num_wait2check_unpacked} == "-" ]];thenstart_num=`echo $num_wait2check|awk -F"-" '{print $1}'`end_num=`echo $num_wait2check|awk -F"-" '{print $2}'`#解压连续数字序列unpacked_numbers=`eval echo "{$start_num..$end_num}"`#打印数字 返回结果echo ${unpacked_numbers}elif [[ ! -n ${num_wait2check} || -n ${num_wait2check_unpacked} ]];thenecho -e "\033[34;5m输入错误,请重新输入!!!\033[0m"return 1elseecho ${num_wait2check}fi}#定义纯数字检测函数function PureNumberLegalChecker(){num=$1num_filtered=`echo ${num}|sed 's/[0-9]//g'`if [[ -n $num && ! -n $num_filtered ]];thenreturn 0elseecho -e "\033[34;5m输入错误,请重新输入!!!\033[0m"return 1fi}#定义继续优化 返回主菜单 退出 交互函数function QuitOrReturn2Mian(){while true;doread -p "`echo -e '\033[33m请选择返回主菜单/退出 (M/Q): \033[0m'`" input_choiceif [[ ! -n ${input_choice} ]];thenecho "输入错误,请重新选择!!!"elif [[ ${input_choice} == [Mm] ]]; thenreturnelif [[ ${input_choice} == [Qq] ]]; thenecho -e "\033[31;7m再见!!! \033[0m"exitfidone}#定义禁用selinux函数function DisableSELINUX(){selinux_config_file=/etc/selinux/configecho "验证SELINUX配置文件。。。"if [[ -f ${selinux_config_file} ]] ; thenecho "配置文件验证成功!"elseecho "配置文件验证失败 "return 1fi#获取目前selinux状态se_status1=`awk -F"=" '/^SELINUX=/ {print $2}' /etc/selinux/config`se_status2=`getenforce`if [[ $se_status1 != 'disabled' ]]; thensed -i 's/\(SELINUX=\)enforcing/\1disabled/g' $selinux_config_fileecho "修改了SELINUX配置文件,已置为Disabled,需要重启服务器"fiif [[ $se_status2 == 'Enforcing' ]]; thensetenforce 0 && echo "已设置临时的SELINUX状态为permissive"fiecho "SELINUX已经成功修改完成"cmd=getenforceecho "执行命令: $cmd"echo "命令结果:`eval $cmd`"cmd="grep -e '^SELINUX=' ${selinux_config_file}"echo "执行命令: $cmd"echo "命令结果:`eval $cmd`"QuitOrReturn2Mian}#修改默认启动级别函数function ModifyDefaultRunlevel(){inittab_config_file=/etc/inittabecho "验证inittab配置文件。。。"if [[ -f ${inittab_config_file} ]] ; thenecho "配置文件验证成功!"elseecho "配置文件验证失败 "return 1fised -i 's/\(id:\)[0-9]\(:initdefault:\)/\13\2/g' ${inittab_config_file}echo "默认启动级别已经成功修改完成"cmd="grep -e '^id:[0-9]:initdefault:' ${inittab_config_file}"echo "执行命令: $cmd"echo "命令结果:`eval $cmd`"QuitOrReturn2Mian}function AutostartOptimization(){#获得目前开机3级别启动项清单current_autostart_inventory=(`chkconfig --list | grep 3:on | awk '{print $1}'`)#初始化用户输入选择序列号的存放的数组user_choice_inventory=()#定义打印开机启动项函数function InactivePrintAutostartItem(){clearfor order_number in `seq 0 $(( ${#current_autostart_inventory[@]} - 1 ))`; dochoice_boolen=falsefor choice_number in ${user_choice_inventory[@]}; doif [[ ${order_number} -eq ${choice_number} ]]; thenchoice_boolen=truefidoneif ${choice_boolen};thenprintf "\033[41;36m%-3s-->%-17s\033[0m" ${order_number} ${current_autostart_inventory[${order_number}]}elseprintf "%-3s-->%-17s" ${order_number} ${current_autostart_inventory[${order_number}]}fiif [[ $(((${order_number}+1)%4)) -eq 0 ]];thenprintf "\n"fidoneechoecho -e "已选择开机启动项 \033[41;36m \033[0m"#打印非法选项if [[ ${#illegal_user_choice_inventory[@]} -gt 0 ]];thenecho -e "\033[35;1m未操作开机启动项 ${illegal_user_choice_inventory[*]} \033[0m"fi}#定义禁止启动项函数function disable_startup(){#首先禁止所有for item in ${current_autostart_inventory[@]};do#echo "执行命令: chkconfig --level 3 $item off"chkconfig --level 3 $item offdone#开启需要的开机启动项for allow_autostart_number in ${user_choice_inventory[@]};doecho "执行命令: chkconfig --level 3 ${current_autostart_inventory[${allow_autostart_number}]} on"chkconfig --level 3 ${current_autostart_inventory[${allow_autostart_number}]} ondoneecho "查看现在的启动项列表"cmd="chkconfig --list | grep 3:on"echo "执行命令: $cmd"echo -e "命令结果: \n`eval $cmd`"}#主循环体while true; doInactivePrintAutostartItem#定义验证输入合法性循环体while true;doecho "请选择需要开机自动启动的项(未选择的将被禁止启动,请输入每个服务所代表的数字)"read -p "支持多选,支持连续模式,如3-11,请输入: " allow_autostart_variables#检验输入是否为空while [[ ! -n ${allow_autostart_variables} ]];doecho "请选择需要开机自动启动的项(未选择的将被禁止启动,请输入每个服务所代表的数字)"read -p "支持多选,请输入: " allow_autostart_variablesdone#先取出输入的数组 判断是否输入回车或者非数字字符 修改为匹配大多数字符 支持-连接符选择连续的数字#allow_autostart_unpacked_inventory=(`echo ${allow_autostart_variables} | sed 's/[[:punct:]]/\ /g'`)allow_autostart_inventory=(`echo ${allow_autostart_variables} |sed 's/[][!#$%&*+,./:;<=>?@\^_{|}~]/\ /g'`)#初始化解压之后的数组allow_autostart_unpacked_inventory=()#遍历输入的选择数组for single_allow_autostart_item in ${allow_autostart_inventory[*]}; do#检测数字是否合法 非法报错result_after_num_checker=`NumberLegalChecker ${single_allow_autostart_item}`if [[ -n $result_after_num_checker ]];then#如果结果不为空 追加到解压之后的数组allow_autostart_unpacked_inventory=(`echo ${allow_autostart_unpacked_inventory[*]}" "$result_after_num_checker`)elsecontinuefidone#定义一个开机启动项的序列号数组autostart_number_inventory=(`eval echo {0..$(( ${#current_autostart_inventory[@]} - 1 ))}`)#求数组并集 差集legal_autostart_num_inventory=(`echo ${allow_autostart_unpacked_inventory[*]} ${autostart_number_inventory[*]} | sed 's/\ /\n/g' | sort |uniq -d |tr "\n" "\ "`)illegal_autostart_num_inventory=(`echo ${allow_autostart_unpacked_inventory[*]} ${autostart_number_inventory[*]} ${autostart_number_inventory[*]} | sed 's/\ /\n/g' | sort |uniq -u|tr "\n" "\ "`)#把每次的结果叠加user_choice_inventory=(`echo ${legal_autostart_num_inventory[*]}" "${user_choice_inventory[*]}`)illegal_user_choice_inventory=(${illegal_autostart_num_inventory[@]})InactivePrintAutostartItembreakdone#定义是否终止 或继续选择循环体while true;doread -p "是否继续选择启用的开机启动项 是/否(应用)/删除(Y/N/D): " con_or_applyif [[ ! -n ${con_or_apply} ]];thenecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"elif [[ ${con_or_apply} == [Yy] ]];thenbreakelif [[ ${con_or_apply} == [Nn] ]];thenread -p "是否应用 是/否(Y/N): " yes_no_apply#是否应用所选择的启动服务项while true;doif [[ ! -n ${yes_no_apply} ]];thenecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"elif [[ ${yes_no_apply} == [Yy] ]];thenecho "开始执行应用所选择的启动项"disable_startupbreakelif [[ ${yes_no_apply} == [Nn] ]];thenbreakelseecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"firead -p "是否应用 是/否(Y/N): " yes_no_applydoneQuitOrReturn2Mianreturnelif [[ ${con_or_apply} == [Dd] ]];thenread -p "清输入要移除的启动项序列号: " require2remove_num_variables#判断输入是否非空while [[ ! -n ${require2remove_num_variables} ]];doread -p "清输入要移除的启动项序列号(支持多选 支持连接符-): " require2remove_num_variablesdone#读取输入的多选到数组removing_num_inventory=(`echo ${require2remove_num_variables} | sed 's/[][!#$%&*+,./:;<=>?@\^_{|}~]/\ /g'`)#初始化解包后的清单数组removing_num_unpacked_inventory=()for single_removing_numt_item in ${removing_num_inventory[*]}; do#检测数字是否合法 非法报错result_after_num_checker=`NumberLegalChecker ${single_removing_numt_item}`if [[ -n $result_after_num_checker ]];then#如果结果不为空 追加到解压之后的数组removing_num_unpacked_inventory=(`echo ${removing_num_unpacked_inventory[*]}" "$result_after_num_checker`)elsecontinuefidone#求并集差集 需要删除的数组和已经选择的数组legal_removing_inventory=(`echo ${removing_num_unpacked_inventory[*]} ${user_choice_inventory[*]} | sed 's/\ /\n/g' | sort |uniq -d |tr "\n" "\ "`)illegal_removing_inventory=(`echo ${removing_num_unpacked_inventory[*]} ${user_choice_inventory[*]} ${user_choice_inventory[*]} | sed 's/\ /\n/g' | sort |uniq -u|tr "\n" "\ "`)#在一选择数组中移除需要移除的合法序列数user_choice_inventory=(`echo ${legal_removing_inventory[*]} ${user_choice_inventory[*]} | sed 's/\ /\n/g' |sort|uniq -u | tr "\n" "\ "`)illegal_user_choice_inventory=(${illegal_removing_inventory[@]})InactivePrintAutostartItemecho "已成功移除 ${legal_removing_inventory[*]}"elseecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"fidonedone}function SshOptimization(){ssh_config_file=/etc/ssh/sshd_configecho "验证sshd配置文件。。。"if [[ -f ${ssh_config_file} ]] ; thenecho "配置文件验证成功!"elseecho "配置文件验证失败 "return 1fi#定义禁用DNS反查询的函数function DisableUseDNS(){#if [[ `grep -c -e "#\ *UseDNS\ *yes" ${ssh_config_file}` -eq 1 && `grep -c -e "[^#]UseDNS" ${ssh_config_file}` -eq 0 ]];thensed -i 's/#*\(UseDNS\ \)yes/\1no/g' ${ssh_config_file}#fised -i 's/\(GSSAPIAuthentication\ \)yes/\1no/g' ${ssh_config_file}cmd="grep UseDNS ${ssh_config_file}"echo "执行命令: $cmd"echo "执行结果: `eval $cmd`"cmd="grep GSSAPIAuthentication ${ssh_config_file}"echo "执行命令: $cmd"echo "执行结果: `eval $cmd`"}#定义更改ssh端口号函数function ChangeSshPort(){port=$1echo "正在更改SSH默认端口号。。。"sed -i "s/#*\(Port\ *\)[0-9]*$/\1$port/g" ${ssh_config_file}cmd="grep -E ^Port ${ssh_config_file}"echo "执行命令: $cmd"echo "执行结果: `eval $cmd`"}#定义更改是否允许root登录函数function PermitRootLogin(){permit_root_login=$1echo "正在修改是否允许root ssh登录。。。"sed -i "s/#*\(PermitRootLogin\ *\).*$/\1$permit_root_login/g" ${ssh_config_file}cmd="grep -E ^#*PermitRootLogin ${ssh_config_file}"echo "执行命令: $cmd"echo "执行结果: `eval $cmd`"}#循环判断是否启用SSH加速function InteractiveDisableUseDNS(){read -p "是否启用SSH加速 是/否 (Y/N): " speedup_yes_nowhile true;doif [[ ! -n ${speedup_yes_no} ]];thenecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"elif [[ ${speedup_yes_no} == [Yy] ]];thenecho "启用SSH加速功能"DisableUseDNSreturnelif [[ ${speedup_yes_no} == [Nn] ]];thenreturnelseecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"firead -p "是否启用SSH加速 是/否 (Y/N): " speedup_yes_nodone}#循环判断是否修改SSH端口function InteracticeChangeSshPort(){read -p "是否修改SSH端口 是/否 (Y/N): " sshport_yes_no#循环判断输入合法性while true;do#如果输入空的字符串if [[ ! -n ${sshport_yes_no} ]];thenecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"elif [[ ${sshport_yes_no} == [Yy] ]];thenwhile true;doread -p "请输入要修改的端口号:" port#判断输入的数字是否合法while ! PureNumberLegalChecker ${port};doread -p "请输入要修改的端口号:" portdone#判断输入是否在合法端口范围内if [[ $port -gt 0 && $port -lt 65535 ]];thenknown_service_filter=`grep -E "[[:space:]]$port/[tcp|udp]" /etc/services`if [[ -n ${known_service_filter} ]];thenecho -e "这个端口已经有服务在使用,\n ${known_service_filter}\n"read -p "是否继续使用这个端口? (Y/N)" port_confirm#判断是否继续使用这个端口while true;doif [[ ! -n ${port_confirm} ]];thenecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"elif [[ ${port_confirm} == [Yy] ]];thenChangeSshPort $portreturnelif [[ ${port_confirm} == [Nn] ]];thenbreakelsecho -e "\033[34;5m输入错误,请重新输入!!!\033[0m"continuefidoneelseChangeSshPort $portreturnfielseecho -e "\033[34;5m输入错误,端口范围需在0~65535 请重新输入!!!\033[0m"fidoneelif [[ ${sshport_yes_no} == [Nn] ]];thenreturnelseecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"firead -p "是否修改SSH端口 是/否 (Y/N): " sshport_yes_nodone}#循环判断是否允许Root ssh登录function InteractivePermitRootLogin(){read -p "是否允许Root通过SSH登录 是/否 (Y/N): " root_login_yes_nowhile true;doif [[ ! -n ${root_login_yes_no} ]];thenecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"elif [[ ${root_login_yes_no} == [Yy] ]];thenecho "允许root登录"PermitRootLogin "yes"returnelif [[ ${root_login_yes_no} == [Nn] ]];thenecho "禁止root登录"PermitRootLogin "no"returnelseecho -e "\033[34;5m输入错误,请重新选择!!!\033[0m"firead -p "是否允许Root通过SSH登录 是/否 (Y/N): " root_login_yes_nodone}#执行定义的函数InteractiveDisableUseDNSInteracticeChangeSshPortInteractivePermitRootLogin/etc/init.d/sshd restart > /dev/nullQuitOrReturn2Mian}function TimeSynchronization(){echo "此功能待开发"QuitOrReturn2Mian}function ModifySystemResourceLimit(){echo "此功能待开发"QuitOrReturn2Mian}function KernelParameterOptimization(){echo "此功能待开发"QuitOrReturn2Mian}#判断是否是root用户运行if [[ `id -u` -ne 0 ]];thenecho "必须以root身份运行此脚本!"exit 1fiwhile ChoiceInterface;doread -p "请输入你的选择:" choice#判断是否输入回车或者非数字字符NumberLegalChecker ${choice} || continuecase $choice in1)DisableSELINUXcontinue;;2)ModifyDefaultRunlevelcontinue;;3)AutostartOptimizationcontinue;;4)SshOptimizationcontinue;;5)TimeSynchronizationcontinue;;6)ModifySystemResourceLimitcontinue;;7)KernelParameterOptimizationcontinue;;10)exit 0;;*)echo "选择错误,请重新选择!"continue;;esacdone
保存此脚本为init_system.sh,并通过以下命令运行它:
chmod +x init_system.sh./init_system.sh

请记住,这只是一个示例脚本,实际部署时需要根据具体情况进行调整。在生产环境中,优化步骤可能会更加复杂,并且需要详细的规划和测试。
以上,既然看到这里了,如果觉得不错,随手点个赞、在看、转发三连吧。

















![电脑问题4[非华为电脑安装华为电脑管家华为荣耀手机多屏协助]](https://i-blog.csdnimg.cn/direct/5dde911f252948238abcc45f10e3e0be.png)

