Linux简单处理CC攻击shell脚本

第一个脚本是通过查找日志中访问次数过多的ip,并用iptables屏蔽,600秒解封。

  1. #!/bin/bash
  2. btime=600
  3. attacks=20
  4. tmpBlockIPFile=/home/tmp_block_ip
  5. timestamp=$(date +%s)
  6. logPath="/home/ban.log"
  7.  
  8. #start detect bad ip
  9. badip=`tac /home/devops.webres.wang/access.log  | awk ‘
  10. BEGIN{
  11. cmd="date -d "1 minute ago" +%H%M%S"
  12. cmd|getline a
  13. }
  14. {
  15. $4 = substr($4,14,8)
  16. gsub(":","",$4)
  17. $4=$4+0
  18. a=a+0
  19. if ($4>=a){
  20. print $1,$7
  21. } else {
  22. exit;
  23. }
  24. }’ | egrep -v ‘.(gif|jpg|jpeg|png|css|js)’ | awk ‘{print $1}’ | sort | uniq -c | awk -v t="$attacks" ‘{$1=$1+0;t=t+0;if ($1>=t) print $2}’`
  25.  
  26. if [ ! -z "$badip" ];then
  27.     for ip in $badip;
  28.     do
  29.         if test -z "`/sbin/iptables -nL | grep $ip`";then
  30.             /sbin/iptables -I INPUT -s $ip -j DROP
  31.  
  32.             #record blocked ip
  33.             echo "$timestamp $ip" >> $tmpBlockIPFile
  34.             echo "$(date) $ip" >> $logPath
  35.         fi
  36.     done
  37. fi
  38.  
  39. #unblock ip
  40. if [ -f "$tmpBlockIPFile" ];then
  41.     ips=""
  42.     while read blockTime ip
  43.     do
  44.         ((interval=$timestamp – $blockTime))
  45.         if [ $interval -gt $btime ];then
  46.             ips="$ips $ipn"
  47.         fi   
  48.     done < $tmpBlockIPFile
  49.  
  50.     if [ "$ips" != "" ];then
  51.         for ip in `echo -e $ips`
  52.         do
  53.             sed -i "/$ip/d" $tmpBlockIPFile
  54.             /sbin/iptables -D INPUT -s $ip -j DROP
  55.         done
  56.     fi
  57. fi

将此代码保存为ban.sh,加入cronjob使每分钟执行一次。
此脚本的作用是:利用iptables屏蔽每分钟访问页面超过20的IP,这些页面已经排除图片,css,js等静态文件。
第二个脚本是通过在日志中查找cc攻击的特征进行屏蔽。

  1. #!/bin/bash
  2. keyword="cc-atack"
  3. badip=`tail -n 5000  /home/devops.webres.wang/log/access.log | grep "$keyword"  | awk ‘{print $1}’ | sort | uniq -c | sort -nr | awk ‘{print $2}’`
  4. if [ ! -z "$badip" ];then
  5. for ip in $badip;
  6. do
  7. if test -z "`/sbin/iptables -nL | grep $ip`";then
  8. /sbin/iptables -I INPUT -s $ip -j DROP
  9. fi
  10. done
  11. fi

keyword则是日志中cc的特征,替换成有效的即可。

bind dns 宕机检测 故障切换shell脚本

devops.webres.wang解析有多个A记录,下面是实现故障切换的脚本:
通过检测网站的返回状态码来确定服务器的健康状况,如果不返回或返回的状态非200,则开始记录一次故障,连续三次故障后开始删除此域名的故障ip A记录,如果之后的检测发现服务器已经恢复,则重新添加此ip的A记录。

  1. #!/bin/bash
  2. #===============================================================================
  3. #Description: this script is to automactic update dns record when website is down.
  4. #Author     : devops.webres.wang
  5. #文件说明:
  6. # /tmp/domain_list.txt                       需要监控的域名列表,每行一个域名
  7. # /tmp/${domain}_online_ip.txt               记录在线的服务器ip,需要提前写入IP,每行一个IP
  8. # /tmp/${domain}_down_ip.txt                 记录有故障的服务器ip
  9. # /tmp/curl.txt                              记录curl获取的http状态码
  10. # /tmp/${domain}_${server_ip}_cur_time.txt    记录服务器出现故障的次数
  11. #===============================================================================
  12.  
  13. #设置一些必要的变量
  14. keyname=rndc-key
  15. keysecret=gAnBYq6xSv7FKTZFmzAD0Q==
  16.  
  17. #用来检测本机网络是否正常
  18. function network_detect(){
  19. ping -c1 8.8.8.8 >/dev/null 2>&1 && echo connect || exit 1
  20. }
  21.  
  22. #用来删除DNS记录
  23. function del_record(){
  24. /usr/local/bind/bin/nsupdate <<EOF
  25. key $keyname $keysecret
  26. update delete $domain A $1
  27. send
  28. quit
  29. EOF
  30. }
  31.  
  32. #用来增加DNS记录
  33. function add_record(){
  34. /usr/local/bind/bin/nsupdate <<EOF
  35. key $keyname $keysecret
  36. update add $domain 3600 A $1
  37. send
  38. quit
  39. EOF
  40. }
  41.  
  42. #用来检测在线ip列表健康状态
  43. function online_detect(){
  44. if [  -s /tmp/${domain}_online_ip.txt ] ;then
  45. for server_ip in `cat /tmp/${domain}_online_ip.txt` ;
  46. do
  47. curl -I -l -H "Host:$domain"  $server_ip -o "/tmp/curl.txt" >/dev/null 2>&1
  48. ###判断状态码是否为200
  49. if [ -s /tmp/curl.txt ] && grep ‘200 OK’ /tmp/curl.txt >/dev/null 2>&1;then
  50. echo "OK"
  51. ###清空故障次数
  52. rm -f /tmp/${domain}_${server_ip}_cur_time.txt
  53. ###状态码非200时
  54. else
  55. ###开始计算故障次数
  56. cur_time=0
  57. [ -s /tmp/${domain}_${server_ip}_cur_time.txt  ] && cur_time=`cat /tmp/${domain}_${server_ip}_cur_time.txt `
  58. cur_time=`expr $cur_time + 1`
  59.  
  60. ###当故障次数大于等于3时
  61. if [ $cur_time -gt 3 ];then
  62. ###删除故障ip记录
  63. del_record $server_ip
  64. ###从在线ip列表中删除故障ip
  65. sed -i "/$server_ip/d" /tmp/${domain}_online_ip.txt
  66. ###记录故障ip到文件
  67. echo $server_ip >> /tmp/${domain}_down_ip.txt
  68. ###删除记录此ip的故障文件
  69. rm -f /tmp/${domain}_${server_ip}_cur_time.txt
  70.  
  71. else
  72. ###记录故障次数
  73. echo $cur_time > /tmp/${domain}_${server_ip}_cur_time.txt
  74. fi
  75. fi
  76. rm -f /tmp/curl.txt
  77.  
  78. done
  79. fi
  80. }
  81.  
  82. #用来检测故障ip列表健康状态
  83. function down_detect(){
  84. if [ -s /tmp/${domain}_down_ip.txt ];then
  85. for server_ip in `cat /tmp/${domain}_down_ip.txt` ;
  86. do
  87. curl -I -l -H "Host:$domain"  $server_ip -o "/tmp/curl.txt" >/dev/null 2>&1
  88. if [ -s /tmp/curl.txt ] && grep ‘200 OK’ /tmp/curl.txt >/dev/null 2>&1;then
  89. ###添加A记录
  90. add_record $server_ip
  91. ###从${domain}_down_ip.txt删除故障ip
  92. sed -i "/$server_ip/d" /tmp/${domain}_down_ip.txt
  93. ###重新添加此ip到${domain}_online_ip.txt
  94. echo $server_ip >> /tmp/${domain}_online_ip.txt
  95. fi
  96. rm -f /tmp/curl.txt
  97. done
  98. fi
  99. }
  100. network_detect
  101. if [ -s /tmp/domain_list.txt ];then
  102. for domain in `cat /tmp/domain_list.txt` ;
  103. do
  104. online_detect
  105. down_detect
  106. done
  107. else
  108. echo "/tmp/domain_list.txt not found!"
  109. exit 1
  110. fi

要正常使用以上脚本,需要注意以下事项:
1、 /tmp/domain_list.txt 填写需要监控的域名,/tmp/${domain}_online_ip.txt填写对应域名的所有A记录。
2、根据bind设置修改脚本中的三个变量

  1. domain=devops.webres.wang
  2. keyname=rndc-key
  3. keysecret=gAnBYq6xSv7FKTZFmzAD0Q==

3、在named.conf文件中的zone添加如下代码:

  1. allow-update {key rndc-key;};

rndc-key修改为自己的。

自动获取联通电信最新IP段

如果需要做联通电信的智能DNS,必然需要知道这两个ISP分配到的IP段。我们可以通过apnic下载完整的IP段,再查询IP的whois,再根据各运营商的关键词(如联通的netname是unicom,电信是chinanet或telecom)筛选出IP段。
下面是实现这一功能的脚本:
在执行脚本之前先安装jwhois,bc

  1. yum install jwhois bc
  1. #!/bin/sh
  2. FILE=/root/apnic/ip_apnic
  3. rm -f $FILE
  4. wget http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest -O $FILE
  5. grep ‘apnic|CN|ipv4|’ $FILE | cut -f 4,5 -d’|’|sed -e ‘s/|/ /g’ | while read ip cnt
  6. do
  7. echo $ip:$cnt
  8.         mask=$(cat << EOF | bc | tail -1
  9. pow=32;
  10. define log2(x) {
  11. if (x<=1) return (pow);
  12. pow–;
  13. return(log2(x/2));
  14. }
  15. log2($cnt)
  16. EOF)
  17.        echo $ip/$mask>> cn.net
  18. if whois [email protected] | grep -i ".*chinanet.*|.*telecom.*">/dev/null;then
  19. echo $ip/$mask >> chinanet
  20. elif whois [email protected] | grep -i ".*unicom.*">/dev/null;then
  21. echo $ip/$mask >> unicom
  22. else
  23. echo $ip/$mask >> others
  24. fi
  25. done

直接执行这脚本就会开始进行IP段筛选,这需要一定的时间,等完成后会在当前目录下生成三个文件unicom,chinanet,others。
下面提供联通电信ip段acl文件:
电信:CHINANET.acl
联通:CNC.acl
脚本参考:http://bbs.chinaunix.net/thread-577601-1-1.html

Linux shell快速查找PHP木马

一句话查找PHP木马

  1. # find ./ -name "*.php" |xargs egrep "phpspy|c99sh|milw0rm|eval(gunerpress|eval(base64_decoolcode|spider_bc"> /tmp/php.txt
  2.  
  3. # grep -r –include=*.php  ‘[^a-z]eval($_POST’ . > /tmp/eval.txt
  4.  
  5. # grep -r –include=*.php  ‘file_put_contents(.*$_POST[.*]);’ . > /tmp/file_put_contents.txt
  6.  
  7. # find ./ -name "*.php" -type f -print0 | xargs -0 egrep "(phpspy|c99sh|milw0rm|eval(gzuncompress(base64_decoolcode|eval(base64_decoolcode|spider_bc|gzinflate)" | awk -F: ‘{print $1}’ | sort | uniq

查找最近一天被修改的PHP文件

  1. #   find -mtime -1 -type f -name *.php

修改网站的权限

  1. # find -type f -name *.php -exec chmod 444 {} ;
  2.  
  3. # find ./ -type d -exec chmod 555{} ;

转自:http://www.xtgly.com/2011/11/21/linux-shell%E5%BF%AB%E9%80%9F%E6%9F%A5%E6%89%BEphp%E6%9C%A8%E9%A9%AC.htm

CentOS系统服务优化脚本

  1. #!/bin/bash
  2. #该脚本用于关闭服务器上非必须的系统服务项,并不适用于所有服务器,比如如果是文件服务器则NFS相关服务则不能关闭
  3. #定义所要停止的服务,可以根据实际服务器应用更改
  4. SERVICES="acpid atd auditd avahi-daemon bluetooth cups firstboot hidd ip6tables kudzu lvm2-monitor mcstrans mdmonitor microcode_ctl netfs nfslock pcscd portmap rpcgssd rpcidmapd xfs yum-updatesd"
  5. for service in $SERVICES
  6. do
  7. #关闭服务随系统启动
  8. chkconfig $service off
  9. #停止选择服务
  10. service $service stop
  11. done

下载脚本:http://devops.webres.wang/wp-content/uploads/2011/10/optimize-service.sh

Linux vsftpd启动,停止,重启脚本

yum安装vsftpd后启动脚本也安装好了,管理vsftpd进程非常方便。但编译安装vsftpd的话,修改配置文件需要重启,就有点麻烦了,需要用kill杀掉进程,再键入/usr/local/sbin/vsftpd &启动。下面提供一个vsftpd启动脚本,让管理vsftpd也像yum安装管理vsftpd一样轻松。

  1. #!/bin/bash
  2.  
  3. #chkconfig: 345 60 50
  4. #description:vsftpd
  5. . /etc/rc.d/init.d/functions
  6. if [ -f /etc/init.d/functions ] ; then
  7. . /etc/init.d/functions
  8. elif [ -f /etc/rc.d/init.d/functions ] ; then
  9. . /etc/rc.d/init.d/functions
  10. else
  11. exit 0
  12. fi
  13. vsftpd=/usr/local/sbin/vsftpd      //vsftp启动脚本中配置vsftpd安装的路径
  14. prog=vsftpd
  15. RETVAL=0
  16. start() {
  17.         if [ -n "`/sbin/pidof $prog`" ]
  18.         then
  19.                 echo "$prog: already running"       
  20.                 echo
  21.                 return 1
  22.         fi
  23.         echo "Starting $prog:"
  24.         base=$prog
  25.         $vsftpd &
  26.         RETVAL=$?
  27.         usleep 5000000
  28.         if [ -z "`/sbin/pidof $prog`" ]
  29.         then
  30.                 RETVAL=1
  31.         fi
  32.         if [ $RETVAL -ne 0 ]       
  33.         then
  34.         echo "Startup failure"     //vsftp启动脚本启动失败提示
  35.         else
  36.         echo "Startup success"     //vsftp启动脚本启动成功提示
  37.         fi
  38.         echo
  39.         return $RETVAL
  40. }
  41.  
  42. stop() {
  43.         echo "Stopping $prog:"
  44.         killall $vsftpd
  45.         RETVAL=$?
  46.         if [ $RETVAL -ne 0 ]
  47.         then
  48.         echo "Shutdown failure"     //vsftp启动脚本停止失败提示
  49.         else
  50.         echo "Shutdown success"     //vsftp启动脚本停止成功提示
  51.         fi
  52.         echo
  53. }
  54.  
  55. case "$1" in
  56. start)
  57.         start     //vsftp启动脚本服务启动操作
  58.         ;;
  59. stop)
  60.         stop     //vsftp启动脚本服务停止操作
  61.         ;;
  62. status)
  63.         status $vsftpd
  64.         RETVAL=$?    //vsftp启动脚本服务状态
  65.         ;;
  66. restart)
  67.         stop
  68.         usleep 5000000    //vsftp启动脚本服务重启操作
  69.         start
  70.         ;;
  71. *)
  72.         echo "Usage: $prog {start|stop|restart|status}"
  73.         exit 1
  74. esac
  75. exit $RETVAL

CentOS一键配置rsync服务器脚本

1、保存下面的代码为一个文件,上传到服务器端,名称为rsync.sh

  1. #!/bin/bash
  2. #rsync Written by zhumaohai
  3. #For more information please visit http://devops.webres.wang
  4. echo “Please input the rsync username:”
  5. read username
  6. echo “Please input the rsync username password:”
  7. read password
  8. echo “Please input the allow ip address:”
  9. read allowip
  10. echo “Please input the path you want to rsync:”
  11. read rsyncpath
  12. echo “==========================input all completed========================”
  13. echo “==========================install rsync========================”
  14. yum -y install rsync
  15. useradd $username
  16. mkdir /etc/rsyncd
  17. cat >/etc/rsyncd/rsyncd.conf<<EOF
  18. # Minimal configuration file for rsync daemon
  19. # See rsync(1) and rsyncd.conf(5) man pages for help
  20.  
  21. # This line is required by the /etc/init.d/rsyncd script
  22. pid file = /var/run/rsyncd.pid   
  23. port = 873
  24. #address = $serverip
  25. #uid = nobody
  26. #gid = nobody   
  27. uid = root   
  28. gid = root   
  29.  
  30. use chroot = yes
  31. read only = yes
  32.  
  33.  
  34. #limit access to private LANs
  35. hosts allow=$allowip
  36. hosts deny=*
  37.  
  38. max connections = 5
  39. motd file = /etc/rsyncd/rsyncd.motd
  40.  
  41. #This will give you a separate log file
  42. #log file = /var/log/rsync.log
  43.  
  44. #This will log every file transferred – up to 85,000+ per user, per sync
  45. #transfer logging = yes
  46.  
  47. log format = %t %a %m %f %b
  48. syslog facility = local3
  49. timeout = 300
  50.  
  51. [home]   
  52. path = $rsyncpath   
  53. list=yes
  54. ignore errors
  55. auth users = $username
  56. secrets file = /etc/rsyncd/rsyncd.secrets 
  57. EOF
  58. echo “$username:$password” > /etc/rsyncd/rsyncd.secrets
  59. chmod 600 /etc/rsyncd/rsyncd.secrets
  60. cat >/etc/rsyncd/rsyncd.motd<<EOF
  61. +++++++++++++++++++++++++++
  62. + webres.wang  rsync  2011-2012 +
  63. +++++++++++++++++++++++++++
  64. EOF
  65. /usr/bin/rsync –daemon  –config=/etc/rsyncd/rsyncd.conf
  66. echo “/usr/bin/rsync –daemon  –config=/etc/rsyncd/rsyncd.conf” >>/etc/rc.d/rc.local
  67. ps -aux | grep rsync

2、赋予脚本权限

  1. chmod +x rsync.sh

3、执行脚本

  1. ./rsync.sh

4、客户端同样需要安装rsync
具体配置见http://devops.webres.wang/2011/06/rsync-server-setup/

Linux apache日志分割脚本

  1. #!/bin/bash
  2. logpath=/home/wwwlogs/ #日志的路径
  3. expred=7 #保存7天前的日志
  4. pid=/usr/local/apache/logs/httpd.pid #httpd pid路径
  5. datetime=$(date -d yesterday +%Y%m%d) #昨天的日期
  6.  
  7. if [ ! -d ${logpath}oldlog ]; then
  8. mkdir ${logpath}oldlog
  9. fi
  10. mkdir ${logpath}oldlog/${datetime}
  11. mv ${logpath}*.log ${logpath}oldlog/${datetime}/
  12. kill -USR1 $(cat ${pid})
  13. find ${logpath}oldlog -type f -mtime +${expred} -exec rm -f {} ;

保存为apache-log-handle.sh文件,设置crontab执行。

  1. echo ‘1 0 * * *  /root/sh/apache-log-handle.sh’ >> /var/spool/cron/root

适合Web服务器的iptables规则

  1. IPT="/sbin/iptables"
  2. $IPT –delete-chain
  3. $IPT –flush
  4. $IPT -P INPUT DROP    #1
  5. $IPT -P FORWARD DROP  #1
  6. $IPT -P OUTPUT DROP   #1
  7. $IPT -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT #2
  8. $IPT -A INPUT -p tcp -m tcp –dport 80 -j ACCEPT #3
  9. $IPT -A INPUT -p tcp -m tcp –dport 22 -j ACCEPT #3
  10. $IPT -A INPUT -p tcp -m tcp –dport 21 -j ACCEPT  #3
  11. $IPT -A INPUT -p tcp -m tcp –dport 873 -j ACCEPT #3
  12. $IPT -A INPUT -i lo -j ACCEPT #4
  13. $IPT -A INPUT -p icmp -m icmp –icmp-type 8 -j ACCEPT  #5
  14. $IPT -A INPUT -p icmp -m icmp –icmp-type 11 -j ACCEPT #5
  15. $IPT -A OUTPUT -m state –state RELATED,ESTABLISHED -j ACCEPT #6
  16. $IPT -A OUTPUT -p udp -m udp –dport 53 -j ACCEPT #7
  17. $IPT -A OUTPUT -o lo -j ACCEPT #4
  18. $IPT -A OUTPUT -p tcp -m tcp –dport 80 -j ACCEPT #8
  19. $IPT -A OUTPUT -p tcp -m tcp –dport 25 -j ACCEPT #9
  20. $IPT -A OUTPUT -p icmp -m icmp –icmp-type 8 -j ACCEPT  #10
  21. $IPT -A OUTPUT -p icmp -m icmp –icmp-type 11 -j ACCEPT #10
  22. service iptables save
  23. service iptables restart

存为脚本iptables.sh,执行sh iptables.sh自动配置防火墙。
解释:
#1、设置INPUT,FORWARD,OUTPUT链默认target为DROP,也就是外部与服务器不能通信。
#2、设置当连接状态为RELATED和ESTABLISHED时,允许数据进入服务器。
#3、设置外部客户端连接服务器端口80,22,21,873。
#4、允许内部数据循回。
#5、允许外部ping服务器 。
#6、设置状态为RELATED和ESTABLISHED的数据可以从服务器发送到外部。
#7、允许服务器使用外部dns解析域名。
#8、设置服务器连接外部服务器端口80。
#9、允许服务器发送邮件。
#10、允许从服务器ping外部。