排查系统是否被***是系统管理员定期做的一个工作,而查看登陆过的ip是排查的第一步,本篇博客就是根据last命令查看登陆过的ip的归属地的一个脚本,来帮助系统管理员查看有没有可疑地区的ip登陆!可以根据需求更改last -n的参数,可结合crontab做成计划任务,也可单独执行本脚本适用于Centos Python3+#!/usr/bin/python3# -*- coding: UTF-8 -*-import osimport urllib.requestimport redef ip_file(): os.system('last -10 >> last.txt') r = open('last.txt', 'r') w = open('ip.txt', 'w') count_AG = 0 count_AT = 0 count_AC = 0 for line in r: dat_in = line.split() count = (dat_in[2]) w.write(count + '\n') w.write('exit') r.close() w.close()def get_result(): url = "http://www.ip138.com/ips138.asp?ip=%s&action=2" % ips u = urllib.request.urlopen(url) s = u.read() s = s.decode('GBK') ipa = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',s) print("\n****** Below Result From IP138 Database *****") print("IP Address:",ipa[0]) result = re.findall(r'(
.*?)',s) for i in result: print(i[4:-5]) print("*"*45) print('\n')try: while True: ip_file() p = open('ip.txt', 'r') p.seek(0, 0) for ipx in p: ip = ipx.split() ips = ''.join(ip) if ip == "" or ip == 'exit': break else: get_result()except: print ("Not Data Find") os.system('rm -f last.txt ip.txt' )