python 查看开启服务
知识点:
1. search()函数会在整个字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None
2. 比如当进行数据库连接时,有时候可能会因为网络原因造成一直连不上,这时候,如果没有去手动停止,socket可能会一直尝试重连,造成资源的浪费
这里我们可以通过设置timeout来限制重连时间,如设置s.settimeout(20) 那么当socket尝试重连到20秒时,就会停止一切操作。提示达到timeout设定阀值
3. connect_ex()方法,该方法如果链接成功会返回0,失败会返回errno库中的errorcode中的key
4. sendall()是对send()的包装,完成了用户需要手动完成的部分,它会自动判断每次发送的内容量,然后从总内容中删除已发送的部分,将剩下的继续传给send()进行发送
5. recv指定数据缓冲区的大小
代码:
import optparse
import time
import socket
import os
import re
SIGNS = (
# 协议 | 版本 | 关键字
b'FTP|FTP|^220.*FTP',
b'MySQL|MySQL|mysql_native_password',
b'oracle-https|^220- ora',
b'Telnet|Telnet|Telnet',
b'Telnet|Telnet|^\r\n%connection closed by remote host!\x00$',
b'VNC|VNC|^RFB',
b'IMAP|IMAP|^\* OK.*?IMAP',
b'POP|POP|^\+OK.*?',
b'SMTP|SMTP|^220.*?SMTP',
b'Kangle|Kangle|HTTP.*kangle',
b'SMTP|SMTP|^554 SMTP',
b'SSH|SSH|^SSH-',
b'HTTPS|HTTPS|Location: https',
b'HTTP|HTTP|HTTP/1.1',
b'HTTP|HTTP|HTTP/1.0',
)
def regex(respose, port):
test = ""
if re.search(b'<title>502 Bad Gateway', respose):
proto = {"Service failed to access!!"}
for pattern in SIGNS:
pattern = pattern.split(b'|')
if re.search(pattern[-1], respose, re.IGNORECASE):
proto = "[" + port + "]" + " open" + pattern[1].decode()
break
else:
proto = "[" + port + "]" + " open " + "Unrecognized"
print(proto)
def requse(ip, port):
response = ''
PROBE = 'GET / HTTP/1.0\r\n\r\n'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout()
result = sock.connect_ex((ip, int(port)))
if result == 0:
try:
sock.sendall(PROBE.encode())
response = sock.recv(256)
if response:
regex(response, port)
except ConnectionAbortedError:
pass
else:
pass
sock.close()
def main():
parser = optparse.OptionParser("Usage:%prog -i <target host> ")
parser.add_option('-i', type='string', dest='IP', help='specify target host')
parser.add_option('-p', type='string', dest='PORT', help='specify target host')
options, args = parser.parse_args()
ip = options.IP
port = optparse.PORT
print("Scan report for " + ip + "\n")
for line in port.split(','):
requse(ip, line)
time.sleep(0.2)
print("\nScan finished!....\n")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("interrupted by user, killing all threads...")