大部分安全工作者都会选择学习python这门语言,常用的内建模块以及大量的第三方模块能够帮助我们快速的实现自己的目的。在日常的安全运维中,很多时候我们会碰到避免安装第三方软件或是第三方软件无法契合自己需求的情况,这个时候我们就可以掏出python来定制属于我们自己的小工具。
前段时间刚好碰到这个需求,客户的服务器是windows,为了对其加固并保证其安全性需要实时监控它的远程桌面连接,便自己抽空用python写了一个,包含的功能有限制远程连接IP地址、询问是否断开连接以及当有用户远程登陆成功后向管理员的邮箱发送登陆者的IP地址信息等。(windows防火墙本身自带限制远程连接IP地址功能,这里为了方便统一化管理,便也添加了这个功能)
整体逻辑就是当有一个新的远程桌面连接产生时,获取其IP地址并检查此地址是否为限制地址范围内的IP,如若不是则直接断开连接并发送邮件至管理员账户告知;如若是则发送邮件通知管理员已产生新的远程连接,之后管理员可选择是否断开此连接。
其中用到了windows下几个很简单的命令:query user、netstat –an以及TSDISCON [ID]命令 :
“query user”命令用来登录到服务器上的所有用户的信息。
“netstat –an”命令用来查询远程连接的IP地址。
“TSDISCON [ID]”命令通过query user获取会话ID值来中断远程会话连接。
直接从命令输出中通过正则来匹配需要的信息。
reObj1 = re.compile('console')
reObj11 = re.compile('s(www-www#d)s')
reObj2 = re.compile('consoles+(d)s')
reObj22 = re.compile('www-www#ds+(d)s')
reObj3 = re.compile('3389s+(d+.d+.d+.d+):d+s+ESTABLISHED')
运行时 :
每隔5秒探测一次远程连接情况。
代码:
# -*- coding: cp936 -*-
import os
import re
import time
import email
import smtplib
from email.mime.text import MIMEText
def send_mail(reO3):
re3 = ''
for re3 in reO3 :
if re3 != '':
_user = 'email@***.com' #任意邮箱
_pwd = 'password' #邮箱密码
_to = 'email@***.com' #管理员邮箱
msg = MIMEText('IP address '+ re3 + ' has already been connected .')
msg["Subject"] = 'Warning : remote access to 3389'
msg["From"] = _user
msg["To"] = _to
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.login(_user, _pwd)
s.sendmail(_user, _to, msg.as_string())
s.quit()
print "Mail Success!"
except smtplib.SMTPException,e:
print "Falied,%s"%e
def main():
command1 = 'query user'
command3 = 'netstat -an'
while 1 == 1:
time.sleep(5)
r = os.popen(command1)
info1 = r.readlines()
line1 = ''
for l1 in info1:
line1 = line1 + l1
print line1
r = os.popen(command3)
info2 = r.readlines()
line2 = ''
for l2 in info2:
line2 = line2 + l2
reObj1 = re.compile('console')
reObj11 = re.compile('s(www-www#d)s')
reObj2 = re.compile('consoles+(d)s')
reObj22 = re.compile('www-www#ds+(d)s')
reObj3 = re.compile('3389s+(d+.d+.d+.d+):d+s+ESTABLISHED')
reO1 = reObj1.findall(line1) + reObj11.findall(line1)
reO2 = reObj2.findall(line1) + reObj22.findall(line1)
reO3 = reObj3.findall(line2)
send_mail(reO3)
reOD = dict(zip(reO1,reO2))
print reOD
n = 0
for reI in reO1:
if reI != 'console':
print '[+]IP address ' + reO3[n] + ' has already been connected .'
ip = reO3[n]
n = n + 1
command2 = 'TSDISCON ' + reOD[reI]
if not re.match('192.168.31.d+',ip): #限制IP地址正则
os.popen(command2)
continue
b = raw_input('Do you need disconnect the connection (y/n):')
if b == 'y' :
os.popen(command2)
print '[+]The session ID:' + reOD[reI] + ' , IP: ' + ip + ' has already been completed .'
else :
pass
if __name__ == "__main__":
main()
这样我们就可以很方便的监控远程桌面连接了。代码还可以再进一步扩展来实现更多的功能,例如管理员只需直接回复一封邮件就可以控制远程连接的通断等等。大家可以自由的扩展想象,实现自己想要的功能,这也是编程语言的魅力所在。
对于python在安全运维方面的运用,后续还会继续放出,敬请期待。