linux防止暴力破解

执行命令:

more /var/log/secure | grep "Failed password"

一堆登录失败的记录,如果登录的ip多很频繁,还会造成服务器无法访问

获取这些ip记录入hosts.deny

 

python 获取失败登录ip代码:

#encoding=utf8

ipDict = {};

def checkBadIP(line):
  s = 'Failed password for root from 60.183.210.207 port 2328 ssh2';
  if line.find('Failed password for ') == -1:
    return False;
  return True;


def getBadIP():
  f = file('/var/log/secure');
  for line in f:
    if checkBadIP(line):
      putBadIP(line);
  f.close();


def putBadIP(line):
  port = getPort(line);
  ip = getIP(line);
  if ip in ipDict:
    ipDict[ip]['number'] = ipDict[ip]['number'] + 1;
    if port not in ipDict[ip]['portList']:
      ipDict[ip]['portList'].append(port);
  else:
    ipDict[ip] = {"portList": [port], "number": 1};


def getPort(line):
  startString = 'port';
  endString = 'ssh2';
  startPos = line.find(startString);
  if startPos > 0:
    startPos = startPos + len(startString);
  else:
    return 0;
  endPos = line.find(endString);
  return line[startPos: endPos].strip();


def getIP(line):
  startString = 'from';
  endString = 'port';
  startPos = line.find(startString);
  endPos = line.find(endString);
  if startPos > 0:
    startPos = startPos + len(startString);
  return line[startPos: endPos].strip();


def printBadIP():
  for ip in ipDict:
    number = ipDict.get(ip).get('number');
    if number > 30:
      print "ip : ", ip
      print "number : ", ipDict[ip]['number']

if __name__ == '__main__':
  getBadIP();
  printBadIP();

posted @ 2017-06-20 14:37  土豆真好吃呀  阅读(263)  评论(0编辑  收藏  举报