You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.9 KiB

2 months ago
'''
对目标资产的管理包括信息的更新维护等
'''
import re
#pattern = r'^(https?://)?((?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|(?:\d{1,3}\.){3}\d{1,3})(:\d+)?(/.*)?$'
pattern = r'^(https?://)?((?:[0-9]{1,3}\.){3}[0-9]{1,3}|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})(:\d+)?(/.*)?$'
class TargetManager:
def __init__(self):
pass
# 辅助函数:验证IPv4地址的有效性
def _is_valid_ipv4(self,ip):
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit() or not 0 <= int(part) <= 255:
return False
return True
#验证目标格式的合法性,并提取域名或IP
def validate_and_extract(self,input_str):
'''
:param input_str:
:return: bool,str,int(1-IP,2-domain)
'''
regex_match = re.fullmatch(pattern, input_str)
type = None
if regex_match:
domain_or_ip = regex_match.group(2)
# 仅对 IPv4 格式的字符串进行有效性验证
if re.fullmatch(r'\d{1,3}(\.\d{1,3}){3}', domain_or_ip):
if not self._is_valid_ipv4(domain_or_ip):
return False, None,type
else:
type = 1 #IP
else:
type = 2 #domain
return True, domain_or_ip,type
else:
return False, None,type
if __name__ == "__main__":
tm = TargetManager()
# 示例测试
test_cases = [
"http://192.168.1.1:8080/path",
"https://example.com",
"192.168.1.1:80",
"example.com/path/to/resource",
"ftp://invalid.com", # 不合规
"http://300.400.500.600" # 不合规
]
for case in test_cases:
is_valid, result = tm.validate_and_extract(case)
print(f"输入: '{case}' → 合规: {is_valid}, 提取结果: {result}")