Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.0 kB
18
Indexable
Never
import sys
import json
import subprocess

def scan_ports(ip_address):
    command = ['/home/user/mybinary', '-host', ip_address, '-j', 'json']
    
    try:
        print(f"Running command: {' '.join(command)}")  # Log the command being run

        # Run the command and capture the output with a timeout
        result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=120)
        
        # Log stdout and stderr for debugging
        stdout = result.stdout
        stderr = result.stderr
        
        print(f"Command stdout: {stdout}")
        print(f"Command stderr: {stderr}")

        if result.returncode != 0:
            return json.dumps({"output": [{"type": "error", "value": f"Error running n: {stderr.strip()}"}]}, indent=2)
        
        output_lines = stdout.splitlines()
        
        output = []
        for line in output_lines:
            try:
                scan_data = json.loads(line)
                if isinstance(scan_data, dict) and 'port' in scan_data and scan_data['port'] > 0:
                    output.append({
                        "type": "port",
                        "value": f"{ip_address}:{scan_data['port']}"
                    })
            except json.JSONDecodeError:
                continue
        
        return json.dumps({"output": output}, indent=2)
    
    except subprocess.TimeoutExpired:
        return json.dumps({"output": [{"type": "error", "value": "Command timed out"}]}, indent=2)
    
    except Exception as e:
        return json.dumps({"output": [{"type": "error", "value": f"Unexpected error occurred: {e}"}]}, indent=2)

def main():
    # Check if the IP address argument is provided
    if len(sys.argv) != 2:
        print("Usage: python script.py <IP_ADDRESS>")
        sys.exit(1)

    ip_address = sys.argv[1].strip()
    
    # Perform the port scan and print the result
    result = scan_ports(ip_address)
    print(result)

if __name__ == "__main__":
    main()
Leave a Comment