好长时间没写啦,更新下
今天分享一个主机端口监控脚本,放在自己主机里面,一但主机被入侵快速发现哈哈。
代码
#coding:utf-8'''__author__ : pickmea'''import jsonimport os, requestsexists = os.path.exists('0.txt')ports = ''# 填写自己的丁丁token的urldingurl = ''headers = {"Content-Type": "application/json"}cmdinfo = os.system("netstat -ntlp|awk '{print $4}' > portinfo.txt")with open('portinfo.txt') as f: portinfos = f.readlines() for portinfo in portinfos: portinfo = portinfo.strip() if portinfo.find('127.0.0.1') >= 0: portinfo = portinfo.split(':')[1] ports = ports+'\n'+portinfo # print("内部端口开放:{}".format(portinfo)) elif portinfo.find('0:') >= 0: portinfo = portinfo.split(':')[1] ports = ports+'\n'+portinfo # print("外部部端口开放:{}".format(portinfo)) elif portinfo.find('::') >= 0: portinfo = portinfo.split(':::')[1] ports = ports+'\n'+portinfo # print("外部部端口开放:{}".format(portinfo))if exists: with open('1.txt', 'w') as f: f.write(ports) with open('1.txt') as f1, open('0.txt') as f2: a0 = [x.strip() for x in f2.readlines()] for y in f1.readlines(): y = y.strip() if y not in a0: print("新端口开放:{}".format(y)) body ={ "msgtype": "text", "text": { "content": "%s 端口开放,请注意!" % y }} res = requests.post(url=dingurl, data=json.dumps(body), headers=headers) os.remove('0.txt') os.rename('1.txt', '0.txt')else: with open('0.txt', 'w') as f: f.write(ports)
脚本中dingurl需要填写自己的tokenurl
将上面代码存储为mp.py。crontab中写入,不会写crontab自己百度就成。
*/3 * * * * /root/.pyenv/shims/python3.6 /root/zhemechangdemingzi-self/mp.py
每隔3分钟运行一次
看下效果。