import re
import subprocess
import tempfile
import os
import pexpect
import struct
import sys
import mysql.connector
import requests


def do_worker(str_instruction):
    try:
        # 使用 subprocess 执行 shell 命令
        result = subprocess.run(str_instruction, shell=True, text=True,capture_output=True)

        return {
            "returncode": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {"error": str(e)}

def do_worker_ftp_pexpect(str_instruction):
    # 解析指令
    lines = str_instruction.strip().split('\n')
    cmd_line = lines[0].split('<<')[0].strip()  # 提取 "ftp -n 192.168.204.137"
    inputs = [line.strip() for line in lines[1:] if line.strip() != 'EOF']

    # 使用 pexpect 执行命令
    child = pexpect.spawn(cmd_line)
    for input_line in inputs:
        child.expect('.*')  # 等待任意提示
        child.sendline(input_line)  # 发送输入
    child.expect(pexpect.EOF)  # 等待命令结束
    output = child.before.decode()  # 获取输出
    child.close()
    return output

def do_worker_ftp_script(str_instruction):
    # 创建临时文件保存输出
    with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
        output_file = tmpfile.name

    # 构建并执行 script 命令
    script_cmd = f"script -c '{str_instruction}' {output_file}"
    result = subprocess.run(script_cmd, shell=True, text=True)

    # 读取输出文件内容
    with open(output_file, 'r') as f:
        output = f.read()

    # 删除临时文件
    os.remove(output_file)
    return output


import socket


def dynamic_fun():
    try:
        host = "192.168.204.137"
        port = 8009
        # 尝试建立连接
        sock = socket.create_connection((host, port), timeout=15)
        # 发送一个基础的AJP协议探测包(仅用于检测响应)
        payload = b'\x12\x34\x00\x02'  # 示例数据包
        sock.sendall(payload)
        response = sock.recv(1024)
        sock.close()
        if response:
            return (1, "收到响应,可能存在CVE-2020-1938漏洞风险,请进一步人工验证")
        else:
            return (0, "无响应,暂未检测到漏洞")
    except Exception as e:
        return (0, "连接失败或错误: " + str(e))

if __name__ == "__main__":
    # 示例使用
    bok,res = dynamic_fun()
    print(bok,res)