**背景:**新购买100台服务器并已安装linux操作系统
需求:
1.设置时区并同步时间
2.禁用selinux
3.清空防火墙默认策略
4.历史命令显示操作时间
5.禁止root远程登录,这个要注意,禁止之前确保有普通账户可以sudo到root权限使用,不然切不到root账户
6.禁止定时任务发送邮件
7.设置最大打开文件数,默认比较少
8.减少swap使用,默认物理内存不够会使用swap来交换,速度慢,不建议使用
9.系统内核参数优化
10.安装系统性能分析工具及一些其他的
实现脚本如下:
$ cat server_initialize.sh
#!/bin/bash
# 设置时区为上海并每小时同步一次时间,默认时区为东八区
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# if判断是根据命令执行状态返回值$#?来判断是否执行成功,执行成功则为0,执行失败则为其他,一般为1
if ! crontab -l | grep ntpdate &>/dev/null; then
# | crontab通过管道符接收定时任务
(echo "* 1 * * * ntpdate time.windows.com >/dev/null 2>&1";crontab -l) | crontab
fi
# 禁用selinux
sed -i '/SELINUX/{s/permissive/disabled/}' /etc/selinux/config
# 关闭防火墙
if egrep "7.[0-9]" /etc/redhat-release &>/dev/null; then
systemctl stop firewalld
systemctl disable firewalld
elif egrep "6.[0-9]" /etc/redhat-release &>/dev/null; then
service iptables stop
chkconfig iptables off
fi
# 历史命令显示操作时间
# 方便后期审计,谁在什么时间操作
if ! grep HISTTIMEFORMAT /etc/bashrc &>/dev/null; then
echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >> /etc/bashrc
fi
# SSH超时时间
# 只有TMOUT可以控制ssh连接在空闲时间超时,自动断开连接的时间,数字单位为“秒”
if ! grep "TMOUT=1500" /etc/profile &>/dev/null; then
echo "export TMOUT=1500" >> /etc/profile
fi
# 禁止root远程登录
# 操作之前授权其他账号或者将自己本机的key保存在系统,或者授权其他账户可以sudo到root账户
# sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
# 禁止定时任务向root发送邮件
# 定时任务的错误等会给当前用户发送邮件,默认是当前用户,会在/var/mail很多小文件占用很大的磁盘空间
sed -i 's/^MAILTO=root/MAILTO=""/' /etc/crontab
# 设置最大打开文件数
# 并发较高时,很容易会达到默认,很容易不可用,这里做个优化
# EOF直接将内容追加到文件中,需要在当前行起始位置,不能加空格
if ! grep "* soft nofile 65535" /etc/security/limits.conf &>/dev/null; then
cat >> /etc/security/limits.conf << EOF
* soft nofile 65535
* hard nofile 65535
EOF
fi
# 系统内核优化
# 默认数值可通过systcl -a查看
# net.core.netdev_max_backlog 决定了,网络设备接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。
# net.ipv4.tcp_syncookies = 1表示开启SYN Cookies。当出现SYN等待队列溢出时,启用cookies来处理,可防范少量SYN攻击,默认为0,表示关闭。
# net.ipv4.tcp_fin_timeout =20表示如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2状态的时间。
cat >> /etc/sysctl.conf << EOF
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_tw_buckets = 20480
net.ipv4.tcp_max_syn_backlog = 20480
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_fin_timeout = 20
EOF
# 减少SWAP使用
# 权重值设置的越大,使用的可能越大。设置为0,尽可能不使用它。
echo "0" > /proc/sys/vm/swappiness
# 安装系统性能分析工具及其他
# htop 比top好用的工具
yum install gcc make autoconf vim htop sysstat net-tools iostat iftop iotp lrzsz -y