import subprocess
import re

def execute_command_streaming(method, target):
    commands = {
        'ping': ['ping', '-c', '4', target],
        'ping6': ['ping', '-c', '4', target],
        'mtr': ['mtr', '-w', '-r', '-c', '10', target],
        'mtr6': ['mtr', '-w', '-r', '-c', '10', target],
        'traceroute': ['traceroute', '-n', target],
        'traceroute6': ['traceroute', '-n', target],
    }

    if method not in commands:
        yield f"Error: Invalid method '{method}'."
        return

    command = commands[method]

    try:
        proc = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=1,
            universal_newlines=True
        )

        for line in iter(proc.stdout.readline, ''):
            yield line
            
        proc.stdout.close()
        proc.wait()
        
    except FileNotFoundError:
        yield f"Error: Command '{command[0]}' not found. Is it installed on the server?"
    except Exception as e:
        yield f"An unexpected error occurred: {e}"