8月 03

bash 产生随机数

  使用bash产生n位的随机数。测试中为产生8位。

#!/bin/bash
# -------------------------------
# Filename:    test.sh
# Revision:    1.0
# Date:        2013-08-01
# Author:      simonzhang
# Email:       simon-zzm@163.com
# Description: 
# -------------------------------

function randnum()
{
    di=(0 1 2 3 4 5 6 7 8 9 \
        a b c d e f g h i j k l m n o p q r s t u v w x y z \
        A B C D E F G H I G K L M N O P Q R S T U V W X Y Z \
        ~ ! ^ _)
    for(( i=0; i<$1; i++))
    do
        num=$num`echo -n ${di[$RANDOM % ${#di[*]}]}`
    done
    echo $num
}

get=$(randnum 8)
echo $get

bash产生n位随机数

8月 02

linux远程通过ssh启停tomcat

  在linux上远程通过ssh启停tomcat,因为存在环境变量加载问题,所以写一个shell脚本,放在tomcat的bin目录下。CentOS测试通过。需要使用bash。因为脚本中包含脚本名字,在查找时要过滤掉自己,所以如果需要修改脚本名字,在脚本内也要相应的修改。

#!/bin/bash
# -------------------------------------------------------------------------------
# Filename:    tomcatcomm.sh
# Revision:    1.0
# Date:        2013-7-29
# Author:      simonzhang
# Email:       simon-zzm@163.com
# Description: 
# -------------------------------------------------------------------------------
# Source function library.
. /etc/init.d/functions
source /etc/profile

#### shell env
path=$(dirname $0)
if [ ${path:0:1} == . ]; then
   path=${path/./$(pwd)}
fi
my_name="tomcatcomm.sh"

###### delete tomcat`s work dir and startup server
del_start()
{
    /bin/rm -rf ${1}work/*
}

######main()
case "$1" in
  start)
       get_pid_count=`/bin/ps -ef|grep -v grep|grep -v ${my_name}|grep ${path}|wc -l`
       if [ ${get_pid_count} -gt 0 ] ; then
          /bin/ps -ef|grep -v grep|grep -v ${my_name}|grep ${path}|awk ' ''{print $2}'|xargs kill -9
          sleep 1
          get_pid_count=`/bin/ps -ef|grep -v grep|grep -v ${my_name}|grep ${path}|wc -l`
           if [ ${get_pid_count} -gt 0 ] ; then
              echo "Error"
           else
              del_start ${path}
              ${path}/startup.sh
           fi
        else
            del_start ${path}
            ${path}/startup.sh
        fi
        ;;
  stop)
        ${path}/shutdown.sh
        del_start ${path}
        sleep 1
        ;;
  restart)
	$0 stop
	$0 start
	;;
  *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

tomcat远程启停脚本

3月 27

不明IP登陆linux服务器时邮件通知

  当有人登陆服务器时希望能知道是那个IP在登陆,如果是黑客登陆了也能及时知道。
  处理方法是,python时时检查linux下 secure 文件,如果是登陆成功的就发邮件。然后用shell脚本调用py启停,然后配置crontab定时检查py是否运行,如果检查进行不在则进行启动。
  python 脚本

#!/bin/python
#-*- coding:utf-8 -*-
# Filename:
# Revision:    1.0
# Date:        2013-3-26
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import re
import os
import time

import smtplib
from email.mime.text import MIMEText

#### 基础设置
mail_host = 'smtp.exmail.qq.com'
mail_user = 'warning'
mail_pwd = 'aaa'
mail_to = "simon-zzm@163.com"
mail_cc = "simon-zzm@"
secure_file = '/var/log/secure'
conn_fail_key = 'Failed password'
conn_access_key = 'Accepted password'
exclude_ip = ['192.168.100.8', \
              '192.168.100.10', \
              '192.168.100.11']
my_path = os.getcwd()


####
def mail_send(text):
    content = '%s' % text
    msg = MIMEText(content)
    msg['From'] = mail_user
    msg['Subject'] = 'access login server'
    msg['To'] = mail_to
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user, mail_pwd)
        s.sendmail(mail_user, [mail_to, mail_cc], msg.as_string())
        s.close()
    except Exception, e:
        print e

####
# get local host ip
####
def get_ip_address():
    ip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read()
    ip = ip[ip.find(':')+1:ip.find('\n')]
    return ip

#### 
def parse_secure(_data):
    # 获取IP地址
    re_ip = re.compile(r'''\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}''',re.DOTALL)
    try:
        get_ip = re_ip.findall(_data)[0]
    except:
        get_ip = ''
    #### 获得关键字位置
    try:
        key_index = _data.index(conn_access_key)
    except:
        key_index = 0
    #### 将正常登陆但不在已知范围的IP获取
    if (get_ip not in exclude_ip) and (get_ip != '') and (key_index > 0):
        return get_ip
    else:
        return ''


def main():
    #### 获取上次分析的最后一行
    try:
        last_line = open('%s/lastline.txt' % my_path, 'rb').readlines()[0][:-1]
    except:
        last_line = ''
    #### 打开安全日志,并记录最后一行
    get_secure = open(secure_file, 'rb').readlines()
    write_line = open('%s/lastline.txt' % my_path, 'wb')
    write_line.write(get_secure[-1])
    write_line.close()
    #### 获取没有处理的数据,如果最后一行为空着处理全部数据。
    if last_line != "":
        last_id = get_secure.index("%s\n" % last_line)
        get_secure = get_secure[last_id + 1:]
    #### 开始处理数据,只处理登陆成功和登陆失败部分数据
    access_login_list = ''
    for _get in get_secure:
        re_get_ip = parse_secure(_get)
        if re_get_ip != '':
            access_login_list += "%s " % re_get_ip
    #### 判断是否需要报警
    if len(access_login_list) > 1:
        mail_send("%s access login %s server" % (access_login_list, get_ip_address())) 


if __name__ == '__main__':
    while True:
        main()
        time.sleep(3)

  shell 脚本

#! /bin/bash
#
# make simon-zzm@163.com
#
#
### END INIT INFO

# Source function library.
. /etc/profile
cd `pwd`
key=monitoring_secure.py
# See how we were called.
case "$1" in
  stop)
     /bin/ps -ef|grep "${key}"|grep -v grep |awk ' ''{print $2}'|xargs kill -9
     ;;
  start)
      /usr/local/bin/python ${key} &
      ;;
  restart)
      stop
      sleep 1
      /usr/local/bin/python ${key} &
      ;;
  check)
      process_count=`/bin/ps -ef|grep "${key}"|grep -v grep|wc -l`
      case "${process_count}" in
          0)
            $0 start
            ;;
          1)
            ;;
          *)
           $0 stop
           sleep 1
           $0 start
           ;;
      esac
      ;;
  status)
      /bin/ps -ef|grep "${key}"|grep -v grep 
      ;;
  *)
        echo $"Usage: $0 {stop|start|restart|check|status}"
        exit 1
esac

exit

  crontab的配置,每8个小时检查一次。
0 */8 * * * /bin/sh /program/script/check_login_user/monitoring_secure.sh check >/dev/null 2>&1
代码下载

5月 15

tomcat 日志切割

日志自动切割以前使用cronolog进行,apache为http://www.simonzhang.net/?p=362,tomcat为http://www.simonzhang.net/?p=359。
但是tomcat7 以后启动叫脚本改了,也就不麻烦了,直接自己写个shell解决,此脚本会丢失少量正在切割时产生的日志。

#!/bin/sh
log_dir=("/program/allweb/tomcat_a/logs" "/program/allweb/tomcat/logs")
for (( i=0 ; i<${#log_dir[@]} ; i++ ))
do
    if [ -f ${log_dir[i]}\/catalina.out ]; then
        cd ${log_dir[i]}
        date_dir=`date +%Y-%m-%d`
        /bin/cp catalina.out  catalina_${date_dir}.out
        /bin/echo '' > catalina.out
        /usr/bin/find -ctime +15 -exec rm -rf {} \;
    fi
done