Command-Line Tools with argparse
A script becomes a tool the day someone else runs it. They will pass the wrong flag, a port range written backwards, a target you never meant to allow, and they will pipe the output into another program. The command line is the tool's first input boundary, so it deserves the same care as a network parser: every value validated as it is read, clear errors, exit codes that mean something, and help text that states the scope. Python's standard argparse does most of this if you let it.
Definitions
ArgumentParser: declares the options;parse_args(argv)reads them (fromsys.argv[1:]whenargvis omitted, which is why passing a list makes a CLI testable).type=: a function that converts and validates one value; raisingargparse.ArgumentTypeErrorgives a clean error message.choices=,nargs=,required=,default=: constraints argparse enforces for you.- Mutually exclusive group: options of which at most one may be given (
--jsonor--csv). - Subcommands (
add_subparsers):tool scan …,tool report …, each with its own options, likegitoropenssl. - On a usage error argparse prints the usage and the message to stderr and exits with status 2.
A validated CLI
The parser below is the front end of the TCP connectivity checker built later in the course. The validators enforce the scope (loopback and the lab network only), parse port lists like 22,80,8000-8002 with limits, and refuse nonsense before any work starts. Calling parse_args with lists lets the example show several command lines in one run; exit_on_error=False (Python 3.9 and later) makes errors raise instead of exiting, for the same reason.
import argparse, ipaddress
SCOPE = [ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("10.10.0.0/24")]
MAX_PORTS = 1024
def target(text):
try:
addr = ipaddress.ip_address(text)
except ValueError:
raise argparse.ArgumentTypeError(f"{text!r} is not an IP address (names are not resolved)")
if not any(addr in n for n in SCOPE):
raise argparse.ArgumentTypeError(f"{addr} is outside the authorized scope")
return addr
def ports(text):
out = set()
for part in text.split(","):
lo, _, hi = part.partition("-")
if not lo.isdigit() or (hi and not hi.isdigit()):
raise argparse.ArgumentTypeError(f"bad port item {part!r}")
a, b = int(lo), int(hi or lo)
if not (1 <= a <= b <= 65535):
raise argparse.ArgumentTypeError(f"bad range {part!r} (1-65535, low-high)")
out.update(range(a, b + 1))
if len(out) > MAX_PORTS:
raise argparse.ArgumentTypeError(f"{len(out)} ports, limit is {MAX_PORTS}")
return sorted(out)
def build_parser():
p = argparse.ArgumentParser(prog="tcpcheck", exit_on_error=False,
description="Check TCP ports on hosts you are authorized to test (127.0.0.0/8, 10.10.0.0/24).")
p.add_argument("targets", nargs="+", type=target, help="IP addresses in scope")
p.add_argument("-p", "--ports", type=ports, required=True, help="e.g. 22,80,8000-8002")
p.add_argument("--timeout", type=float, default=1.0, help="seconds per connection (default 1.0)")
out = p.add_mutually_exclusive_group()
out.add_argument("--json", action="store_true")
out.add_argument("--csv", action="store_true")
return p
parser = build_parser()
for argv in (["127.0.0.1", "-p", "22,8000-8002", "--json"],
["10.10.0.10", "10.10.0.11", "--ports", "443"],
["192.0.2.10", "-p", "80"],
["lab.test", "-p", "80"],
["127.0.0.1", "-p", "9000-8000"],
["127.0.0.1", "-p", "1-5000"],
["127.0.0.1", "-p", "80", "--json", "--csv"]):
try:
a = parser.parse_args(argv)
print("OK ", [str(t) for t in a.targets], a.ports, "json" if a.json else "csv" if a.csv else "text")
except argparse.ArgumentError as e:
print("ERROR", e)
print()
print(parser.format_usage().strip())OK ['127.0.0.1'] [22, 8000, 8001, 8002] json
OK ['10.10.0.10', '10.10.0.11'] [443] text
ERROR argument targets: 192.0.2.10 is outside the authorized scope
ERROR argument targets: 'lab.test' is not an IP address (names are not resolved)
ERROR argument -p/--ports: bad range '9000-8000' (1-65535, low-high)
ERROR argument -p/--ports: 5000 ports, limit is 1024
ERROR argument --csv: not allowed with argument --json
usage: tcpcheck [-h] -p PORTS [--timeout TIMEOUT] [--json | --csv]
targets [targets ...]
Every bad command line is rejected with a message that says what is wrong, and none of them reaches the part of the tool that would open a connection. In the real tool, exit_on_error stays at its default, so argparse prints the usage and exits with status 2, which scripts can test for.
The tool's other half: exit codes and streams
The main function that uses the parser follows the convention from Designing a Small Security Tool: findings to stdout, diagnostics to stderr, and an exit code. Writing it as main(argv=None) -> int makes it testable without a subprocess:
import argparse, json, sys
def main(argv=None):
p = argparse.ArgumentParser(prog="hashlist", exit_on_error=False)
p.add_argument("--expect", required=True, help="name=sha256 pairs, comma-separated")
p.add_argument("--json", action="store_true")
try:
args = p.parse_args(argv)
expected = dict(item.split("=", 1) for item in args.expect.split(","))
except (argparse.ArgumentError, ValueError) as e:
print(f"hashlist: error: {e}", file=sys.stderr)
return 2
actual = {"a.txt": "11aa", "b.txt": "22bb"} # stands in for hashing real files
bad = sorted(n for n, h in expected.items() if actual.get(n) != h)
for n in bad:
print(json.dumps({"file": n, "expected": expected[n], "actual": actual.get(n)}) if args.json
else f"MISMATCH {n}")
return 1 if bad else 0
sys.stderr = sys.stdout # show stderr in this example's output
for argv in (["--expect", "a.txt=11aa,b.txt=22bb"],
["--expect", "a.txt=11aa,b.txt=ffff", "--json"],
["--expect", "a.txt"]):
print("exit", main(argv))exit 0
{"file": "b.txt", "expected": "ffff", "actual": "22bb"}
exit 1
hashlist: error: dictionary update sequence element #0 has length 1; 2 is required
exit 2
How CLI weaknesses are found
- Try the hostile arguments yourself: empty strings, huge numbers, reversed ranges, names where addresses are expected, a value starting with
-, options given twice. Every one should produce a clear error and exit 2. - Read the help: if
--helpdoes not state what the tool touches, users will guess. - Check what happens on partial failure: a tool that crashes with a traceback halfway through a list of targets leaves the user unsure which ones ran.
How to make the CLI robust
- Validate in
type=functions, so bad values never reach the tool's logic. - Make dangerous behaviour opt-in with a long, explicit flag (
--write-baseline,--really-delete), never the default. - Cap sizes: number of targets, ports, lines, bytes.
- Exit codes 0/1/2, findings on stdout, errors on stderr,
--jsonfor machines. - No secrets on the command line. Arguments are visible to every user in
psand are saved in shell history. Read keys from a file with tight permissions, an environment variable, or a prompt (getpass).
Pitfalls
type=booldoes not do what you expect:bool("False")isTrue. Useaction="store_true".- Prefix matching. argparse accepts unambiguous abbreviations (
--timfor--timeout); setallow_abbrev=Falseif a future option could make an old abbreviation mean something else. nargs="*"with no values gives an empty list; make sure "no targets" is an error, not "check nothing and exit 0".
Practice
1. Add --max-rate (connections per second) that accepts only 1 to 100. What should --max-rate 0 do?
A type= function that converts with int() and raises ArgumentTypeError outside 1–100. --max-rate 0 is a usage error: message and exit 2. Rate limits keep even an in-scope check from looking like a flood in the target's logs.
2. Why does the scope validator refuse lab.test instead of resolving it?
Name resolution happens at a different time from connection and can return different answers (DNS changes, /etc/hosts, rebinding). The tool would check one address and connect to another. Taking addresses only, or resolving once and checking the address that will actually be used, removes the gap.
3. A colleague wants to pass an API key as --key abc123. What do you suggest?
--key-file path (read it, check the file is not world-readable), or an environment variable such as TOOL_API_KEY. Command lines show up in ps, /proc/<pid>/cmdline, shell history and process-creation logs.
Test yourself
Which exit status does argparse use for a usage error?
- 0
- 1
- 2
- 255
Where should a port-range check such as 1-65535 be done?
- After the scan, by filtering results
- In a
type=function, so argparse rejects bad values before the tool runs - In the help text
- Nowhere; the OS checks ports
Why write the entry point as main(argv=None) -> int?
- It is required by argparse
- Tests can call it with a list of arguments and check the returned exit code, without starting a process
- It runs faster
- To hide errors
Why shouldn't a tool take a secret as a command-line argument?
- argparse can't parse it
- Arguments are visible in ps, /proc and shell history
- It makes the tool slower
- Secrets must be in JSON