我的服务器每天都有很多人尝试SSH登录,这些有规律的登录是利用机器人程序尝试猜密码产生的(使用Hydra通过ssh破解密码)。
我想知道这些烦人的IP属于哪个国家。下面本人就使用简单的Python脚本看看哪个国家的鸟人最多。
auth.log日志:
由于我设置了长达20位的root密码,这种暴力破解方式很难破解。
保护SSH参考:
# 安装GeoIP
1 |
pip install pygeoip |
GeoIP的使用参考:http://pygeoip.readthedocs.io/en/v0.3.2/getting-started.html
# 下载GeoIP数据了
1 2 |
$ wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz $ wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz |
下载完成之后解压数据文件。
# 代码
提取日志文件中的IP地址:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def read_log(logfile): log = open(logfile, 'r') lines = log.readlines() print(len(lines)) log.close() logs = [] for line in lines: if 'pam_unix' in line: items = line.split() for item in items: if 'rhost' in item: ip = item.split('=')[1] # ip logs.append(ip) return list(set(logs)) # 去除重复IP ip_list = read_log("./auth.log") print(ip_list) print(len(ip_list)) |
获得IP所在国家:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
def is_ipv4(ip): match = re.match("^(\d{0,3})\.(\d{0,3})\.(\d{0,3})\.(\d{0,3})$", ip) if not match: return False quad = [] for number in match.groups(): quad.append(int(number)) if quad[0] < 1: return False for number in quad: if number > 255 or number < 0: return False return True gi = pygeoip.GeoIP('./GeoIP.dat') FuckCountry = [] for ip in ip_list: if is_ipv4(ip) is True: FuckCountry.append( gi.country_name_by_addr(ip) ) else: FuckCountry.append( gi.country_name_by_name(ip) ) counter=collections.Counter(FuckCountry) print(counter) |
LOL