arthurs 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
arthurs-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Christopher Arthur
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
arthurs-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: arthurs
3
+ Version: 0.1.0
4
+ Summary: Arthurs — Christopher's own library of programs. Currently: nmap only.
5
+ Author: Christopher Arthur
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # Arthurs
13
+
14
+ Christopher's own Python library of programs. Right now it holds
15
+ **one** program only: **nmap**. Other programs will be added later,
16
+ one at a time, each in its own module.
17
+
18
+ ## Run it — type `nmap`
19
+
20
+ Once the library is installed, typing `nmap` runs nmap, exactly
21
+ like always. The library's launcher finds the real nmap on the
22
+ machine and hands it your arguments untouched:
23
+
24
+ ```sh
25
+ nmap --version
26
+ nmap -sn 127.0.0.1
27
+ ```
28
+
29
+ Same thing through the library dispatcher:
30
+
31
+ ```sh
32
+ arthurs nmap --version
33
+ ```
34
+
35
+ ## Guided way — presets
36
+
37
+ Prefer answering questions instead of typing nmap options? The
38
+ launcher walks you through it:
39
+
40
+ ```sh
41
+ python3 -m arthurs
42
+ # Type a program name: nmap
43
+ # Target address [127.0.0.1]: 127.0.0.1
44
+ # Pick 1-3 [ping]: 1
45
+ ```
46
+
47
+ Or in one line:
48
+
49
+ ```sh
50
+ python3 -m arthurs nmap 127.0.0.1 ping
51
+ ```
52
+
53
+ Scan types: `ping` (hosts up, no ports), `quick` (common ports),
54
+ `service` (services / versions).
55
+
56
+ ## Use it from Python
57
+
58
+ ```python
59
+ from arthurs import nmap
60
+ nmap.run("127.0.0.1") # ping scan
61
+ nmap.run("192.168.1.1", scan="quick")
62
+ ```
63
+
64
+ ## If nmap is not installed
65
+
66
+ Arthurs does not install nmap for you — it runs the real nmap on
67
+ the machine and says so plainly if it is missing:
68
+
69
+ - Ubuntu/Debian: `sudo apt install nmap`
70
+ - macOS (Homebrew): `brew install nmap`
71
+ - Windows: https://nmap.org/download.html
72
+
73
+ ## Rule
74
+
75
+ Only scan networks and machines you own, or that you have
76
+ permission to scan.
@@ -0,0 +1,65 @@
1
+ # Arthurs
2
+
3
+ Christopher's own Python library of programs. Right now it holds
4
+ **one** program only: **nmap**. Other programs will be added later,
5
+ one at a time, each in its own module.
6
+
7
+ ## Run it — type `nmap`
8
+
9
+ Once the library is installed, typing `nmap` runs nmap, exactly
10
+ like always. The library's launcher finds the real nmap on the
11
+ machine and hands it your arguments untouched:
12
+
13
+ ```sh
14
+ nmap --version
15
+ nmap -sn 127.0.0.1
16
+ ```
17
+
18
+ Same thing through the library dispatcher:
19
+
20
+ ```sh
21
+ arthurs nmap --version
22
+ ```
23
+
24
+ ## Guided way — presets
25
+
26
+ Prefer answering questions instead of typing nmap options? The
27
+ launcher walks you through it:
28
+
29
+ ```sh
30
+ python3 -m arthurs
31
+ # Type a program name: nmap
32
+ # Target address [127.0.0.1]: 127.0.0.1
33
+ # Pick 1-3 [ping]: 1
34
+ ```
35
+
36
+ Or in one line:
37
+
38
+ ```sh
39
+ python3 -m arthurs nmap 127.0.0.1 ping
40
+ ```
41
+
42
+ Scan types: `ping` (hosts up, no ports), `quick` (common ports),
43
+ `service` (services / versions).
44
+
45
+ ## Use it from Python
46
+
47
+ ```python
48
+ from arthurs import nmap
49
+ nmap.run("127.0.0.1") # ping scan
50
+ nmap.run("192.168.1.1", scan="quick")
51
+ ```
52
+
53
+ ## If nmap is not installed
54
+
55
+ Arthurs does not install nmap for you — it runs the real nmap on
56
+ the machine and says so plainly if it is missing:
57
+
58
+ - Ubuntu/Debian: `sudo apt install nmap`
59
+ - macOS (Homebrew): `brew install nmap`
60
+ - Windows: https://nmap.org/download.html
61
+
62
+ ## Rule
63
+
64
+ Only scan networks and machines you own, or that you have
65
+ permission to scan.
@@ -0,0 +1,23 @@
1
+ """Arthurs — Christopher's own Python library of programs.
2
+
3
+ Right now it holds exactly one program: nmap. Other programs get
4
+ added later, one at a time, in their own module under this package.
5
+
6
+ Usage from Python:
7
+
8
+ from arthurs import nmap
9
+ nmap.run("127.0.0.1") # ping scan of this machine
10
+
11
+ Usage from a terminal (the launcher):
12
+
13
+ python -m arthurs
14
+ # type: nmap (then answer the target / scan questions)
15
+
16
+ Only scan networks and machines you own, or that you have
17
+ permission to scan. Nmap is a real network scanner.
18
+ """
19
+
20
+ from . import nmap
21
+
22
+ __version__ = "0.1.0"
23
+ __all__ = ["nmap"]
@@ -0,0 +1,90 @@
1
+ """Arthurs launcher: type a program name, it runs that program.
2
+
3
+ Right now the only program in Arthurs is nmap, so typing anything
4
+ else just says so. Run it with:
5
+
6
+ python -m arthurs
7
+ python -m arthurs nmap 127.0.0.1
8
+ python -m arthurs nmap 127.0.0.1 quick
9
+ """
10
+
11
+ import sys
12
+
13
+ from . import nmap as nmap_program
14
+ from .nmap import NmapNotFoundError, SCAN_PRESETS
15
+
16
+ PROGRAMS = {
17
+ "nmap": "network scanner — find hosts and open ports",
18
+ }
19
+
20
+
21
+ def _choose_scan(default="ping"):
22
+ print("Scan type:")
23
+ for i, name in enumerate(SCAN_PRESETS, start=1):
24
+ print(f" {i}. {name}")
25
+ try:
26
+ choice = input(f"Pick 1-{len(SCAN_PRESETS)} [{default}]: ").strip()
27
+ except EOFError:
28
+ return default
29
+ if not choice:
30
+ return default
31
+ names = list(SCAN_PRESETS)
32
+ if choice.isdigit() and 1 <= int(choice) <= len(names):
33
+ return names[int(choice) - 1]
34
+ if choice in SCAN_PRESETS:
35
+ return choice
36
+ print(f"Did not understand {choice!r}, using {default}.")
37
+ return default
38
+
39
+
40
+ def _run_nmap_interactive():
41
+ try:
42
+ target = input("Target address [127.0.0.1]: ").strip() or "127.0.0.1"
43
+ except EOFError:
44
+ print("No target given. Stopping.")
45
+ return
46
+ scan = _choose_scan()
47
+ try:
48
+ nmap_program.run(target, scan=scan)
49
+ except NmapNotFoundError as exc:
50
+ print(exc)
51
+ except ValueError as exc:
52
+ print(f"Could not run nmap: {exc}")
53
+
54
+
55
+ def main(argv=None):
56
+ argv = list(sys.argv[1:] if argv is None else argv)
57
+ print("Arthurs — programs:")
58
+ for name, what in PROGRAMS.items():
59
+ print(f" {name} — {what}")
60
+ if argv:
61
+ # python -m arthurs nmap [target] [scan]
62
+ name = argv[0].lower()
63
+ if name != "nmap":
64
+ print(f"{name!r} is not in Arthurs yet. Only nmap is.")
65
+ return 1
66
+ target = argv[1] if len(argv) > 1 else "127.0.0.1"
67
+ scan = argv[2] if len(argv) > 2 else "ping"
68
+ try:
69
+ nmap_program.run(target, scan=scan)
70
+ except (NmapNotFoundError, ValueError) as exc:
71
+ print(exc)
72
+ return 1
73
+ return 0
74
+ try:
75
+ name = input("Type a program name: ").strip().lower()
76
+ except EOFError:
77
+ print("Nothing typed. Only nmap is in Arthurs right now.")
78
+ return 1
79
+ if name == "nmap":
80
+ _run_nmap_interactive()
81
+ return 0
82
+ if not name:
83
+ print("Nothing typed. Only nmap is in Arthurs right now.")
84
+ else:
85
+ print(f"{name!r} is not in Arthurs yet. Only nmap is.")
86
+ return 1
87
+
88
+
89
+ if __name__ == "__main__":
90
+ raise SystemExit(main())
@@ -0,0 +1,37 @@
1
+ """Dispatcher for the Arthurs library: ``arthurs <program> [args...]``.
2
+
3
+ Programs live in :mod:`arthurs.programs`. Adding a program means one
4
+ module there plus one line in the registry below — nothing else.
5
+ """
6
+
7
+ import importlib
8
+
9
+ # Program name -> module. One line per program, added as programs land.
10
+ PROGRAMS = {
11
+ "nmap": "arthurs.programs.nmap",
12
+ }
13
+
14
+
15
+ def main(argv=None):
16
+ """Run a program by name. Returns its exit code."""
17
+ import sys
18
+
19
+ args = list(sys.argv[1:] if argv is None else argv)
20
+ if not args or args[0] in ("-h", "--help", "help"):
21
+ print("Usage: arthurs <program> [args...]")
22
+ print("Programs:")
23
+ for name in sorted(PROGRAMS):
24
+ print(f" {name}")
25
+ print("Or run a program straight by its own name, e.g. `nmap`.")
26
+ return 0
27
+ if args[0] == "--list":
28
+ for name in sorted(PROGRAMS):
29
+ print(name)
30
+ return 0
31
+ name = args[0]
32
+ if name not in PROGRAMS:
33
+ print(f"arthurs: no program named '{name}'", file=sys.stderr)
34
+ print("Programs:", ", ".join(sorted(PROGRAMS)), file=sys.stderr)
35
+ return 2
36
+ module = importlib.import_module(PROGRAMS[name])
37
+ return module.run(args[1:])
@@ -0,0 +1,128 @@
1
+ """The nmap program inside the Arthurs library.
2
+
3
+ This is a thin, honest wrapper around the real `nmap` program
4
+ installed on the machine. It does not re-implement scanning, and
5
+ it does not hide what it is about to run: it builds the command
6
+ as a list (never through a shell), prints it, and then runs it.
7
+
8
+ If nmap is not installed, it says so plainly instead of failing
9
+ with a confusing error, and tells you how to install it.
10
+
11
+ Only scan networks and machines you own, or that you have
12
+ permission to scan.
13
+ """
14
+
15
+ import os
16
+ import re
17
+ import subprocess
18
+
19
+ # Scan presets only. No stealth / evasion / script presets are
20
+ # offered here; add a new preset deliberately if one is ever wanted.
21
+ SCAN_PRESETS = {
22
+ "ping": ["-sn"], # hosts up, no port scan
23
+ "quick": ["-F"], # fast scan of the most common ports
24
+ "service": ["-sV"], # find services / versions on open ports
25
+ }
26
+
27
+ _TARGET_RE = re.compile(r"^[A-Za-z0-9._:/-]+$")
28
+ # A hostname / IP / CIDR / range, with no spaces or shell characters.
29
+ # IPv6, CIDR (192.168.1.0/24) and ranges (192.168.1.1-10) all match.
30
+
31
+ class NmapNotFoundError(FileNotFoundError):
32
+ """Raised when the real nmap program is not on this machine."""
33
+
34
+
35
+ # Marker carried by the library's own `nmap` launcher script, so the
36
+ # resolver below can tell the launcher apart from the real binary.
37
+ _LAUNCHER_MARKER = b"arthurs.programs.nmap"
38
+
39
+
40
+ def _is_launcher(path):
41
+ try:
42
+ with open(path, "rb") as handle:
43
+ return _LAUNCHER_MARKER in handle.read(2048)
44
+ except OSError:
45
+ return False
46
+
47
+
48
+ def find_nmap():
49
+ """Return the path to the real nmap program, or None.
50
+
51
+ Skips the library's own ``nmap`` launcher when it is installed on
52
+ PATH ahead of the system binary, so this always finds the real
53
+ nmap, never the launcher calling itself.
54
+ """
55
+ for directory in os.environ.get("PATH", "").split(os.pathsep):
56
+ if not directory:
57
+ continue
58
+ candidate = os.path.join(directory, "nmap")
59
+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
60
+ if _is_launcher(candidate):
61
+ continue
62
+ return candidate
63
+ return None
64
+
65
+
66
+ def validate_target(target):
67
+ """Return a clean target string, or raise ValueError.
68
+
69
+ Rejects empty targets, anything starting with a dash (so a
70
+ target can never be mistaken for an option), and any spaces
71
+ or shell characters.
72
+ """
73
+ if not isinstance(target, str):
74
+ raise ValueError("target must be text, e.g. '127.0.0.1'")
75
+ target = target.strip()
76
+ if not target:
77
+ raise ValueError("target is empty — give an address, e.g. '127.0.0.1'")
78
+ if target.startswith("-"):
79
+ raise ValueError(f"target must not start with '-': {target!r}")
80
+ if not _TARGET_RE.match(target):
81
+ raise ValueError(
82
+ f"target looks unsafe, only letters, digits, '.', '-', ':' "
83
+ f"and '/' are allowed: {target!r}"
84
+ )
85
+ return target
86
+
87
+
88
+ def build_command(target, scan="ping"):
89
+ """Build the exact command list that will run.
90
+
91
+ Raises NmapNotFoundError if nmap is not installed, and
92
+ ValueError for a bad target or unknown scan preset.
93
+ """
94
+ nmap_path = find_nmap()
95
+ if nmap_path is None:
96
+ raise NmapNotFoundError(
97
+ "nmap is not installed on this machine, so Arthurs cannot run it.\n"
98
+ "Install it first, then try again:\n"
99
+ " Ubuntu/Debian: sudo apt install nmap\n"
100
+ " macOS (Homebrew): brew install nmap\n"
101
+ " Windows: download it from https://nmap.org/download.html"
102
+ )
103
+ if scan not in SCAN_PRESETS:
104
+ raise ValueError(
105
+ f"unknown scan {scan!r} — pick one of: {', '.join(SCAN_PRESETS)}"
106
+ )
107
+ return [nmap_path] + SCAN_PRESETS[scan] + [validate_target(target)]
108
+
109
+
110
+ def run(target="127.0.0.1", scan="ping", timeout=120):
111
+ """Run nmap on one target and return the finished process.
112
+
113
+ The command is printed before it runs. Output is returned on
114
+ the process object (`.stdout` / `.stderr` / `.returncode`)
115
+ and also printed, so both the launcher and library callers
116
+ can see it.
117
+ """
118
+ command = build_command(target, scan)
119
+ print("Running:", " ".join(command))
120
+ print("Only scan networks you own or have permission to scan.")
121
+ result = subprocess.run(
122
+ command, capture_output=True, text=True, timeout=timeout
123
+ )
124
+ if result.stdout:
125
+ print(result.stdout, end="")
126
+ if result.stderr:
127
+ print(result.stderr, end="")
128
+ return result
@@ -0,0 +1,5 @@
1
+ """Programs in the Arthurs library. One module per program.
2
+
3
+ Each program module exposes ``run(argv)`` returning an exit code and
4
+ ``main()`` exiting with it. The registry lives in :mod:`arthurs.cli`.
5
+ """
@@ -0,0 +1,83 @@
1
+ """nmap, the first program in the Arthurs library.
2
+
3
+ A faithful passthrough to the real nmap binary: your arguments go to
4
+ real nmap untouched, with your terminal and nmap's own exit code. This
5
+ module never scans anything itself and never fakes a result — if the
6
+ real nmap is not installed, it says so plainly.
7
+
8
+ Resolving the real binary needs care: installing this library puts a
9
+ small ``nmap`` launcher on PATH ahead of the system binary, so a naive
10
+ lookup would find the launcher itself and recurse forever. The resolver
11
+ below skips the running launcher (same file, or a file carrying this
12
+ module's marker) and honours the ``ARTHURS_NMAP_BIN`` override.
13
+ """
14
+
15
+ import os
16
+ import subprocess
17
+ import sys
18
+
19
+ PROGRAM_NAME = "nmap"
20
+ _MARKER = b"arthurs.programs.nmap"
21
+ _MISSING_MESSAGE = (
22
+ "arthurs: the real 'nmap' program is not installed on this machine.\n"
23
+ "Install it first (for example: sudo apt install nmap), "
24
+ "then run 'nmap' again.\n"
25
+ "Nothing was scanned and nothing was faked."
26
+ )
27
+
28
+
29
+ def _is_wrapper(path):
30
+ """True if the file at path is this launcher, not the real nmap."""
31
+ try:
32
+ with open(path, "rb") as handle:
33
+ return _MARKER in handle.read(2048)
34
+ except OSError:
35
+ return False
36
+
37
+
38
+ def resolve_nmap(executable=None):
39
+ """Path to the real nmap binary, or None when there is none.
40
+
41
+ ``ARTHURS_NMAP_BIN`` overrides everything when it names a file.
42
+ Otherwise PATH is scanned in order, skipping the launcher itself.
43
+ """
44
+ override = os.environ.get("ARTHURS_NMAP_BIN")
45
+ if override:
46
+ return override if os.path.isfile(override) else None
47
+ own = None
48
+ if sys.argv and sys.argv[0]:
49
+ try:
50
+ own = os.path.realpath(sys.argv[0])
51
+ except OSError:
52
+ own = None
53
+ for directory in os.environ.get("PATH", "").split(os.pathsep):
54
+ if not directory:
55
+ continue
56
+ candidate = os.path.join(directory, "nmap")
57
+ if not (os.path.isfile(candidate) and os.access(candidate, os.X_OK)):
58
+ continue
59
+ try:
60
+ if own and os.path.samefile(candidate, own):
61
+ continue
62
+ except OSError:
63
+ pass
64
+ if _is_wrapper(candidate):
65
+ continue
66
+ return candidate
67
+ return None
68
+
69
+
70
+ def run(argv=None):
71
+ """Run real nmap with argv (default: the command line's). Returns
72
+ nmap's exit code, or 127 when the real nmap is not installed."""
73
+ args = list(sys.argv[1:] if argv is None else argv)
74
+ binary = resolve_nmap()
75
+ if binary is None:
76
+ print(_MISSING_MESSAGE, file=sys.stderr)
77
+ return 127
78
+ completed = subprocess.run([binary] + args)
79
+ return completed.returncode
80
+
81
+
82
+ def main(argv=None):
83
+ sys.exit(run(argv))
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: arthurs
3
+ Version: 0.1.0
4
+ Summary: Arthurs — Christopher's own library of programs. Currently: nmap only.
5
+ Author: Christopher Arthur
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # Arthurs
13
+
14
+ Christopher's own Python library of programs. Right now it holds
15
+ **one** program only: **nmap**. Other programs will be added later,
16
+ one at a time, each in its own module.
17
+
18
+ ## Run it — type `nmap`
19
+
20
+ Once the library is installed, typing `nmap` runs nmap, exactly
21
+ like always. The library's launcher finds the real nmap on the
22
+ machine and hands it your arguments untouched:
23
+
24
+ ```sh
25
+ nmap --version
26
+ nmap -sn 127.0.0.1
27
+ ```
28
+
29
+ Same thing through the library dispatcher:
30
+
31
+ ```sh
32
+ arthurs nmap --version
33
+ ```
34
+
35
+ ## Guided way — presets
36
+
37
+ Prefer answering questions instead of typing nmap options? The
38
+ launcher walks you through it:
39
+
40
+ ```sh
41
+ python3 -m arthurs
42
+ # Type a program name: nmap
43
+ # Target address [127.0.0.1]: 127.0.0.1
44
+ # Pick 1-3 [ping]: 1
45
+ ```
46
+
47
+ Or in one line:
48
+
49
+ ```sh
50
+ python3 -m arthurs nmap 127.0.0.1 ping
51
+ ```
52
+
53
+ Scan types: `ping` (hosts up, no ports), `quick` (common ports),
54
+ `service` (services / versions).
55
+
56
+ ## Use it from Python
57
+
58
+ ```python
59
+ from arthurs import nmap
60
+ nmap.run("127.0.0.1") # ping scan
61
+ nmap.run("192.168.1.1", scan="quick")
62
+ ```
63
+
64
+ ## If nmap is not installed
65
+
66
+ Arthurs does not install nmap for you — it runs the real nmap on
67
+ the machine and says so plainly if it is missing:
68
+
69
+ - Ubuntu/Debian: `sudo apt install nmap`
70
+ - macOS (Homebrew): `brew install nmap`
71
+ - Windows: https://nmap.org/download.html
72
+
73
+ ## Rule
74
+
75
+ Only scan networks and machines you own, or that you have
76
+ permission to scan.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ arthurs/__init__.py
5
+ arthurs/__main__.py
6
+ arthurs/cli.py
7
+ arthurs/nmap.py
8
+ arthurs.egg-info/PKG-INFO
9
+ arthurs.egg-info/SOURCES.txt
10
+ arthurs.egg-info/dependency_links.txt
11
+ arthurs.egg-info/entry_points.txt
12
+ arthurs.egg-info/top_level.txt
13
+ arthurs/programs/__init__.py
14
+ arthurs/programs/nmap.py
15
+ tests/test_nmap.py
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ arthurs = arthurs.cli:main
3
+ nmap = arthurs.programs.nmap:main
@@ -0,0 +1 @@
1
+ arthurs
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "arthurs"
7
+ version = "0.1.0"
8
+ description = "Arthurs — Christopher's own library of programs. Currently: nmap only."
9
+ readme = "README.md"
10
+ authors = [{name = "Christopher Arthur"}]
11
+ license = {text = "MIT"}
12
+ requires-python = ">=3.9"
13
+
14
+ [project.scripts]
15
+ arthurs = "arthurs.cli:main"
16
+ nmap = "arthurs.programs.nmap:main"
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["."]
20
+ include = ["arthurs*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,87 @@
1
+ """Tests for the Arthurs nmap program. Standard library only."""
2
+
3
+ import io
4
+ import os
5
+ import stat
6
+ import sys
7
+ import tempfile
8
+ import unittest
9
+ from contextlib import redirect_stdout
10
+ from unittest import mock
11
+
12
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
13
+
14
+ from arthurs import cli
15
+ from arthurs.programs import nmap as nmap_program
16
+
17
+
18
+ def _make_executable(path, content):
19
+ with open(path, "w") as handle:
20
+ handle.write(content)
21
+ os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
22
+
23
+
24
+ class ResolveTests(unittest.TestCase):
25
+ def test_resolve_skips_the_wrapper_itself(self):
26
+ with tempfile.TemporaryDirectory() as tmp:
27
+ wrapper = os.path.join(tmp, "nmap")
28
+ _make_executable(wrapper, "#!/bin/sh\n# arthurs.programs.nmap\n")
29
+ with mock.patch.dict(os.environ, {"PATH": tmp}, clear=False):
30
+ with mock.patch.object(sys, "argv", [wrapper]):
31
+ # The only nmap on PATH is the wrapper: nothing real.
32
+ with mock.patch.dict(os.environ, {}, clear=False):
33
+ os.environ.pop("ARTHURS_NMAP_BIN", None)
34
+ self.assertIsNone(nmap_program.resolve_nmap())
35
+
36
+ def test_resolve_honours_override(self):
37
+ with tempfile.TemporaryDirectory() as tmp:
38
+ target = os.path.join(tmp, "real-nmap")
39
+ _make_executable(target, "#!/bin/sh\nexit 0\n")
40
+ with mock.patch.dict(os.environ, {"ARTHURS_NMAP_BIN": target}):
41
+ self.assertEqual(nmap_program.resolve_nmap(), target)
42
+ with mock.patch.dict(os.environ, {"ARTHURS_NMAP_BIN": "/nonexistent"}):
43
+ self.assertIsNone(nmap_program.resolve_nmap())
44
+
45
+
46
+ class RunTests(unittest.TestCase):
47
+ def test_run_passes_args_and_exit_code_through(self):
48
+ # The dummy writes to a file: a child process inherits the OS
49
+ # file descriptor, not Python's redirected sys.stdout.
50
+ with tempfile.TemporaryDirectory() as tmp:
51
+ dummy = os.path.join(tmp, "dummy-nmap")
52
+ outfile = os.path.join(tmp, "out.txt")
53
+ _make_executable(
54
+ dummy, '#!/bin/sh\necho "ARGS:$@" > "$DUMMY_OUT"\nexit 7\n')
55
+ env = {"ARTHURS_NMAP_BIN": dummy, "DUMMY_OUT": outfile}
56
+ with mock.patch.dict(os.environ, env):
57
+ code = nmap_program.run(["--version", "example.com"])
58
+ self.assertEqual(code, 7)
59
+ with open(outfile) as handle:
60
+ self.assertIn("ARGS:--version example.com", handle.read())
61
+
62
+ def test_run_missing_binary_reports_plainly(self):
63
+ err = io.StringIO()
64
+ with mock.patch.dict(os.environ, {"ARTHURS_NMAP_BIN": "/nonexistent"}):
65
+ with redirect_stdout(err):
66
+ pass
67
+ with mock.patch("sys.stderr", err):
68
+ code = nmap_program.run([])
69
+ self.assertEqual(code, 127)
70
+ self.assertIn("not installed", err.getvalue())
71
+
72
+
73
+ class CliTests(unittest.TestCase):
74
+ def test_list_names_nmap(self):
75
+ out = io.StringIO()
76
+ with redirect_stdout(out):
77
+ code = cli.main(["--list"])
78
+ self.assertEqual(code, 0)
79
+ self.assertIn("nmap", out.getvalue())
80
+
81
+ def test_unknown_program_fails(self):
82
+ code = cli.main(["no-such-program"])
83
+ self.assertEqual(code, 2)
84
+
85
+
86
+ if __name__ == "__main__":
87
+ unittest.main()