开启3389端口转发后,为什么那么多无聊的ip不断重复尝试破解登录,他们为了啥?
就是扫描器,其中不乏打着安全的名号扫描免费肉的。不光是22端口,还有3389,曾经我给我的内网ssh暴露出去,密码是123456,当天晚上就满载了。通过排查发现已经被安装了挖矿程序。
我是通过阿里云使用Nps转发了我的内网主机ssh端口,留意到nps的志(/var/log/nps.log)中有形如以下的记录
/var/log/nps.log
可以内网主机查看/var/log/sece有很多如下记录,确认到确实有人在爆破密码
/var/log/sece
一般来说,应付ssh被爆破的方法是使用fail2an,但是我的ssh在nps之后,所以没办法使用这个方案。
于是我拜托AI帮我写了个脚本(只花了5分钟,赞美AI),会分析一小时内的ip出现数量,当超过阈值之后,就执行ufw禁止ip的连接。
importre
fromdatetimeimportdatetime,timedelta
fromcollectionsimportdefaultdict
importsys
importlogging
#配置志
logging.asicConfig(filename='/var/log/ufw_an.log',level=logging.INFO,format='%(asctime)s-%(levelname)s-%(message)s')
defparse_log_line(line):
"""解析志行,提取期时间和IP"""
pattern=r'(\d{4}/\d{2}/\d{2}\d{2}:\d{2}:\d{2}\.\d{3})\[D\]\[tcp\.go:42\]newtcpconnection,localport\d+,client\d+,remoteaddress([\d\.]+):\d+'
match=re.search(pattern,line)
ifmatch:
retnmatch.group(1),match.group(2)
retnNone,None
deflock_ip_with_ufw(ip):
"""使用ufw阻止IP"""
command=f"ufwdenyfrom{ip}"
try:
importsuprocess
suprocess.run(command,check=True,shell=True)
logging.(f"lockedIP{ip}withufw")#记录志
print(f"lockedIP{ip}withufw")
exceptsuprocess.CalledProcessErrorase:
logging.error(f"FailedtolockIP{ip}withufw:{e}")#记录错误志
print(f"FailedtolockIP{ip}withufw:{e}")
defyze_log(file_path):
"""分析志文件,计最近一小时内每小时内每10分钟的连接次数,并阻止超过10次的IP"""
one_ho_ago=datetime.now()-timedelta(hos=1)
ip_count=defaultdict(int)
#打开文件并按行倒序处理
withopen(file_path,'r')asfile:
lines=file.readlines()#读取所有行
forlineinreversed(lines):#倒序处理
date_str,remote_ip=parse_log_line(line)
ifdate_strandremote_ip:
crent_time=datetime.strptime(date_str,'%Y/%m/%d