0

How can I check if an CLI argument has been entered incorrectly using argparse or sys.argv and then print something?

The arguments are:

--remote_host google.com --verbose 0 (or verbose 1 for full verbosity...)

or

--help

#!/usr/bin/env python

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import argparse
import sys
from scapy.all import *

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--remote_host")
parser.add_argument("--verbose")
parser.add_argument("--help", action='store_true')
args = parser.parse_args()

if args.help:
    print("Custom Help Section...")
    exit()
 
# Define end host and TCP port range
hostInput    = args.remote_host
host  = socket.gethostbyname(hostInput)
port_range = [21,22,23,25,53,80,110,135,137,138,139,443,1433,1434,8080]

# Send SYN with random Src Port for each Dst port
for dst_port in port_range:
    src_port = random.randint(1025,65534)
    resp = sr1(
        IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=1,
        verbose=int(args.verbose),
    )

    if resp is None:
        print(f"{host}:{dst_port} is filtered (silently dropped).")

    elif(resp.haslayer(TCP)):
        if(resp.getlayer(TCP).flags == 0x12):
            # Send a gratuitous RST to close the connection
            send_rst = sr(
                IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags='R'),
                timeout=1,
                verbose=int(args.verbose),
            )
            print(f"{host}:{dst_port} is open.")

        elif (resp.getlayer(TCP).flags == 0x14):
            print(f"{host}:{dst_port} is closed.")

    elif(resp.haslayer(ICMP)):
        if(
            int(resp.getlayer(ICMP).type) == 3 and
            int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13]
        ):
            print(f"{host}:{dst_port} is filtered (silently dropped).")
IlludiumPu36
  • 4,196
  • 10
  • 61
  • 100

1 Answers1

1

You can simply get all the CLI arguments with:

arglist = sys.argv[1:]  # first parameter is always script name

Then, you can just run a check against a list of available commands, like:

available_commands = ['--help', '--remote_host', 'google.com', '--verbose', '0', '1']
for arg in arglist:
    valid = False
    for command in available_commands:
        if arg == command: valid = True
    if not valid:
        raise ValueError('Invalid command name')
q9i
  • 205
  • 2
  • 11
  • Thanks. Does this use argparse, or just the scapy/python code? if it doesn't use argparse, perhaps I should just use sys.argv in my code instead of argparse. i'm a complete noob at python... – IlludiumPu36 Jun 29 '21 at 04:28
  • This clearly does not use ArgParse. For simple option processing, directly picking apart the command line is a feasible alternative; ArgParse is rather complex. Though if your question is "is there a way to get ArgParse to verify that the option argument is of a certain type" the answer to that is definitely yes. – tripleee Jun 29 '21 at 04:30