CentOS6系统优化

[root@xuliangwei ~]# cat /etc/redhat-release  //系统环境CentOS6.6
CentOS release 6.6 (Final)
[root@xuliangwei ~]# uname –a       //内核版本2.6.32 64位操作系统
Linux xuliangwei.com 2.6.32-504.el6.x86_64 #1 SMP Wed Oct 15 04:27:16 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

1.1精简开机系统

为什么要设置开机自启动?
好处:
1、节省开机时间、加快启动速度。
2、节省资源开销
3、减少安全隐患

保留5个必须:sshd|rsyslog|network|crond|sysstat
sshd        远程连接Linux服务器时需要用到这个服务器程序,所以必须要开启,否则将无法连接Linux服务器。
rsyslog 是操作系统提供的一种机制,系统的守护程序通常会使用rsyslog将各种信息记录系统日志文件中,Centos6以前服务器的名字为syslog
network 系统启动时,若想激活/关闭各个网络接口,则应(必须)考虑开启。
crond   该服务用于周期性地执行系统及用户配置的任务计划。有要周期性执行的任务,任要开启,此服务几乎是生产场景必须要用的一个软件。
sysstat     sysstat是一个软件包,包含检测系统性能及效率的一组工具,这些工具对于系统性能数据很有帮助,比如CPU使用率,硬盘和网络吞吐数据等,这些数据的分析,有利于判断系统运行是否正常,所以它是提高系统运行效率、安全运行服务器的助手。
sysstat软件包集成的主要工具为:
    iostat      工具提供CPU使用率及硬盘吞吐效率的数据;
    mpstat      工具提供与单个或多个处理器相关的数据;
    sar         工具负责收集、报告并存储系统活跃的信息;
    
其他不用开机自启动的处理方法:
1). setup-->SystemServices-->取消*表示关闭
2)netsysv-->取消*表示关闭
3)使用chkconfig进行关闭   chkconfig name off
4)export LANG=en 配置临时英文语言

使用for循环,配合awk清理不需要开机自启动服务
//
chkconfig --list|grep "3:on"|grep -Ev "sshd|rsyslog|network|crond|sysstat"| awk '{print "chkconfig", "$1","off"}'|bash

//
for i in `chkconfig --list | awk '{print $1}' | grep -Ev "sshd|network|rsyslog|sysstat|crond"`; do chkconfig $i off; done

//
chkconfig --list |grep 3:on |awk '{print $1}'|grep -Ev "crond|network|rsyslog|sshd|sysstat" |sed -r 's/(.*)/chkconfig \1 off /g' |bash


1.列出我们需要的服务
chkconfig --list | egrep "syslog|cron|network|ssh" | awk '{print $1}'

2.关闭所有服务
for n  in'chkconfig --list | awk '{print $1}'';do chkconfig $n off; done

3.仅开启我们需要的服务
for n in 'chkconfig --list| egrep "syslog| crond|network|ssh" | awk'{print $1}'';do chkconfig --level 3 $n on ;done

4 开启所服务3的级别
for name in `chkconfig --list|awk '{print $1}'`;do chkconfig --level 3 $name on; done

5 开启所有系统服务运行级别为on
for name in `chkconfig --list|awk '{print $1}'`;do chkconfig --level 0123456   $name on; done

6 关闭所有系统服务运行级别off
for name in `chkconfig --list|awk '{print $1}'`;do chkconfig --level 0123456   $name off; done

1.2Linux最小化安装

运维思想最小化原则
2.1、安装Linux系统最小化,即选包最小化,yum安装软件包也要最小化,无用的包不装。
2.2、操作命令最小化。例如:用rm -f text.txt 而不用rm –rf。
2.3、登录Linux用户最小化。平时没有需求不用root登录,用普通用户登录即可sudo。
2.4、普通用户授权权限最小化,即只给必须的管理系统的命令。
2.5、Linux系统文件及目录的权限设置最小化,禁止随意创建、更改、删除。(理论上禁止)

1.3SSH优化

编辑/etc/ssh/sshd_config配置文件
/etc/ssh/sshd_config        //服务端配置文件
/etc/ssh/ssh_config         //客户端配置文件
Port    52113                   //修改端口52113
UseDNS yes                  //修改为No会反向查询客户端主机名,进行验证,防止客户端欺骗
PermitRootlogin no             //禁止root登录
PermitEmpasswords   no         //禁止使用空密码(默认为空)
ListenAddress   192.168.1.x //只运行服务器上的内网地址来进行远程连接,外网地址直接拒绝,可以用Vpn做跳
GSSAPIAuthentication yes    //解决Linux之间使用ssh连接慢的问题
板进入局域网,通过这样来访问,更加的安全

配置文件修改:

######xuliangwei######  
Port 52113
UseDNS no
PermitRootlogin no
GSSAPIAuthentication no
PermitEmpasswords   no
######2015-10-06######  

sed添加方式:

[root@student ~]# sed -ir '12 iPort 52113\nUseDNS no\nPermitRootlogin no\nGSSAPIAuthentication no' /etc/ssh/sshd_config
[root@student ~]# sed -i '/#Port 22/i ######xuliangwei######\nPort 52113\nUseDNS no\nPermitRootlogin no\nGSSAPIAuthentication no\n PermitEmptyPasswords no\n######2015-10-06######' /etc/ssh/sshd_config

[root@xuliangwei ~]# /etc/init.d/sshd restart   //重启生效
Stopping sshd:                                      [  OK  ]
Starting sshd:                                      [  OK  ]

1.4SUDO提权

[root@ student ~]# sed -i '98 ax1uliangwei  ALL=(ALL)   NOPASSWD:ALL' /etc/sudoers      普通用户能够提权至root权限,并且不需要执行密码
[root@ student ~]# visudo -c        检测sudo文件是否配置正确
/etc/sudoers: parsed OK

1.5中文乱码

中文字符集调整,调整服务器端字符集, Xshell客户端连接工具也需要调整为UTF-8
[root@ student ~]# cat /etc/sysconfig/i18n  //调整为zh注意大小写 
LANG="zh_CN.UTF-8"
SYSFONT="latarcyrheb-sun16"
[root@oldboy ~]# source /etc/sysconfig/i18n //source配置文件生效
[root@oldboy ~]# echo $LANG
zh_CN.UTF-8


英文字符集调整
export LANG=en_US.UTF-8     //临时生效
sed或者 vim修改配置文件 “/etc/sysconfig/i18n”  更改 LANG="en_US.UTF-8"
> /etc/sysconfig/i18n && echo "LANG=en_US.UTF-8"> /etc/sysconfig/i18n && source /etc/sysconfig/i18n     //自动更改永久生效

1.6时间同步

time.nist.gov   time.windows.com    //时间服务器
date -s "2015/05/28 12:00"      date手动修改时间同步
echo '#time sync by oldboy at 2010-2-1' >>/var/spool/cron/root  //往crond写入注释信息
echo '*/5 * * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1' >>/var/spool/cron/root       //ntpdate定时和互联网时间同步
服务器在50-100台之间搭建时间同步服务器ntpserver

1.7优化历史记录

history 查看历史记录 默认100条,防止黑客进入服务器,查看到机密信息
参数:
    -c:清空历史记录
    -d:指定删除一行
export HISTSIZE=5       
[root@student ~]# export HISTSIZE=5     命令行只看见5条信息(控制终端)
[root@student ~]# history       查看是否只存留5条
  730  history 
  731  ls
  732  history 
  733  export HISTSIZE=5
  734  history
[root@student ~]# echo 'export HISTSIZE=5' >>/etc/profile       写入全局配置文件,永久生效控制终端只有5条信息
[root@student ~]#source /etc/profile        立即生效
    

[root@student ~]# export HISTFILESIZE=5     ~/.bash_historty(控制用户家目录下的记录)
[root@student ~]# cat ~/.bash_history 
Test
Welcome to xuliangwei Linux
EOF
Exit
[root@student ~]# echo 'export HISTFILESIZE=5' >>/etc/profile       写入全局配置文件,永久生效。当前用户家目录下~/.bash_history
[root@student ~]#source /etc/profile        立即生效


[root@student ~]# history -c        清空历史记录终端
[root@student ~]# history  
  734  history
export HISTTIMEFORMAT="%F %T `whoami`"  记录历史命令执行时间以及是谁执行(生产必加)

1.8终端超时

[root@student ~]# export TMOUT=600  //临时生效
[root@student ~]# echo "export TMOUT=600" >> /etc/profile   //永久生效

1.9加大文件描述符

启动进程使用它来表示打开的文件。每个进程启动都会占用文件描述符,如果过文件描述符不够,会导致进程失败
ulinit -n       查看默认文件描述符
参数: -S:软   -H:硬
[root@student ~]# ulimit -SHn 65535 //临时生效调整文件描述符
[root@student ~]# echo "* - nofile 65535" >>/etc/security/limits.conf
//永久生效调整文件描述符(退出终端可生效)

1.10锁定系统关键文件

[root@student ~]# chattr +i /etc/passwd /etc/shadow /etc/group /etc/gshadow /etc/inittab        锁定文件系统
[root@student ~]# lsattr /etc/passwd /etc/shadow /etc/group /etc/gshadow /etc/inittab       查看锁定文件
----i--------e- /etc/passwd
----i--------e- /etc/shadow
----i--------e- /etc/group
----i--------e- /etc/gshadow
----i--------e- /etc/inittab
[root@student ~]# chattr -i /etc/passwd /etc/shadow /etc/group /etc/gshadow /etc/inittab        解除锁定
 [root@student ~]# lsattr /etc/passwd /etc/shadow /etc/group /etc/gshadow /etc/inittab      再次查看
-------------e- /etc/passwd
-------------e- /etc/shadow
-------------e- /etc/group
-------------e- /etc/gshadow
-------------e- /etc/inittab

1.11禁止Linux被ping

[root@student ~]# echo "net.ipv4.icmp_echo_ignore_all=1">>/etc/sysctl.conf      //禁止Linux被ping会增加系统安全(自己也无法ping)
[root@student ~]#  echo "net.ipv4.icmp_echo_ignore_all=0">>/etc/sysctl.conf     //还原禁ping
[root@student ~]# sysctl -p     //不管禁止还是开启都需要使其生效(一般工作中我们用防火墙)

1.12调整yum源

由于默认的yum源是从centos官网下载会很慢,调整为国内的速度会快很多。

[root@student ~]# mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.xuliangwei.20150629    //备份yum源
[root@student ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo    //CentOS6源
[root@student ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo    //CentOS 7源

1.13隐藏Linux版本号

[root@student ~]# >/etc/issue       清空版本信息
[root@student ~]# >/etc/issue =  cat > /dev/null /etc/issue
[root@student ~]# cat >> /etc/motd << EOF       编辑/etc/motd (设置登录提示信息)
> Welcome to xuliangwei Linux
> EOF

1.14定时清理垃圾文件

CentOS6 默认情况下没有安装sendmail服务,而是改装了postfix服务,因此邮件存放地点的路径为/var/spool/postfix/maildrop/。
以上两个目录很容易被垃圾文件填满导致系统的inode数量不够用,从而导致无法存放文件。
手动清理方法如下:
[root@student ~]#find /var/spool/postfix/maildrop/ -type f | xarfs rm -f        //适合CentOS6的Postfix服务 
定时清理方法为:将上述命令写成脚本,然后做定时任务,每天晚上0点执行一下。

1.15关闭iptables防火墙

学习一般关闭掉防火墙,如果生产环境在做调试

[root@student ~]# iptables -L –n       //查看防火墙
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
[root@student ~]# /etc/init.d/iptables stop //关闭防火墙
iptables: Setting chains to policy ACCEPT: filter         [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                           [  OK  ]

1.16关闭SElinux防火墙

SELINUX是美国国家安全局(NSA)对于强制访问控制的实现,这个功能让系统管理员又爱又恨,这里我们还是把它关闭了,至于安全问题,后面通过其他手段来解决,这也是大多数生产环境的做法,如果非要开启也是可以的。

修改/etc/selinux/config-->    SELINUX=enforcing修改为SELINUX=disabled
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config     使用sed替换关闭selinux
getenforce  查看selinux当前环境
setenforce  临时关闭 1.开启 0.关闭  permissive

1.17Linux内核优化

这儿所列参数是老师生产中常用的参数:
把参数添加到/etc/sysctl.conf中,然后执行sysctl -p使参数生效,永久生效

net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl =15
net.ipv4.tcp_retries2 = 5
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_orphans = 32768
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_wmem = 8192 131072 16777216
net.ipv4.tcp_rmem = 32768 131072 16777216
net.ipv4.tcp_mem = 786432 1048576 1572864
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.ip_conntrack_max = 65536
net.ipv4.netfilter.ip_conntrack_max=65536
net.ipv4.netfilter.ip_conntrack_tcp_timeout_established=180
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
如下内容,如果不开启iptables防火墙,会报错
#net.bridge.bridge-nf-call-ip6tables = 0
#net.bridge.bridge-nf-call-iptables = 0
#net.bridge.bridge-nf-call-arptables = 0
#net.ipv4.ip_conntrack_max = 65536
#net.ipv4.netfilter.ip_conntrack_max=65536
#net.ipv4.netfilter.ip_conntrack_tcp_timeout_established=180

企业面试:Linux系统如何优化?

1.sudo管理用户授权  (不用root管理,以普通用户的名义通过sudo提权)
2.更改默认的远程连接SSH服务端口,禁止root用户远程连接,(提前建立普通用户)(甚至更改为只监听内网IP)
3.精简并保留必要的开机自启动服务(如crond、sshd、network、rsyslog、sysstat)
4.设置运行级别为3(文本模式)
5.服务器时间同步。
6.关闭SELINUX防火墙
7.关闭防火墙(iptables),(在工作场景中,如果有外部IP一般打开)
8.设置回话的超时时间及历史记录数。
9.配置yum更新源,从国内更新源下载安装软件包。
10.调整文件描述符的数量,进程及文件的打开都会消耗文件描述符。
11.定时自动清理邮件目录垃圾文件,防止inodes节点被占满(注意centos5和centos6目录不同)
12.Linux内核参数优化/etc/sysctl.conf,执行sysctl -p 生效。
13.更改字符集,是其支持中文,(但建议还是用英文字符集,防止出现乱码。)
14.锁定关键系统文件如/etc/passwd /etc/shadow /etc/group /etc/gshadow /etc/inittab处理以上内容后把chattr、lsattr改名为xuliangwei,这样就安全多了。
15.清空/etc/issue、/etc/issue.net,去除系统及内核版本登录前的信息。
16.清除多余的系统虚拟账号。
17.给grub菜单加密码。
18.禁止被PING
19.升级漏洞软件(yum/rpm升级)

1.18CentOS6优化脚本

#!/bin/sh
echo -e "\033[32m========================================\033[0m"
echo -e "\033[32m   The Author : xubusi                  \033[0m"
echo -e "\033[32m   Description: Optimization            \033[0m"
echo -e "\033[32m   QQ:552408925                         \033[0m"
echo -e "\033[32m========================================\033[0m"
. /etc/init.d/functions
function jd () {
b=''
for ((i=0;$i<=100;i+=2))
do
        printf "TimeOut:[%-50s]%d%%\r" $b "$i"
        sleep 0.1
        b=#$b
done
echo -e
}

#Defined functions
function Msg() {
  if [ $? -eq 0 ];then
action "$1" /bin/true
else
action "$1" /bin/false
  fi
}

#Defined  alias function
 function alias () {
echo "alias ll='ls -l --time-style=long-iso'" >> /etc/bashrc && \
echo "alias grep='grep --color=auto'" >> /etc/bashrc && \
echo "alias egrep='egrep --color=auto'" >> /etc/bashrc && \
Msg "alias"

}

#Defined network is configure
 function ip () {
  ping -c4 www.baidu.com &>/dev/null
Msg "network"
}

#Defined yum source
function yum () {
  YumDir=/etc/yum.repos.d/
 [ -f "$YumDir/CentOS-Base.repo" ] && \/bin/cp $YumDir/CentOS-Base.repo{,.ori}
wget=`rpm -qa wget|wc -l`
 if [ $wget -ne 1 ];then
yum install -y wget &>/dev/null && \
wget -qO /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo &>/dev/null
      Msg "Yum source"
else
wget -qO /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo &>/dev/null
      Msg "Yum source"
fi
}


#Defined character set
function charset () {
  set="/etc/sysconfig/"
  [ -f "$set/i18n" ] && /bin/mv $set/i18n{,.ori}
cat > $set/i18n <<EOF
LANG=en_US.UTF-8
EOF
    Msg "character set"
}


#Defined Time Synchronization
 function Time () {
  echo "######time sync by xuliangwei is $(date +%F)######" >> /var/spool/cron/root
  echo "*/5 * * * * ntpdate time.windows.com >/dev/null 2>&1" >> /var/spool/cron/root
Msg "time sync"
}


#Defined Tmp Clear
 function tmp () {
/bin/find /var/spool/postfix/maildrop/ -type f | xargs rm -f
echo "######clear tmp by xuliangwei is $(date +%F)######" >> /var/spool/cron/root
echo "00 00 * * * /bin/find /var/spool/postfix/maildrop/ -type f | xargs rm -f >/dev/null 2>&1" >> /var/spool/cron/root
Msg "Tmp Clear"
}

#Defined Terminal
 function ter () {
  echo "export TMOUT=600ms" >> /etc/profile
Msg "Terminal"
}

#Defined is open file
function file () {
 OpenFile="/etc/security/limits.conf"
[ -f "$OpenFile" ] && echo "* - nofile 65535" >>/etc/security/limits.conf
Msg "OpenFile"
}

#Defined Hide System Version
 function Hide () {
[ -f "/etc/issue" ] && > /etc/issue && \
[ -f "/etc/issue" ] && > /etc/issue.net && \
[ -f "/etc/motd" ] && cat >> /etc/motd <<EOF
Welcome to xuliangwei Linux Server 6.7
EOF
Msg "Hide system version"
}

#Defined Kernel
 function kernel () {
cat > /etc/sysctl.conf <<EOF
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled.  See sysctl(8) and
# sysctl.conf(5) for more details.

# Controls IP packet forwarding
net.ipv4.ip_forward = 0

# Controls source route verification
net.ipv4.conf.default.rp_filter = 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
net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.
#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
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl =15
net.ipv4.tcp_retries2 = 5
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_orphans = 32768
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_wmem = 8192 131072 16777216
net.ipv4.tcp_rmem = 32768 131072 16777216
net.ipv4.tcp_mem = 786432 1048576 1572864
net.ipv4.ip_local_port_range = 1024 65000
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
EOF
#net.bridge.bridge-nf-call-ip6tables = 0
#net.bridge.bridge-nf-call-iptables = 0
#net.bridge.bridge-nf-call-arptables = 0
#net.ipv4.ip_conntrack_max = 65536
#net.ipv4.netfilter.ip_conntrack_max=65536
#net.ipv4.netfilter.ip_conntrack_tcp_timeout_established=180
/sbin/sysctl -p &>/dev/null
   Msg "Kernel"
}

#Defined Selinux off
 function selinux (){
 sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' \
/etc/selinux/config && getenforce &>/dev/null
Msg "Selinux"
}


#Defined iptables off
 function iptables (){
  /etc/init.d/iptables stop >/dev/null
Msg "iptables"
}

#Defined sudoer
function sudo (){
  /usr/sbin/useradd xuliangwei &>/dev/null
  echo "123456"|passwd --stdin xuliangwei &>/dev/null
sed  -i '98a xuliangwei  ALL=(ALL)   NOPASSWD:ALL'  /etc/sudoers && \
    visudo -c &>/dev/null
Msg "sudoers"
}


#Defined ssh config
 function ssh () {
  SshDir="/etc/ssh"
[ -f $SshDir/sshd_config ] && \/bin/cp /etc/ssh/sshd_config{,.ori}
 sed -ir '12 iPort 52113\nUseDNS no\nPermitRootlogin no\nGSSAPIAuthentication no' /etc/ssh/sshd_config
##################################
#cat >> /etc/ssh/sshd_config <<EOF
#Port 52113
#UseDNS no
#PermitRootlogin no
#GSSAPIAuthentication no
#EOF
#####################################
  Msg "sshd config"
}


#Defined boot off
 function boot () {
  for i in `chkconfig --list | awk '{print $1}' | grep -Ev "sshd|network|rsyslog|sysstat|crond"`; do chkconfig $i off; done
  Msg "boot off"
}


#Defined restart services
 function sshrestart () {
/etc/init.d/sshd restart &>/dev/null
Msg "sshd restart"
}


function main (){
ip
yum
charset
Time
tmp
ter
file
Hide
kernel
selinux
iptables
sudo
boot
alias
ssh
sshrestart
}
jd
main

猜你喜欢

转载自www.cnblogs.com/xuliangwei/p/9034422.html