@Linux Centos系统优化与内核参数优化详解

一、更改yum源

# 更改base源为阿里云的源
[root@hzl ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo


# 更改添加epel源
[root@hzl ~]# yum install -y epel-release

二、常用工具安装

[root@hzl ~]# yum install -y  \
 tree telnet lrzsz wget ntpdate vim  nc namp dos2unix  tcpdump  expect sshpass elinks unzip \
 lsof net-tools iproute  bridge-utils \
 bind-utils nscd \
 gcc gcc-c++ make cmake libaio zlib-devel pcre-devel  \
 psmisclsof sysstat yum-utils 


#注:
lrzsz       #是上传下载的软件
sysstat     #是用来检测系统性能及效率的工具
net-tools   #没有ifconfig命令时候需要安装工具

三、关闭Selinux

[root@hzl ~]# sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
[root@hzl ~]# setenforce 0
[root@hzl ~]# getenforce 0
Permissive

四、关闭防火墙—清空iptables

1#关闭防火墙
[root@hzl ~]#systemctl stop firewalld.service          # 临时关闭irewalld防火墙
[root@hzl ~]#systemctl disable firewalld.service       # 加入不让其开机自启动
[root@hzl ~]#systemctl mask firewalld.service          # 配置不让其启动和设置开机自启动






2#清空iptables
# iptables –F                #清理防火墙规则
# iptables –L                #查看防火墙规则
#/etc/init.d/iptables save   #保存防火墙配置信息


[root@hzl hzl]#  iptables -F
[root@hzl hzl]#  iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination




3)iptables防火墙配置
1#安装iptables防火墙
[root@hzl ~]#yum install iptables-services
.......
...
#更改iptables配置文件后执行
[root@hzl ~]# service iptables save


2#编辑iptables防火墙配置
[root@hzl ~]# vi /etc/sysconfig/iptables      #编辑防火墙配置文件
一个完整的配置文件:(在你运行完save中间插入下面的规则)
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
:wq! #保存退出



3#启动
[root@hzl ~]#systemctl start iptables.service  #开启
[root@hzl ~]#systemctl enable iptables.service #设置防火墙开机启动

【iptables防火墙脚本】

先必须安装iptables
【iptables详解】

[root@hzl ~]# cat iptables.sh
#!/bin/bash

IPT=`which iptables`
$IPT -F
$IPT -X
$IPT -P INPUT DROP
$IPT -P FORWARD ACCEPT 
$IPT -P OUTPUT ACCEPT
$IPT -N syn-flood

##本地回环 内网允许任何
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -m state --state NEW -s 10.0.0.0/8 -j ACCEPT


# ssh 端口开放 任何IP
$IPT -A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT


# 根据需求填写相应的端口
$IPT -A INPUT -p tcp -m multiport --dports 80,8087,89 -j ACCEPT


# zabbix监控地址
$IPT -A INPUT -p tcp -s zabbix.ip -m state --state NEW -m tcp --dport 10050 -j ACCEPT


# ICMP 规则控制
$IPT -A INPUT -p icmp -m limit --limit 100/sec --limit-burst 100 -j ACCEPT
$IPT -A INPUT -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT


# DOS防护
$IPT -A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -j syn-flood
$IPT -A INPUT -j REJECT --reject-with icmp-host-prohibited
$IPT -A syn-flood -p tcp -m limit --limit 3/sec --limit-burst 6 -j RETURN
$IPT -A syn-flood -j REJECT --reject-with icmp-port-unreachable

五、设置中文字符

[root@hzl ~]# echo "LANG=\"zh_CN.UTF-8\"" >/etc/locale.conf

六、系统的时间校准

## 创建/etc/sysconfig/clock文件
[root@hzl ~]# cat >>/etc/sysconfig/clock <<EOF
ZONE="Asia/Shanghai"
UTC=false
ARC=false
EOF



# 强制让其与/etc/localtime文件进行软链接
[root@hzl ~]# ln -sf /usr/share/zoneinfo/Asia/Shanghai    /etc/localtime



# 同步阿里云时间
[root@hzl ~]#ntpdate ntp1.aliyun.com



# 设置硬件时间和系统时间一致并校准
[root@hzl ~]# /sbin/hwclock --systohc 
[root@hzl ~]# hwclock --show
1>#输出当前时间
date +"%Y-%m-%d %H:%M:%S"       # 2018-06-08 14:05:08输出指定时间

#参数:
-d<字符串>#显示字符串所指的日期与时间,字符串前后必须加上双引号;
date -d "1 day ago" +"%Y-%m-%d"   2018-06-07    #ago是昨天
date -d "1 day" +"%Y-%m-%d"       2018-06-09    #不加参数是明天

#实列:
[root@hzl ~]# date -d "1 day ago" +"%Y-%m-%d"    #表示昨天
2021-07-30
[root@hzl ~]# date -d "1 day" +"%Y-%m-%d"        #表示明天
2021-08-01



2>使用数字表示前后多少天的加减
date +%Y%m%d #显示前天年月日 
date -d "+1 day" +%F   #显示前一天的日期  ( %F与%Y-%m-%d相同)
date -d "-1 day" +%F   #显示后一天的日期   
date -d "-1 month" +F  #显示上一月的日期 
date -d "+1 month" +F  #显示下一月的日期 
date -d "-1 year" +F   #显示前一年的日期 
date -d "+1 year" +F   #显示下一年的日期



3>#设置时间
-s<字符串>:根据字符串来设置日期与时间,字符串前后必须加上双引号; 
date -s 01:01:01              #设置具体时间,不会对日期做更改 
date -s "01:01:01 2012-05-23" #这样可以设置全部时间 
date -s "01:01:01 20120523"   #这样可以设置全部时间 
date -s "2012-05-23 01:01:01" #这样可以设置全部时间 
date -s "20120523 01:01:01"   #这样可以设置全部时间

【操作系统时间定时更新脚本】

[root@hzl ~]# cat /root/update_os_time.sh

#!/bin/bash

# Define variables
RETVAL=0
Ntp_server=(
ntp.aliyun.com
ntp1.aliyun.com
ntp2.aliyun.com
ntp3.aliyun.com
ntp4.aliyun.com
ntp5.aliyun.com
ntp6.aliyun.com
ntp7.aliyun.com
)
 


# Determine the user to execute
echo "执行的用户"
if [ $UID -ne $RETVAL ];then
   echo "Must be root to run scripts"
   exit 1
fi
 



# Load locall functions library
echo "函数调用"
[ -f /etc/init.d/functions ] && source /etc/init.d/functions
 
 

# Install ntpdate command
echo "安装ntpdate"
yum install ntpdate -y >/dev/null 2>&1
 



# for loop update os time
echo "更新操作系统时间"
for((i=0;i<${#Ntp_server[*]};i++))
do
    /usr/sbin/ntpdate ${Ntp_server[i]} >/dev/null 2>&1 &
    RETVAL=$?
    if [ $RETVAL -eq 0 ];then
       action "Update os time" /bin/true
       break
      else
       action "Update os time" /bin/false
       continue
    fi
done
 

echo "校对完毕"



# Scripts return values
exit $RTVAL
#加入定时任务
[root@hzl ~]# crontab -l
# Crond update os time. USER:hzl  TIME:2021-02-02
*/05 * * * * /bin/sh /root/update_os_time.sh >/dev/null 2>&1   #每隔5分钟更新一次系统时间

七、ssh服务优化

# 更改firewalld防火墙的ssh服务的端口为921
[root@hzl ~]# sed -i 's#22#921#g' /usr/lib/firewalld/services/ssh.xml



# ssh服务的优化如下
[root@hzl ~]# cat >>/etc/ssh/sshd_config<<EOF
Port 921
PermitRootLogin no
PermitEmptyPasswords no
UseDNS no                      #关闭DNS PTR反向查询
GSSAPIAuthentication no        #关闭GSSAPI身份验证
EOF



# 重启sshd服务
[root@hzl ~]# systemctl restart sshd.service

八、调整swap交换分区

# Centos swap文件说明
[root@hzl ~]# cat /proc/sys/vm/swappiness 
30   

#不同的操作系统这个值是不一样的哈,oracle linux是60,我这里是CentOS linux;
#30的意思是:当服务器的物理内存被用到100%-30%=70%时,就让其使用swap交换页面(分区)了
#如果设置为0,则表示不使用swap交换页面(分区)






# swap优化使用
[root@hzl ~]# chattr -i /etc/sysctl.conf
[root@hzl ~]# echo "vm.swappiness=10" >>/etc/sysctl.conf
[root@hzl ~]# chattr +i /etc/sysctl.conf
[root@hzl ~]# sysctl -p

# 当物理内存使用到90%时,才使用swap交换分区
# 当服务器的物理内存用到80%的时候就要进行报警了

九、yum源基础软件的使用

在这里插入图片描述

检查命令(如:检查ifconfig属于哪个安装包)

[root@hzl opt]# yum provides ifconfig  
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.bfsu.edu.cn
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
docker-ce-stable/7/x86_64/filelists_db                                                                                                                                  |  26 kB  00:00:00     
net-tools-2.0-0.25.20131004git.el7.x86_64 : Basic networking tools
源    :@base
匹配来源:
文件名    :/usr/sbin/ifconfig


#安装yum-config-manager工具
[root@hzl ~]# yum -y install yum-utils

#显示仓库信息
[root@hzl ~]# yum-config-manager

【本地仓库创建yum源】

1#安装yum-config-manager工具
[root@hzl /]# yum -y install yum-utils




2#建立本地仓库
[root@hzl /]# mkdir hzl                
[root@hzl /]# cd /hzl/





3#创建本地仓库
[root@hzl hzl]# yum-config-manager --add-repo="file:///hzl"
已加载插件:fastestmirror
adding repo from: file:///hzl

[hzl]
name=added from: file:///hzl
baseurl=file:///hzl
enabled=1

[root@hzl hzl]# 🆗啦  简单吧






4#查看本地仓库
[root@hzl hzl]# ll /etc/yum.repos.d/  | grep hzl 
-rw-r--r--. 1 root root   67 731 14:08 hzl.repo
[root@hzl hzl]# cat /etc/yum.repos.d/hzl.repo 

[hzl]
name=added from: file:///hzl
baseurl=file:///hzl
enabled=1

[root@hzl hzl]# 

十、优化ulimit

[root@hzl hzl]# echo '* - nofile 65535' >> /etc/security/limits.conf
[root@hzl hzl]# cat /etc/security/limits.conf |egrep -v "^#|^$"
* - nofile 65535

十一、显示优化

默认的PS1内容为: PS1=’[\u@\h \W]$ ’ ,所以默认的提示符就是: [root@linux ~]#

1)# 设置ps1变量的显示   
PS1(是数字1而不是字母l),每个版本bash的PS1变量内的特殊符号可能有些小的差异,你可以先man bash 一下

FC4环境下默认的特殊符号所代表的意义:
    \d :代表日期,格式为weekday month date,例如:"Mon Aug 1"

    \H :完整的主机名称。例如:我的机器名称为:fc4.linux,则这个名称就是fc4.linux

    \h :仅取主机的第一个名字,如上例,则为fc4,.linux则被省略

    \t :显示时间为24小时格式,如:HH:MM:SS

    \T :显示时间为12小时格式

    \A :显示时间为24小时格式:HH:MM

    \u :当前用户的账号名称

    \v :BASH的版本信息

    \w :完整的工作目录名称。家目录会以 ~代替

    \W :利用basename取得工作目录名称,所以只会列出最后一个目录

    \# :下达的第几个命令

    \$ :提示字符,如果是root时,提示符为:# ,普通用户则为:$

-----------------------------------------------------------------------------------------------------------------------------------------

2)#设置ps1变量的颜色 (配置PS1变量使提示符成为彩色)PS1中配置字符序列颜色的格式为:   \[\e[F;Bm\]
 
    基本上是夹在 "\e["(转义开方括号)和 "m" 之间数字值。假如指定一个以上的数字代码,则用分号将他们分开。
    其中 F 为字体颜色,编号30~37; B 为背景色,编号40~47。
    可通过 \e[0m 关闭颜色输出;特别的,当B为1时,将显示加亮加粗的文字,请看下面的颜色表和代码表。
  
   #颜色表
      前景     背景     颜色
---------------------------------------
    30         40         黑色
    31         41         红色
    32         42         绿色
    33         43         黄色
    34         44         蓝色
    35         45         紫色
    36         46         青色
    37         47         白色

-----------------------------------------------------------------------------------------------------------------------------------------
3)颜色设置
[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\[\e[34;1m\]\u@\[\e[0m\]\[\e[32;1m\]\H\[\e[0m\] \[\e[31;1m\]\w\[\e[0m\]]\\$ "

1》更改添加到/etc/bashrc,注释掉原有的PS1,重载配置文件 source /etc/bashrc
在这里插入图片描述

2》使用xshell,并将连接段的字符集改成UTF-8在这里插入图片描述

十二、精简开机自启动服务

# 修改启动服务
systemctl            #是管制服务的主要工具,它整合了chkconfig 与 service功能于一体

systemctl is-enabled iptables.service     #查询防火墙是否开机启动
systemctl restart sshd                    #有可能不需要加service
systemctl is-enabled servicename.service  #查询服务是否开机启动
systemctl enable *.service                #开机运行服务
systemctl disable *.service               #取消开机运行
systemctl start *.service                 #启动服务
systemctl stop *.service                  #停止服务
systemctl restart *.service               #重启服务
systemctl reload *.service                #重新加载服务配置文件
systemctl status *.service                #查询服务运行状态
systemctl --failed                        #显示启动失败的服务

十三、锁定关键文件系统(文件加锁与去锁)

1#加锁,不可修改加锁文件
[root@hzl ~]# chattr +i /etc/passwd
[root@hzl ~]#  lsattr /etc/passwd
----i--------e-- /etc/passwd



2#去锁,可以修改文件
[root@hzl ~]# chattr -i /etc/passwd 
[root@hzl ~]# lsattr /etc/passwd   
-------------e-- /etc/passwd



3#使用chattr命令后,为了安全我们需要将其改名
mv /usr/bin/chattr /usr/bin/任意名称

【系统优化脚本】


#!/bin/bash


echo  "***** For newly installed systems********"
# ***** Have access to the Internet********
# ***** Root user execution**********



########## Define variables       #定义变量
---------------------------------------------------------------------------------------------------
RETVAL=0


Baidu_url="www.baidu.com"


Yum_soure="http://mirrors.aliyun.com/repo/Centos-7.repo"      ##  According to operating system version
         


Common_tools="tree telnet lrzsz wget ntp ntpdate vim net-tools \
              lsof nc namp dos2unix tcpdump gcc gcc-c++ make \
              cmake libaio zlib-devel pcre-devel psmisclsof \
              sysstat yum-utils"



Change_ssh_port="921"



Firewalld_ssh_file="/usr/lib/firewalld/services/ssh.xml"

-----------------------------------------------------------------------------------------------------------------------------------------
echo "开始系统更新"
########## Determine the user to execute   #需要执行的用户
echo "使用root用户执行"
sleep 1
if [ "$UID" -ne $RETVAL ];then
   echo "Must be root to run scripts"
   exit 1
fi





########## Load local functions    
echo "加载本地函数"
sleep 2
[ -f /etc/init.d/functions ] && source /etc/init.d/functions




 
########## Check Internet access
echo "检查网络"     
ping -c 2 $Baidu_url >/dev/null 2>&1
RETVAL=$?
if [ $RETVAL -eq 0 ];then
   action "Check internet access" /bin/true
  else
   action "Check internet access" /bin/false
   exit 1
fi




echo "yum源更改"
########## Change domestic yum sources
curl -o /etc/yum.repos.d/CentOS-Base.repo $Yum_soure >/dev/null 2>&1
RETVAL=$?
if [ $RETVAL -eq 0 ];then
   action "Change yum sources" /bin/true
  else
   action "Change yum sources" /bin/false
fi


########## Install common toolkits
echo "安装常用工具包"
sleep 1
yum install -y $Common_tools >/dev/null 2>&1
RETVAL=$?
if [ $RETVAL -eq 0 ];then
   action "Install common toolkits" /bin/true
  else
   action "Install common toolkits" /bin/false
fi



########## Empty version display
echo "显示空版本"
sleep 1
if [ -f /etc/issue  -a /etc/issue.net ];then
   >/etc/issue && >/etc/issue.net   
   RETVAL=$?
   if [ $RETVAL -eq 0 ];then
      action "Emty version display" /bin/true
   fi
  else
   echo "/etc/issue or /etc/issue.net is not exists"
fi





########## Disable selinux
echo "关闭 Selinux"

if [ -f /etc/selinux/config  ];then
   sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config &&
   setenforce 0
   RETVAL=$?
   if [ $RETVAL -eq 0  ];then
      action "Disable selinux" /bin/true
     else
      action "Disable selinux" /bin/false
   fi
fi






########## User password does not expire
echo "用户密码永久生效设置"
if [ -f /etc/login.defs ];then
   echo -e "\nPASS_MAX_DAYS   99999\nPASS_MIN_DAYS   0\nPASS_MIN_LEN    5\nPASS_WARN_AGE   7\n" >>/etc/login.defs
   RETVAL=$?
   if [ $RETVAL -eq 0  ];then
      action "Set user password not expire" /bin/true
     else
      action "Set user password not expire" /bin/false
   fi
fi






########## Command line history sav change
echo "命令历史记录更改"
sleep 1
echo -e "\nexport HISTSIZE=10\nexport HISTFILESIZE=10\nexport HISTCONTROL=ignorespace" >>/etc/bashrc
RETVAL=$?
if [ $RETVAL -eq 0 ];then
   action "Command line history sav change" /bin/true
  else
   action "Command line history sav change" /bin/false
fi



########## rm command alias set
echo "禁止使用rm"
echo "alias rm='echo Do not use the rm command'" >>/etc/bashrc
RETVAL=$?
if [ $RETVAL -eq 0  ];then
   action "Command rm alias set" /bin/true
  else
   action "Command rm alias set" /bin/false
fi




######## Time proofread and first update
echo "时间校对"
echo -e "ZONE="Asia/Shanghai"\nUTC=false\nARC=false" >/etc/sysconfig/clock && 
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime &&
ntpdate ntp1.aliyun.com >/dev/null 2>&1 &&
/sbin/hwclock --systohc
RETVAL=$?
if [ $RETVAL -eq 0   ];then
   action "Time proofread and first update" /bin/true
  else
   action "Time proofread and first update" /bin/false
fi
 


######### /etc/rc.d/rc.local file permission change
echo "本地文件权限更改"
sleep 2
chmod 744 /etc/rc.d/rc.local
RETVAL=$?
if [ $RETVAL -eq 0 ];then
   action "/etc/rc.d/rc.local file permission change" /bin/true
  else
   action "/etc/rc.d/rc.local file permission change" /bin/false
fi



echo "更新完毕"
posted @ 2021-07-31 13:39  ଲ一笑奈&何  阅读(133)  评论(0编辑  收藏  举报