排查系統是否被***是系統管理員按期作的一個工做,而查看登錄過的ip是排查的第一步,本篇 博客就是根據last命令查看登錄過的ip的歸屬地的一個腳本,來幫助系統管理員查看有沒有可疑地區的 ip登錄! 能夠根據需求更改last -n的參數,可結合crontab作成計劃任務,也可單獨執行 本腳本適用於Centos Python3+ #!/usr/bin/python3 # -*- coding: UTF-8 -*- import os import urllib.request import re def 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'(<li>.*?</li>)',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' )