import subprocess

def scan_ports(target_ip):
    """Scan all ports on the target IP using nmap."""
    try:
        result = subprocess.run(['nmap', '-p-', target_ip], capture_output=True, text=True, check=True)
        return parse_open_ports(result.stdout)
    except subprocess.CalledProcessError as e:
        print("Error during port scanning:", e)
        return []

def parse_open_ports(nmap_output):
    """Parse nmap output to extract open ports."""
    open_ports = []
    lines = nmap_output.split('\n')
    for line in lines:
        if '/tcp' in line and 'open' in line:
            port = line.split('/')[0].strip()
            open_ports.append(port)
    return open_ports

def scan_vulnerabilities(target_ip, open_ports):
    """Scan for vulnerabilities on open ports using nmap with the vulners script."""
    for port in open_ports:
        try:
            # Ensure the port number is passed as a string in the command list
            port_str = str(port)  # Convert port number to string if it isn't already
            command = ['nmap', '-sV', '--script', 'vulners', '--script-args', 'min_cvss=7.0', '--scan-delay', '1s', '-p', port_str, target_ip]
            result = subprocess.run(command, capture_output=True, text=True, check=True)

            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print(f"Error during vulnerability scan on port {port}:", e)

def save_scan_result(scan_result, filename, location):
    """Save the scan result to a file."""
    try:
        with open(location + filename, "w") as file:
            file.write(scan_result)
        print(f"Scan result saved to: {location}{filename}")
    except Exception as e:
        print(f"Error saving scan results: {e}")
