#Ftp
import ftplib
import re
import  ipaddress
from tools.ToolBase import ToolBase

class FtpTool(ToolBase):

    def is_ip_domain(self,str):
        # IP 地址校验(支持 IPv4/IPv6)
        try:
            ipaddress.ip_address(str)
            return True
        except ValueError:
            pass


        # 域名格式校验
        domain_pattern = re.compile(
            r'^(?!(https?://|www\.|ftp://))'  # 排除 URL 协议
            r'([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)'  # 子域名
            r'+[a-zA-Z]{2,63}$'  # 顶级域名(2-63个字母)
        )

        # 总长度校验(域名最大253字符)
        return bool(domain_pattern.match(str)) and len(str) <= 253

    def test_anonymous_ftp_login(self,host, username='anonymous', password='anonymous@example.com'):
        try:
            # 创建 FTP 客户端实例并连接服务器
            ftp = ftplib.FTP(host)
            # 尝试使用匿名凭据登录
            ftp.login(username, password)
            # 登录成功,打印消息
            res = f"匿名登录成功: {host}"
            # 关闭连接
            ftp.quit()
        except ftplib.all_errors as e:
            # 登录失败,打印错误信息
            res = f"匿名登录失败: {host} - {e}"
        return res

    def validate_instruction(self, instruction):
        #ftp暂时不做指令过滤和变化,只执行匿名攻击
        timeout = 0
        #lines = instruction.splitlines()
        # if(len(lines) > 1):
        #     modified_code = "\n".join(lines[1:])
        # else:
        #     modified_code = ""
        #print(modified_code)
        modified_code = "ftp匿名登录测试"
        return modified_code,timeout

    #对于非sh命令调用的工具,自己实现命令执行的内容
    def execute_instruction(self, instruction_old):
        ext_params = self.create_extparams()
        # 第一步:验证指令合法性
        instruction,time_out = self.validate_instruction(instruction_old)
        if not instruction:
            return False, instruction_old, "该指令暂不执行!","",ext_params
        # 过滤修改后的指令是否需要判重?同样指令再执行结果一致?待定---#?

        # 第二步:执行指令
        #target = instruction_old.split()[1] #有赌的成分!
        target = ""
        for str in instruction_old.split():
            if self.is_ip_domain(str):
                target = str

        if target:
            output = self.test_anonymous_ftp_login(target)
        else:
            output = f"ftp指令未兼容{instruction_old}"

        # 第三步:分析执行结果
        analysis = self.analyze_result(output,instruction,"","")

        return True, instruction, analysis,output,ext_params

    def analyze_result(self, result,instruction,stderr,stdout):
        #
        return result