2月 21

服务器 自动封锁和解封IP 对付攻击

  服务器流量暴涨,首先通过访问日志查看。每个IP并发不是很高,分布也很广,但是都是只访问主页,可见不是抓取服务导致。通过“netstat -nat|awk ‘{print awk $NF}’|sort|uniq -c|sort -n”t命令查看,连接中还有很多SYN_RECV、TIME_WAIT、ESTABLISHED。看来是小型的攻击。首先是修改web服务的配置,缩减了timeout时间,在nginx上禁止一部分并发比较高的IP,小改系统参数。流量降了20M,但还是太高。nginx虽然禁止了IP,如果用浏览看是一个空白页面,但是每个连接还会产生很小的流量。最后决定将最小的返回值也封掉,直接在iptables上drop掉连接。每个超限IP暂定封2天。写个脚本自动运行。

  此脚本在在centos5.3+python2.6.6使用通过。需要注意,此脚本统计日志完毕会将nginx日志文件清空,如需保留日志,请自行修改。每次加载iptables规则时会清楚上次所有规则,如果有使用其它规则也要自行处理。

#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    drop_ip_iptables.py
# Revision:    1.0
# Date:        2013-2-21
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import os
import time
from string import strip


#### 参数和脚本中使用到的系统命令
nginx_log = "/usr/local/nginx/logs/nginx.access.log"
# 统计nginx日志中IP访问数量
check_comm = "/bin/cat %s |awk ' ''{print $1}'|sort |uniq -c|sort -n -k1 -r" % nginx_log
# 放在crontab中10分钟跑一次,访问超出n次的全部封掉
overproof = 3000
# 被封地址记录文件
# 文件中记录封IP时间和IP地址。时间单位为秒
lock_ip_list = "/usr/local/nginx/logs/lock_ip_list.txt"
# 被封地址解开时间。时间单位为秒
unlock_time = 3600*24*2 


def manage_lock_ip():
    # 获取当前时间
    get_now_time = int(time.time())
    # 管理日志字典
    man_ip = {}
    # 处理日志中的IP
    try:
        log_file = open('%s' % lock_ip_list, 'rb').readlines()
        for get_ip_info in log_file:
            _get_ip_info = strip(get_ip_info).split(' ')
            man_ip['%s' % _get_ip_info[1]] = int(_get_ip_info[0])
    except:
        exit(0)
    # 清空iptable列表,和ip记录日志
    os.popen('/sbin/iptables -F')
    clean_file = open('%s' % lock_ip_list, 'rb+')
    clean_file.truncate()
    # 开始处理IP,被封没有超时的IP写入iptables和日志中
    log_file = open('%s' % lock_ip_list, 'ab')
    for loop_ip in man_ip.keys():
        if (get_now_time - man_ip[loop_ip]) < unlock_time:
            os.popen('/sbin/iptables -I INPUT -s %s -j DROP' % loop_ip)
            log_file.write('%s %s\n' % (man_ip[loop_ip], loop_ip))
    log_file.close()
        


def main():
    # 已封IP地址字典
    drop_ip_list = {}
    # 加载已封IP日志
    try:
        log_file = open('%s' % lock_ip_list, 'rb').readlines()
        for get_drop_ip_info in log_file:
            _get_drop_ip_info = strip(get_drop_ip_info).split(' ')
            drop_ip_list['%s' % _get_drop_ip_info[1]] = int(_get_drop_ip_info[0])
    except:
        os.mknod('%s' % lock_ip_list)
    # 获取nginx日志中的访问超高的ip并写入日志
    access_high_ip = os.popen('%s' % check_comm).readlines()
    for get_ip_count in access_high_ip:
        try :
            _get_ip_count = strip(get_ip_count).split(' ')
            _get_ip = _get_ip_count[1]
            _get_count = _get_ip_count[0]
        except:
            pass
        if (int(_get_count) > int(overproof)) and (_get_ip not in drop_ip_list.keys()):
            now_time = int(time.time())
            log_file = open('%s' % lock_ip_list, 'ab+')
            log_file.write('%s %s\n' % (now_time, _get_ip))
            log_file.close()
    # 统计完毕清空nginx日志
    log_file = open('%s' % nginx_log, 'wb')
    log_file.truncate()
    # 处理要封的IP和要解开的IP
    manage_lock_ip()


if __name__ == '__main__':
    main()

再补充两条日志分析命令
# 单位时间内统计单个IP只访问首页的数量:
#check_comm = “/bin/cat %s|grep ‘GET / HTTP/1.1’|awk ‘ ”{print $1}’|sort |uniq -c|sort -n -k1 -r” % nginx_log
# 单位时间内统计单个IP访问相同页面的数量
#check_comm = “/bin/cat %s|awk -F'”‘ ‘{print $1 $2}’|awk ‘ ”{print $1″ “$6” “$7” “$8}’|sort -k2,4 -r|uniq -c|sort -n -k1 -r” % nginx_log

源码下载
drop_ip_tables

2月 20

学习《Linux系统灾难恢复技术和方法》分区表丢失

http://doc.chinaunix.net/linux/201211/2511264.shtml Linux系统灾难恢复技术和方法

  我所保存的数据都是冗余的分布在不同地域的服务器上,所以之前没有做过磁盘分区损坏恢复的试验。今天看到这篇文章觉得很好,学习学习。以后也备份一下以备需要。
备份到usb中
[root@FCoE ~]# dd if=/dev/sda of=/mnt/sda.mbr bs=512 count=1
1+0 records in
1+0 records out
512 bytes (512 B) copied, 0.000777948 s, 658 kB/s

救援模式下恢复
bash-4.1# dd if=/usb/sda.mbr of=/dev/sda bs=1 count=64 skip=446 seek=446

1月 04

centos下搭建yum服务器自动同步源

  在内网中建立yum服务器,内网linux服务器可以使用yum升级。这样做有两个好处,一内网服务器不用登陆公网比较安全,二节约了流量,不用每台服务器更新都连到公网上。
  安装配置比较简单。需要nginx或apache,本次只列出了nginx配置。还需要rsync工具,建议使用命令“yum install -y rsync”。
  yum服务器内网地址192.168.100.100

Nginx配置

#######################################yum server
server {
        # 直接使用IP地址
        server_name 192.168.100.100;
        # 开启自动显示目录
        autoindex on;
        # 显示文件大小
        autoindex_exact_size off;
        # 显示服务器本地时间
        autoindex_localtime on;
        # yum放置目录
        root    /u01/yumserver/;
        # 内网可见
        allow 192.168.100.0/24;
        # 除上列ip均不能查看
        deny all;
        # 限制ip后会报403错误,做个跳转
        error_page 400 403 404 500 502 503 504 = http://www.simonzhang.net;
        }

同步脚本,将脚本有可执行权限,将此设置到crontab即可。

#!/bin/bash
# -------------------------------
# Revision: 
# Date:        2012-12-11
# Author:      simonzhang
# Email:       simon-zzm@163.com
# Web:         www.simonzhang.net
# ------------------------------- 

# base value
# 要同步的源
YUM_SITE="rsync://mirrors.kernel.org/centos/"
# 本地存放目录
LOCAL_PATH="/u01/mirrors/centos/"
# 需要同步的版本,我只需要5和6版本的
LOCAL_VER="5 5* 6 6*"
# 同步时要限制的带宽
BW_limit=512
# 记录本脚本进程号
LOCK_FILE="/var/log/yum_server.pid"
# 如用系统默认rsync工具为空即可。
# 如用自己安装的rsync工具直接填写完整路径
RSYNC_PATH=""

# check update yum server  pid
MY_PID=$$
if [ -f $LOCK_FILE ]; then
    get_pid=`/bin/cat $LOCK_FILE`
    get_system_pid=`/bin/ps -ef|grep -v grep|grep $get_pid|wc -l`
    if [ $get_system_pid -eq 0] ; then
        echo $MY_PID>$LOCK_FILE
    else
        echo "Have update yum server now!"
        exit 1
    fi
else
    echo $MY_PID>$LOCK_FILE
fi

# check rsync tool
if [ -z $RSYNC_PATH ]; then
    RSYNC_PATH=`/usr/bin/whereis rsync|awk ' ''{print $2}'`
    if [ -z $RSYNC_PATH ]; then
        echo 'Not find rsync tool.'
        echo 'use comm: yum install -y rsync'
    fi
fi

# sync yum source
for VER in $LOCAL_VER;
do 
    # Check whether there are local directory
    if [ ! -d "$LOCAL_PATH$VER" ] ; then
        echo "Create dir $LOCAL_PATH$VER"
        `/bin/mkdir -p $LOCAL_PATH$VER`
    fi
    # sync yum source
    echo "Start sync $LOCAL_PATH$VER"
    $RSYNC_PATH -avrtH --delete --bwlimit=$BW_limit --exclude "isos" $YUM_SITE$VER $LOCAL_PATH$VER
done

# clean lock file
`/bin/rm -rf $LOCK_FILE`

echo 'sync end.'
exit 1

centos_yum_server

客户端配置
编辑/etc/yum.repos.d/CentOS-Base.repo
#base
[base]
name=CentOS-$releasever – Base
baseurl=http://192.168.100.100/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#released updates
[updates]
name=CentOS-$releasever – Updates
baseurl=http://192.168.100.100/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#additional packages that may be useful
[extras]
name=CentOS-$releasever – Extras
baseurl=http://192.168.100.100/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever – Plus
baseurl=http://192.168.100.100/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#contrib – packages by Centos Users
[contrib]
name=CentOS-$releasever – Contrib
baseurl=http://192.168.100.100/centos/$releasever/contrib/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

11月 26

php服务器CPU负载过高故障解决

  今天接到问题,服务器跑一段时间总是cpu使用量突然增大,然后就不能连接了。突然增大情况无规律。通过查看平时服务器运行正常,CPU、内存和IO用量都不高,日志报警大致信息如下:
[WARNING] fpm_stdio_child_said(), line 167: child 30951 (pool default) said into stderr:….. [ERROR] fpm_unix_init_child(), line 168:

setrlimit(RLIMIT_NOFILE) failed: Invalid argument (22)”

  通过安装和初步处理人员沟通了解到。现在已经按照日志在网上搜索,按照网上的解决方案进行处理。处理如下

1、提升服务器的文件句柄打开打开
/etc/security/limits.conf : (增加)
* soft nofile 51200
* hard nofile 51200
# vi /etc/security/limits.conf 加上
* soft nofile 51200
* hard nofile 51200
2、提升nginx的进程文件打开数
nginx.conf : worker_rlimit_nofile 51200;
3、修改php-fpm.conf文件,主要需要修改2处。
命令 ulimit -n 查看限制的打开文件数,php-fpm.conf 中的选项rlimit_files 确保和此数值一致。
10240
51200
4、
# vi /etc/sysctl.conf
底部添加
fs.file-max=51200

  “max_requests”为什么是10240,不知道所以然。

  因为其他资源已经占满,或者存在内存泄露等问题,再大量请求时,系统单个任务压力过大导致服务器不稳定。所以经将配置改为“1024”减少最大值重启数量。

  优化并不是单纯的将参数调大,如果这样能解决,那发布版本时直接都改为最大就好了。也不能按照网上的解决方案照搬方法。所以在解决过程中,要参考学习,也要搞清原理,按照当前环境适当调整。通过调整,服务器已经稳定运行3个月,没有再次出现问题。

11月 09

用nginx的cache 对本地静态文件做缓存

需要对静态文件做缓存,但是静态文件也是在本地,由同一个nginx来解析。
使用if不能嵌套,所以只能使用本地的IP跳转一下,我的cache使用的nginx命名cache_one配置如下。如果本地跳转有问题可以再hosts表中修改一下指向。

   #######################pic
   upstream  local_img {
            server localhost:81;
       }
    server{
        listen       81;
        server_name 127.0.0.1;
        location / {
                root /image/;
                client_max_body_size   10m;
                access_log off;
                autoindex off;
                }
    }
   server {
        listen       80;
        server_name img.test.com;
        proxy_cache cache_one;
        location / {
                proxy_redirect off;
                proxy_cache_valid 200 304 12h;
                proxy_cache_valid 301 302 1m;
                proxy_cache_key $host$uri$is_args$args;
                add_header X-Cache $upstream_cache_status;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $remote_addr;
                proxy_pass http://local_img;
                access_log off;
                }
    }