gns3ctl 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.
- gns3ctl-0.1.0/PKG-INFO +114 -0
- gns3ctl-0.1.0/README.md +91 -0
- gns3ctl-0.1.0/pyproject.toml +41 -0
- gns3ctl-0.1.0/setup.cfg +4 -0
- gns3ctl-0.1.0/src/gns3ctl/__init__.py +1 -0
- gns3ctl-0.1.0/src/gns3ctl/__main__.py +4 -0
- gns3ctl-0.1.0/src/gns3ctl/cli.py +312 -0
- gns3ctl-0.1.0/src/gns3ctl/client.py +271 -0
- gns3ctl-0.1.0/src/gns3ctl/config.py +175 -0
- gns3ctl-0.1.0/src/gns3ctl/setup.py +151 -0
- gns3ctl-0.1.0/src/gns3ctl.egg-info/PKG-INFO +114 -0
- gns3ctl-0.1.0/src/gns3ctl.egg-info/SOURCES.txt +14 -0
- gns3ctl-0.1.0/src/gns3ctl.egg-info/dependency_links.txt +1 -0
- gns3ctl-0.1.0/src/gns3ctl.egg-info/entry_points.txt +3 -0
- gns3ctl-0.1.0/src/gns3ctl.egg-info/requires.txt +2 -0
- gns3ctl-0.1.0/src/gns3ctl.egg-info/top_level.txt +1 -0
gns3ctl-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gns3ctl
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CLI for controlling a GNS3 server — projects, nodes, links, templates — via the GNS3 REST API
|
|
5
|
+
Author-email: Jakob Holst <code@jakobholst.dk>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://gitlab.com/jakobholst/gns3ctl
|
|
8
|
+
Project-URL: Repository, https://gitlab.com/jakobholst/gns3ctl
|
|
9
|
+
Keywords: gns3,network,simulator,cli,automation,rest,api
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: System Administrators
|
|
13
|
+
Classifier: Intended Audience :: Information Technology
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: System :: Networking
|
|
18
|
+
Classifier: Topic :: Utilities
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: requests>=2.28
|
|
22
|
+
Requires-Dist: pyyaml>=6.0
|
|
23
|
+
|
|
24
|
+
# gns3ctl
|
|
25
|
+
|
|
26
|
+
`gns3ctl` drives a [GNS3](https://www.gns3.com/) server from the command
|
|
27
|
+
line via its REST API. It covers the day-to-day things you'd otherwise
|
|
28
|
+
have to click through in the GUI: list / open / close projects, see
|
|
29
|
+
and operate on nodes (start / stop / reload / suspend), inspect links,
|
|
30
|
+
templates and computes.
|
|
31
|
+
|
|
32
|
+
| Command | Purpose |
|
|
33
|
+
|--------------------|------------------------------------------------------------------|
|
|
34
|
+
| `gns3ctl` | Main CLI with subcommands (projects, nodes, links, …) |
|
|
35
|
+
| `gns3ctl-setup` | Interactive first-run: writes `GNS3_*` exports to your shell rc |
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install gns3ctl
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Configure
|
|
44
|
+
|
|
45
|
+
### Quickest: `gns3ctl-setup`
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
gns3ctl-setup
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Prompts for URL, user, password, default project; writes an idempotent
|
|
52
|
+
export block into `~/.zshrc` / `~/.bashrc` / `~/.bash_profile`.
|
|
53
|
+
|
|
54
|
+
### Env vars
|
|
55
|
+
|
|
56
|
+
| Variable | Meaning |
|
|
57
|
+
|-------------------------|--------------------------------------------------------|
|
|
58
|
+
| `GNS3_URL` | Base URL, e.g. `http://localhost:3080` |
|
|
59
|
+
| `GNS3_USER` | Basic-auth username (omit for open servers) |
|
|
60
|
+
| `GNS3_PASSWORD` | Basic-auth password |
|
|
61
|
+
| `GNS3_API_VERSION` | `v2` (default) or `v3` |
|
|
62
|
+
| `GNS3_VERIFY_SSL` | `false` to skip TLS verification |
|
|
63
|
+
| `GNS3_DEFAULT_PROJECT` | Id or name used when `--project` is omitted |
|
|
64
|
+
|
|
65
|
+
### YAML (fallback)
|
|
66
|
+
|
|
67
|
+
A stub is written to `~/.local/etc/gns3ctl/config.yaml` on first run if
|
|
68
|
+
`GNS3_URL` isn't exported. Env vars always win.
|
|
69
|
+
|
|
70
|
+
## Usage
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
# Server info
|
|
74
|
+
gns3ctl version
|
|
75
|
+
|
|
76
|
+
# Projects
|
|
77
|
+
gns3ctl projects list
|
|
78
|
+
gns3ctl projects open my-lab
|
|
79
|
+
gns3ctl projects close my-lab
|
|
80
|
+
|
|
81
|
+
# Nodes (requires a project — --project or GNS3_DEFAULT_PROJECT)
|
|
82
|
+
gns3ctl --project my-lab nodes list
|
|
83
|
+
gns3ctl --project my-lab nodes start R1
|
|
84
|
+
gns3ctl --project my-lab nodes stop --all
|
|
85
|
+
gns3ctl --project my-lab nodes reload R1
|
|
86
|
+
gns3ctl --project my-lab nodes suspend R1
|
|
87
|
+
|
|
88
|
+
# Links / templates / computes
|
|
89
|
+
gns3ctl --project my-lab links list
|
|
90
|
+
gns3ctl templates list
|
|
91
|
+
gns3ctl computes list
|
|
92
|
+
|
|
93
|
+
# JSON output, overriding the server URL
|
|
94
|
+
gns3ctl --url http://gns3.lab:3080 --json projects list
|
|
95
|
+
|
|
96
|
+
# Self-signed GNS3 server
|
|
97
|
+
gns3ctl --insecure projects list
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Project and node refs accept either the id or the name — `gns3ctl`
|
|
101
|
+
resolves the name against `GET /projects` or `GET /nodes` and uses the
|
|
102
|
+
id for the subsequent call.
|
|
103
|
+
|
|
104
|
+
## Exit codes
|
|
105
|
+
|
|
106
|
+
| Code | Meaning |
|
|
107
|
+
|------|------------------------------------------------------|
|
|
108
|
+
| 0 | Success |
|
|
109
|
+
| 1 | GNS3 server returned an error (auth, 4xx, 5xx, etc.) |
|
|
110
|
+
| 2 | Usage / configuration problem |
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT
|
gns3ctl-0.1.0/README.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# gns3ctl
|
|
2
|
+
|
|
3
|
+
`gns3ctl` drives a [GNS3](https://www.gns3.com/) server from the command
|
|
4
|
+
line via its REST API. It covers the day-to-day things you'd otherwise
|
|
5
|
+
have to click through in the GUI: list / open / close projects, see
|
|
6
|
+
and operate on nodes (start / stop / reload / suspend), inspect links,
|
|
7
|
+
templates and computes.
|
|
8
|
+
|
|
9
|
+
| Command | Purpose |
|
|
10
|
+
|--------------------|------------------------------------------------------------------|
|
|
11
|
+
| `gns3ctl` | Main CLI with subcommands (projects, nodes, links, …) |
|
|
12
|
+
| `gns3ctl-setup` | Interactive first-run: writes `GNS3_*` exports to your shell rc |
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install gns3ctl
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Configure
|
|
21
|
+
|
|
22
|
+
### Quickest: `gns3ctl-setup`
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
gns3ctl-setup
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Prompts for URL, user, password, default project; writes an idempotent
|
|
29
|
+
export block into `~/.zshrc` / `~/.bashrc` / `~/.bash_profile`.
|
|
30
|
+
|
|
31
|
+
### Env vars
|
|
32
|
+
|
|
33
|
+
| Variable | Meaning |
|
|
34
|
+
|-------------------------|--------------------------------------------------------|
|
|
35
|
+
| `GNS3_URL` | Base URL, e.g. `http://localhost:3080` |
|
|
36
|
+
| `GNS3_USER` | Basic-auth username (omit for open servers) |
|
|
37
|
+
| `GNS3_PASSWORD` | Basic-auth password |
|
|
38
|
+
| `GNS3_API_VERSION` | `v2` (default) or `v3` |
|
|
39
|
+
| `GNS3_VERIFY_SSL` | `false` to skip TLS verification |
|
|
40
|
+
| `GNS3_DEFAULT_PROJECT` | Id or name used when `--project` is omitted |
|
|
41
|
+
|
|
42
|
+
### YAML (fallback)
|
|
43
|
+
|
|
44
|
+
A stub is written to `~/.local/etc/gns3ctl/config.yaml` on first run if
|
|
45
|
+
`GNS3_URL` isn't exported. Env vars always win.
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
# Server info
|
|
51
|
+
gns3ctl version
|
|
52
|
+
|
|
53
|
+
# Projects
|
|
54
|
+
gns3ctl projects list
|
|
55
|
+
gns3ctl projects open my-lab
|
|
56
|
+
gns3ctl projects close my-lab
|
|
57
|
+
|
|
58
|
+
# Nodes (requires a project — --project or GNS3_DEFAULT_PROJECT)
|
|
59
|
+
gns3ctl --project my-lab nodes list
|
|
60
|
+
gns3ctl --project my-lab nodes start R1
|
|
61
|
+
gns3ctl --project my-lab nodes stop --all
|
|
62
|
+
gns3ctl --project my-lab nodes reload R1
|
|
63
|
+
gns3ctl --project my-lab nodes suspend R1
|
|
64
|
+
|
|
65
|
+
# Links / templates / computes
|
|
66
|
+
gns3ctl --project my-lab links list
|
|
67
|
+
gns3ctl templates list
|
|
68
|
+
gns3ctl computes list
|
|
69
|
+
|
|
70
|
+
# JSON output, overriding the server URL
|
|
71
|
+
gns3ctl --url http://gns3.lab:3080 --json projects list
|
|
72
|
+
|
|
73
|
+
# Self-signed GNS3 server
|
|
74
|
+
gns3ctl --insecure projects list
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Project and node refs accept either the id or the name — `gns3ctl`
|
|
78
|
+
resolves the name against `GET /projects` or `GET /nodes` and uses the
|
|
79
|
+
id for the subsequent call.
|
|
80
|
+
|
|
81
|
+
## Exit codes
|
|
82
|
+
|
|
83
|
+
| Code | Meaning |
|
|
84
|
+
|------|------------------------------------------------------|
|
|
85
|
+
| 0 | Success |
|
|
86
|
+
| 1 | GNS3 server returned an error (auth, 4xx, 5xx, etc.) |
|
|
87
|
+
| 2 | Usage / configuration problem |
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
MIT
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "gns3ctl"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "CLI for controlling a GNS3 server — projects, nodes, links, templates — via the GNS3 REST API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Jakob Holst", email = "code@jakobholst.dk" },
|
|
14
|
+
]
|
|
15
|
+
keywords = ["gns3", "network", "simulator", "cli", "automation", "rest", "api"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Environment :: Console",
|
|
19
|
+
"Intended Audience :: System Administrators",
|
|
20
|
+
"Intended Audience :: Information Technology",
|
|
21
|
+
"License :: OSI Approved :: MIT License",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Topic :: System :: Networking",
|
|
25
|
+
"Topic :: Utilities",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"requests>=2.28",
|
|
29
|
+
"pyyaml>=6.0",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.scripts]
|
|
33
|
+
gns3ctl = "gns3ctl.cli:main"
|
|
34
|
+
gns3ctl-setup = "gns3ctl.setup:main"
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://gitlab.com/jakobholst/gns3ctl"
|
|
38
|
+
Repository = "https://gitlab.com/jakobholst/gns3ctl"
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.packages.find]
|
|
41
|
+
where = ["src"]
|
gns3ctl-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""`gns3ctl` CLI — control a GNS3 server from the shell.
|
|
2
|
+
|
|
3
|
+
Subcommands:
|
|
4
|
+
|
|
5
|
+
gns3ctl version
|
|
6
|
+
gns3ctl projects list|open|close
|
|
7
|
+
gns3ctl nodes list|start|stop|reload|suspend [--all | NODE]
|
|
8
|
+
gns3ctl links list
|
|
9
|
+
gns3ctl templates list
|
|
10
|
+
gns3ctl computes list
|
|
11
|
+
|
|
12
|
+
Most commands print an aligned table; pass ``--json`` for
|
|
13
|
+
machine-readable output.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import sys
|
|
21
|
+
from dataclasses import asdict, is_dataclass
|
|
22
|
+
from typing import Any, Callable
|
|
23
|
+
|
|
24
|
+
from gns3ctl import __version__, config
|
|
25
|
+
from gns3ctl.client import GNS3Client, GNS3Error
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ---------------------------------------------------------------- output
|
|
29
|
+
|
|
30
|
+
def _emit(rows: list[dict], columns: list[tuple[str, str]], as_json: bool) -> None:
|
|
31
|
+
"""Print rows either as JSON or an aligned table.
|
|
32
|
+
|
|
33
|
+
``columns`` is a list of (header, key) pairs — header is shown,
|
|
34
|
+
key is looked up in each row dict.
|
|
35
|
+
"""
|
|
36
|
+
if as_json:
|
|
37
|
+
print(json.dumps(rows, indent=2, default=str))
|
|
38
|
+
return
|
|
39
|
+
if not rows:
|
|
40
|
+
print("No results.")
|
|
41
|
+
return
|
|
42
|
+
headers = [h for h, _ in columns]
|
|
43
|
+
keys = [k for _, k in columns]
|
|
44
|
+
widths = [
|
|
45
|
+
max(len(headers[i]), *(len(str(r.get(keys[i], "") or "-")) for r in rows))
|
|
46
|
+
for i in range(len(columns))
|
|
47
|
+
]
|
|
48
|
+
parts = [f"{{:<{w}}}" for w in widths[:-1]] + ["{}"]
|
|
49
|
+
fmt = " ".join(parts)
|
|
50
|
+
print(fmt.format(*headers).rstrip())
|
|
51
|
+
print(fmt.format(*("-" * w for w in widths)).rstrip())
|
|
52
|
+
for r in rows:
|
|
53
|
+
print(fmt.format(*(str(r.get(k, "") or "-") for k in keys)).rstrip())
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _to_rows(objs: list[Any]) -> list[dict]:
|
|
57
|
+
return [asdict(o) if is_dataclass(o) else dict(o) for o in objs]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---------------------------------------------------------------- parser
|
|
61
|
+
|
|
62
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
63
|
+
p = argparse.ArgumentParser(
|
|
64
|
+
prog="gns3ctl",
|
|
65
|
+
description="Control a GNS3 server — projects, nodes, links — from the CLI.",
|
|
66
|
+
)
|
|
67
|
+
p.add_argument("--json", action="store_true", help="Emit JSON instead of a table.")
|
|
68
|
+
p.add_argument(
|
|
69
|
+
"--insecure",
|
|
70
|
+
action="store_true",
|
|
71
|
+
help="Skip TLS cert verification (self-signed GNS3 server, etc).",
|
|
72
|
+
)
|
|
73
|
+
p.add_argument(
|
|
74
|
+
"--url",
|
|
75
|
+
help="Override GNS3 server URL (defaults to GNS3_URL / config).",
|
|
76
|
+
)
|
|
77
|
+
p.add_argument(
|
|
78
|
+
"--project",
|
|
79
|
+
help="Project id or name (defaults to GNS3_DEFAULT_PROJECT / config).",
|
|
80
|
+
)
|
|
81
|
+
p.add_argument("--version", action="version", version=f"gns3ctl {__version__}")
|
|
82
|
+
|
|
83
|
+
sub = p.add_subparsers(dest="command", required=False, metavar="COMMAND")
|
|
84
|
+
|
|
85
|
+
sub.add_parser("version", help="Show remote GNS3 server version.")
|
|
86
|
+
|
|
87
|
+
proj = sub.add_parser("projects", help="Manage projects.")
|
|
88
|
+
proj_sub = proj.add_subparsers(dest="action", required=True)
|
|
89
|
+
proj_sub.add_parser("list", help="List all projects.")
|
|
90
|
+
po = proj_sub.add_parser("open", help="Open a project.")
|
|
91
|
+
po.add_argument("project_ref", help="Project id or name.")
|
|
92
|
+
pc = proj_sub.add_parser("close", help="Close a project.")
|
|
93
|
+
pc.add_argument("project_ref", help="Project id or name.")
|
|
94
|
+
|
|
95
|
+
nodes = sub.add_parser("nodes", help="Manage nodes in a project.")
|
|
96
|
+
nodes_sub = nodes.add_subparsers(dest="action", required=True)
|
|
97
|
+
nodes_sub.add_parser("list", help="List nodes in the selected project.")
|
|
98
|
+
for act in ("start", "stop", "reload", "suspend"):
|
|
99
|
+
n = nodes_sub.add_parser(act, help=f"{act.capitalize()} one node or --all.")
|
|
100
|
+
g = n.add_mutually_exclusive_group(required=True)
|
|
101
|
+
g.add_argument("node_ref", nargs="?", help="Node id or name.")
|
|
102
|
+
g.add_argument(
|
|
103
|
+
"--all",
|
|
104
|
+
dest="all_nodes",
|
|
105
|
+
action="store_true",
|
|
106
|
+
help=f"{act.capitalize()} every node in the project.",
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
links = sub.add_parser("links", help="Inspect links.")
|
|
110
|
+
links_sub = links.add_subparsers(dest="action", required=True)
|
|
111
|
+
links_sub.add_parser("list", help="List links in the selected project.")
|
|
112
|
+
ld = links_sub.add_parser("delete", help="Delete a link by id.")
|
|
113
|
+
ld.add_argument("link_id")
|
|
114
|
+
|
|
115
|
+
tmpl = sub.add_parser("templates", help="Inspect templates.")
|
|
116
|
+
tmpl_sub = tmpl.add_subparsers(dest="action", required=True)
|
|
117
|
+
tmpl_sub.add_parser("list", help="List templates on the server.")
|
|
118
|
+
|
|
119
|
+
comp = sub.add_parser("computes", help="Inspect computes.")
|
|
120
|
+
comp_sub = comp.add_subparsers(dest="action", required=True)
|
|
121
|
+
comp_sub.add_parser("list", help="List computes registered on the server.")
|
|
122
|
+
|
|
123
|
+
return p
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ---------------------------------------------------------------- helpers
|
|
127
|
+
|
|
128
|
+
def _need_project(client: GNS3Client, args, cfg) -> str:
|
|
129
|
+
ref = args.project or config.resolve_default_project(cfg)
|
|
130
|
+
if not ref:
|
|
131
|
+
raise GNS3Error(
|
|
132
|
+
"no project selected — pass --project or export GNS3_DEFAULT_PROJECT."
|
|
133
|
+
)
|
|
134
|
+
return client.resolve_project_id(ref)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ---------------------------------------------------------------- dispatch
|
|
138
|
+
|
|
139
|
+
def _cmd_version(client: GNS3Client, args, cfg) -> int:
|
|
140
|
+
info = client.version()
|
|
141
|
+
if args.json:
|
|
142
|
+
print(json.dumps(info, indent=2))
|
|
143
|
+
else:
|
|
144
|
+
for k, v in (info or {}).items():
|
|
145
|
+
print(f"{k}: {v}")
|
|
146
|
+
return 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _cmd_projects(client: GNS3Client, args, cfg) -> int:
|
|
150
|
+
if args.action == "list":
|
|
151
|
+
rows = _to_rows(client.list_projects())
|
|
152
|
+
_emit(
|
|
153
|
+
rows,
|
|
154
|
+
[("PROJECT_ID", "project_id"), ("NAME", "name"),
|
|
155
|
+
("STATUS", "status"), ("PATH", "path")],
|
|
156
|
+
args.json,
|
|
157
|
+
)
|
|
158
|
+
return 0
|
|
159
|
+
pid = client.resolve_project_id(args.project_ref)
|
|
160
|
+
if args.action == "open":
|
|
161
|
+
result = client.open_project(pid)
|
|
162
|
+
print(f"opened {args.project_ref} ({pid})")
|
|
163
|
+
if args.json and result:
|
|
164
|
+
print(json.dumps(result, indent=2))
|
|
165
|
+
elif args.action == "close":
|
|
166
|
+
client.close_project(pid)
|
|
167
|
+
print(f"closed {args.project_ref} ({pid})")
|
|
168
|
+
return 0
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _cmd_nodes(client: GNS3Client, args, cfg) -> int:
|
|
172
|
+
pid = _need_project(client, args, cfg)
|
|
173
|
+
if args.action == "list":
|
|
174
|
+
rows = _to_rows(client.list_nodes(pid))
|
|
175
|
+
_emit(
|
|
176
|
+
rows,
|
|
177
|
+
[("NODE_ID", "node_id"), ("NAME", "name"),
|
|
178
|
+
("TYPE", "node_type"), ("STATUS", "status"),
|
|
179
|
+
("CONSOLE", "console"), ("CONSOLE_TYPE", "console_type")],
|
|
180
|
+
args.json,
|
|
181
|
+
)
|
|
182
|
+
return 0
|
|
183
|
+
|
|
184
|
+
batch: dict[str, Callable[[str], None]] = {
|
|
185
|
+
"start": client.start_all_nodes,
|
|
186
|
+
"stop": client.stop_all_nodes,
|
|
187
|
+
"reload": client.reload_all_nodes,
|
|
188
|
+
"suspend": client.suspend_all_nodes,
|
|
189
|
+
}
|
|
190
|
+
single: dict[str, Callable[[str, str], Any]] = {
|
|
191
|
+
"start": client.start_node,
|
|
192
|
+
"stop": client.stop_node,
|
|
193
|
+
"reload": client.reload_node,
|
|
194
|
+
"suspend": client.suspend_node,
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if getattr(args, "all_nodes", False):
|
|
198
|
+
batch[args.action](pid)
|
|
199
|
+
print(f"{args.action}: all nodes in project {pid}")
|
|
200
|
+
return 0
|
|
201
|
+
|
|
202
|
+
nid = client.resolve_node_id(pid, args.node_ref)
|
|
203
|
+
result = single[args.action](pid, nid)
|
|
204
|
+
print(f"{args.action}: {args.node_ref} ({nid})")
|
|
205
|
+
if args.json and result:
|
|
206
|
+
print(json.dumps(result, indent=2, default=str))
|
|
207
|
+
return 0
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _cmd_links(client: GNS3Client, args, cfg) -> int:
|
|
211
|
+
pid = _need_project(client, args, cfg)
|
|
212
|
+
if args.action == "list":
|
|
213
|
+
rows = _to_rows(client.list_links(pid))
|
|
214
|
+
# Collapse the nodes list to "nodeA:port <-> nodeB:port" for the table.
|
|
215
|
+
for r in rows:
|
|
216
|
+
endpoints = r.get("nodes") or []
|
|
217
|
+
pieces = []
|
|
218
|
+
for ep in endpoints:
|
|
219
|
+
pieces.append(
|
|
220
|
+
f"{ep.get('node_id', '')[:8]}:{ep.get('adapter_number', '-')}/"
|
|
221
|
+
f"{ep.get('port_number', '-')}"
|
|
222
|
+
)
|
|
223
|
+
r["endpoints"] = " <-> ".join(pieces)
|
|
224
|
+
_emit(
|
|
225
|
+
rows,
|
|
226
|
+
[("LINK_ID", "link_id"), ("TYPE", "link_type"),
|
|
227
|
+
("ENDPOINTS", "endpoints")],
|
|
228
|
+
args.json,
|
|
229
|
+
)
|
|
230
|
+
return 0
|
|
231
|
+
client.delete_link(pid, args.link_id)
|
|
232
|
+
print(f"deleted link {args.link_id}")
|
|
233
|
+
return 0
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _cmd_templates(client: GNS3Client, args, cfg) -> int:
|
|
237
|
+
rows = _to_rows(client.list_templates())
|
|
238
|
+
_emit(
|
|
239
|
+
rows,
|
|
240
|
+
[("TEMPLATE_ID", "template_id"), ("NAME", "name"),
|
|
241
|
+
("TYPE", "template_type"), ("BUILTIN", "builtin")],
|
|
242
|
+
args.json,
|
|
243
|
+
)
|
|
244
|
+
return 0
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _cmd_computes(client: GNS3Client, args, cfg) -> int:
|
|
248
|
+
rows = _to_rows(client.list_computes())
|
|
249
|
+
_emit(
|
|
250
|
+
rows,
|
|
251
|
+
[("COMPUTE_ID", "compute_id"), ("NAME", "name"),
|
|
252
|
+
("HOST", "host"), ("PROTOCOL", "protocol"),
|
|
253
|
+
("PORT", "port"), ("CONNECTED", "connected")],
|
|
254
|
+
args.json,
|
|
255
|
+
)
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
DISPATCH: dict[str, Callable[..., int]] = {
|
|
260
|
+
"version": _cmd_version,
|
|
261
|
+
"projects": _cmd_projects,
|
|
262
|
+
"nodes": _cmd_nodes,
|
|
263
|
+
"links": _cmd_links,
|
|
264
|
+
"templates": _cmd_templates,
|
|
265
|
+
"computes": _cmd_computes,
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# ---------------------------------------------------------------- main
|
|
270
|
+
|
|
271
|
+
def main(argv: list[str] | None = None) -> int:
|
|
272
|
+
parser = _build_parser()
|
|
273
|
+
args = parser.parse_args(argv)
|
|
274
|
+
|
|
275
|
+
if not args.command:
|
|
276
|
+
parser.print_help()
|
|
277
|
+
return 2
|
|
278
|
+
|
|
279
|
+
state = config.bootstrap()
|
|
280
|
+
if state != "ok" and not args.url:
|
|
281
|
+
print(config.USAGE)
|
|
282
|
+
if state == "created":
|
|
283
|
+
print(f"Wrote template at {config.CONFIG_PATH}. Edit it, then re-run.")
|
|
284
|
+
return 2
|
|
285
|
+
|
|
286
|
+
cfg = config.load() or {}
|
|
287
|
+
try:
|
|
288
|
+
auth = config.resolve_auth(cfg)
|
|
289
|
+
except RuntimeError as exc:
|
|
290
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
291
|
+
return 2
|
|
292
|
+
|
|
293
|
+
url = args.url or config.resolve_url(cfg)
|
|
294
|
+
verify = False if args.insecure else config.resolve_verify_ssl(cfg)
|
|
295
|
+
client = GNS3Client(
|
|
296
|
+
url,
|
|
297
|
+
auth=auth,
|
|
298
|
+
api_version=config.resolve_api_version(cfg),
|
|
299
|
+
timeout=config.resolve_timeout(cfg),
|
|
300
|
+
verify=verify,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
handler = DISPATCH[args.command]
|
|
304
|
+
try:
|
|
305
|
+
return handler(client, args, cfg)
|
|
306
|
+
except GNS3Error as exc:
|
|
307
|
+
print(f"gns3 error: {exc}", file=sys.stderr)
|
|
308
|
+
return 1
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
if __name__ == "__main__":
|
|
312
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""GNS3 server REST client.
|
|
2
|
+
|
|
3
|
+
Thin, opinionated wrapper around the GNS3 v2 / v3 REST APIs. Covers
|
|
4
|
+
the handful of endpoints a CLI needs: version, projects, nodes,
|
|
5
|
+
links, templates and computes — plus per-node lifecycle actions
|
|
6
|
+
(start / stop / reload / suspend) and the batch variants that apply
|
|
7
|
+
to every node in a project.
|
|
8
|
+
|
|
9
|
+
Reference: https://gns3-server.readthedocs.io/
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import urljoin
|
|
17
|
+
|
|
18
|
+
import requests
|
|
19
|
+
from requests.adapters import HTTPAdapter
|
|
20
|
+
from urllib3.util.retry import Retry
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class GNS3Error(RuntimeError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Project:
|
|
29
|
+
project_id: str
|
|
30
|
+
name: str
|
|
31
|
+
status: str | None
|
|
32
|
+
path: str | None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Node:
|
|
37
|
+
node_id: str
|
|
38
|
+
name: str
|
|
39
|
+
node_type: str
|
|
40
|
+
status: str | None
|
|
41
|
+
console: int | None
|
|
42
|
+
console_type: str | None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Link:
|
|
47
|
+
link_id: str
|
|
48
|
+
nodes: list[dict]
|
|
49
|
+
link_type: str | None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Template:
|
|
54
|
+
template_id: str
|
|
55
|
+
name: str
|
|
56
|
+
template_type: str
|
|
57
|
+
builtin: bool
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Compute:
|
|
62
|
+
compute_id: str
|
|
63
|
+
name: str
|
|
64
|
+
host: str | None
|
|
65
|
+
protocol: str | None
|
|
66
|
+
port: int | None
|
|
67
|
+
connected: bool | None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class GNS3Client:
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
base_url: str,
|
|
74
|
+
*,
|
|
75
|
+
auth: tuple[str, str] | None = None,
|
|
76
|
+
api_version: str = "2",
|
|
77
|
+
timeout: int = 30,
|
|
78
|
+
verify: bool = True,
|
|
79
|
+
session: requests.Session | None = None,
|
|
80
|
+
):
|
|
81
|
+
if not base_url:
|
|
82
|
+
raise ValueError("base_url is required")
|
|
83
|
+
self.base_url = base_url.rstrip("/")
|
|
84
|
+
self.api_prefix = f"v{api_version.lstrip('v')}"
|
|
85
|
+
self.timeout = timeout
|
|
86
|
+
self.session = session or requests.Session()
|
|
87
|
+
retry = Retry(
|
|
88
|
+
total=3,
|
|
89
|
+
connect=3,
|
|
90
|
+
read=3,
|
|
91
|
+
status=3,
|
|
92
|
+
backoff_factor=0.5,
|
|
93
|
+
status_forcelist=(502, 503, 504),
|
|
94
|
+
allowed_methods=frozenset(["GET", "POST", "PUT", "DELETE", "HEAD"]),
|
|
95
|
+
raise_on_status=False,
|
|
96
|
+
respect_retry_after_header=True,
|
|
97
|
+
)
|
|
98
|
+
adapter = HTTPAdapter(max_retries=retry)
|
|
99
|
+
self.session.mount("http://", adapter)
|
|
100
|
+
self.session.mount("https://", adapter)
|
|
101
|
+
self.session.verify = verify
|
|
102
|
+
if not verify:
|
|
103
|
+
try:
|
|
104
|
+
from urllib3.exceptions import InsecureRequestWarning
|
|
105
|
+
import urllib3
|
|
106
|
+
urllib3.disable_warnings(InsecureRequestWarning)
|
|
107
|
+
except Exception:
|
|
108
|
+
pass
|
|
109
|
+
if auth is not None:
|
|
110
|
+
self.session.auth = auth
|
|
111
|
+
self.session.headers.setdefault("Accept", "application/json")
|
|
112
|
+
|
|
113
|
+
def _url(self, path: str) -> str:
|
|
114
|
+
path = path.lstrip("/")
|
|
115
|
+
return urljoin(
|
|
116
|
+
self.base_url + "/" + self.api_prefix + "/",
|
|
117
|
+
path,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def _request(self, method: str, path: str, **kwargs) -> Any:
|
|
121
|
+
resp = self.session.request(
|
|
122
|
+
method, self._url(path), timeout=self.timeout, **kwargs
|
|
123
|
+
)
|
|
124
|
+
if resp.status_code == 401:
|
|
125
|
+
raise GNS3Error("401 Unauthorized — check GNS3_USER / GNS3_PASSWORD.")
|
|
126
|
+
if resp.status_code == 403:
|
|
127
|
+
raise GNS3Error("403 Forbidden — this account cannot perform that call.")
|
|
128
|
+
if resp.status_code == 404:
|
|
129
|
+
raise GNS3Error(f"404 Not Found: {path}")
|
|
130
|
+
if resp.status_code >= 400:
|
|
131
|
+
raise GNS3Error(
|
|
132
|
+
f"{resp.status_code} {resp.reason}: {resp.text[:300]}"
|
|
133
|
+
)
|
|
134
|
+
if resp.status_code == 204 or not resp.content:
|
|
135
|
+
return None
|
|
136
|
+
ctype = resp.headers.get("Content-Type", "")
|
|
137
|
+
if "application/json" in ctype:
|
|
138
|
+
return resp.json()
|
|
139
|
+
return resp.text
|
|
140
|
+
|
|
141
|
+
# -- Server -----------------------------------------------------
|
|
142
|
+
|
|
143
|
+
def version(self) -> dict:
|
|
144
|
+
return self._request("GET", "version")
|
|
145
|
+
|
|
146
|
+
# -- Projects ---------------------------------------------------
|
|
147
|
+
|
|
148
|
+
def list_projects(self) -> list[Project]:
|
|
149
|
+
data = self._request("GET", "projects") or []
|
|
150
|
+
return [
|
|
151
|
+
Project(
|
|
152
|
+
project_id=p.get("project_id") or p.get("id") or "",
|
|
153
|
+
name=p.get("name", ""),
|
|
154
|
+
status=p.get("status"),
|
|
155
|
+
path=p.get("path"),
|
|
156
|
+
)
|
|
157
|
+
for p in data
|
|
158
|
+
]
|
|
159
|
+
|
|
160
|
+
def get_project(self, project_id: str) -> dict:
|
|
161
|
+
return self._request("GET", f"projects/{project_id}")
|
|
162
|
+
|
|
163
|
+
def open_project(self, project_id: str) -> dict:
|
|
164
|
+
return self._request("POST", f"projects/{project_id}/open")
|
|
165
|
+
|
|
166
|
+
def close_project(self, project_id: str) -> None:
|
|
167
|
+
self._request("POST", f"projects/{project_id}/close")
|
|
168
|
+
|
|
169
|
+
def resolve_project_id(self, ref: str) -> str:
|
|
170
|
+
"""Accept either a project_id or a project name; return the id."""
|
|
171
|
+
for p in self.list_projects():
|
|
172
|
+
if ref in (p.project_id, p.name):
|
|
173
|
+
return p.project_id
|
|
174
|
+
raise GNS3Error(f"no project matches {ref!r}")
|
|
175
|
+
|
|
176
|
+
# -- Nodes ------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
def list_nodes(self, project_id: str) -> list[Node]:
|
|
179
|
+
data = self._request("GET", f"projects/{project_id}/nodes") or []
|
|
180
|
+
return [
|
|
181
|
+
Node(
|
|
182
|
+
node_id=n.get("node_id", ""),
|
|
183
|
+
name=n.get("name", ""),
|
|
184
|
+
node_type=n.get("node_type", ""),
|
|
185
|
+
status=n.get("status"),
|
|
186
|
+
console=n.get("console"),
|
|
187
|
+
console_type=n.get("console_type"),
|
|
188
|
+
)
|
|
189
|
+
for n in data
|
|
190
|
+
]
|
|
191
|
+
|
|
192
|
+
def resolve_node_id(self, project_id: str, ref: str) -> str:
|
|
193
|
+
for n in self.list_nodes(project_id):
|
|
194
|
+
if ref in (n.node_id, n.name):
|
|
195
|
+
return n.node_id
|
|
196
|
+
raise GNS3Error(f"no node matches {ref!r} in project {project_id}")
|
|
197
|
+
|
|
198
|
+
def _node_action(self, project_id: str, node_id: str, action: str) -> dict | None:
|
|
199
|
+
return self._request(
|
|
200
|
+
"POST", f"projects/{project_id}/nodes/{node_id}/{action}"
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
def start_node(self, project_id: str, node_id: str) -> dict | None:
|
|
204
|
+
return self._node_action(project_id, node_id, "start")
|
|
205
|
+
|
|
206
|
+
def stop_node(self, project_id: str, node_id: str) -> dict | None:
|
|
207
|
+
return self._node_action(project_id, node_id, "stop")
|
|
208
|
+
|
|
209
|
+
def reload_node(self, project_id: str, node_id: str) -> dict | None:
|
|
210
|
+
return self._node_action(project_id, node_id, "reload")
|
|
211
|
+
|
|
212
|
+
def suspend_node(self, project_id: str, node_id: str) -> dict | None:
|
|
213
|
+
return self._node_action(project_id, node_id, "suspend")
|
|
214
|
+
|
|
215
|
+
def start_all_nodes(self, project_id: str) -> None:
|
|
216
|
+
self._request("POST", f"projects/{project_id}/nodes/start")
|
|
217
|
+
|
|
218
|
+
def stop_all_nodes(self, project_id: str) -> None:
|
|
219
|
+
self._request("POST", f"projects/{project_id}/nodes/stop")
|
|
220
|
+
|
|
221
|
+
def reload_all_nodes(self, project_id: str) -> None:
|
|
222
|
+
self._request("POST", f"projects/{project_id}/nodes/reload")
|
|
223
|
+
|
|
224
|
+
def suspend_all_nodes(self, project_id: str) -> None:
|
|
225
|
+
self._request("POST", f"projects/{project_id}/nodes/suspend")
|
|
226
|
+
|
|
227
|
+
# -- Links ------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
def list_links(self, project_id: str) -> list[Link]:
|
|
230
|
+
data = self._request("GET", f"projects/{project_id}/links") or []
|
|
231
|
+
return [
|
|
232
|
+
Link(
|
|
233
|
+
link_id=l.get("link_id", ""),
|
|
234
|
+
nodes=l.get("nodes") or [],
|
|
235
|
+
link_type=l.get("link_type"),
|
|
236
|
+
)
|
|
237
|
+
for l in data
|
|
238
|
+
]
|
|
239
|
+
|
|
240
|
+
def delete_link(self, project_id: str, link_id: str) -> None:
|
|
241
|
+
self._request("DELETE", f"projects/{project_id}/links/{link_id}")
|
|
242
|
+
|
|
243
|
+
# -- Templates --------------------------------------------------
|
|
244
|
+
|
|
245
|
+
def list_templates(self) -> list[Template]:
|
|
246
|
+
data = self._request("GET", "templates") or []
|
|
247
|
+
return [
|
|
248
|
+
Template(
|
|
249
|
+
template_id=t.get("template_id", ""),
|
|
250
|
+
name=t.get("name", ""),
|
|
251
|
+
template_type=t.get("template_type", ""),
|
|
252
|
+
builtin=bool(t.get("builtin", False)),
|
|
253
|
+
)
|
|
254
|
+
for t in data
|
|
255
|
+
]
|
|
256
|
+
|
|
257
|
+
# -- Computes ---------------------------------------------------
|
|
258
|
+
|
|
259
|
+
def list_computes(self) -> list[Compute]:
|
|
260
|
+
data = self._request("GET", "computes") or []
|
|
261
|
+
return [
|
|
262
|
+
Compute(
|
|
263
|
+
compute_id=c.get("compute_id", ""),
|
|
264
|
+
name=c.get("name", ""),
|
|
265
|
+
host=c.get("host"),
|
|
266
|
+
protocol=c.get("protocol"),
|
|
267
|
+
port=c.get("port"),
|
|
268
|
+
connected=c.get("connected"),
|
|
269
|
+
)
|
|
270
|
+
for c in data
|
|
271
|
+
]
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""gns3ctl configuration — env vars first, YAML as fallback.
|
|
2
|
+
|
|
3
|
+
Precedence (first match wins):
|
|
4
|
+
|
|
5
|
+
1. $GNS3_URL / $GNS3_USER / $GNS3_PASSWORD / $GNS3_VERIFY_SSL
|
|
6
|
+
2. ~/.local/etc/gns3ctl/config.yaml
|
|
7
|
+
|
|
8
|
+
A stub yaml is written on first run so there's always something to
|
|
9
|
+
edit, but gns3ctl works with only env vars set.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import yaml
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
CONFIG_DIR = Path.home() / ".local" / "etc" / "gns3ctl"
|
|
21
|
+
CONFIG_PATH = CONFIG_DIR / "config.yaml"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
TEMPLATE = """\
|
|
25
|
+
gns3:
|
|
26
|
+
# Base URL of the GNS3 server, e.g. http://localhost:3080
|
|
27
|
+
url: http://localhost:3080
|
|
28
|
+
# Optional: pin to a specific project by id or name. Blank = none.
|
|
29
|
+
default_project: ""
|
|
30
|
+
|
|
31
|
+
authentication:
|
|
32
|
+
# Basic auth is what the GNS3 server exposes. Leave both blank for
|
|
33
|
+
# unauthenticated local servers (the default when you run GNS3 from
|
|
34
|
+
# the GUI without touching server settings).
|
|
35
|
+
username: ""
|
|
36
|
+
password_env: GNS3_PASSWORD
|
|
37
|
+
|
|
38
|
+
settings:
|
|
39
|
+
timeout: 30
|
|
40
|
+
# API prefix. v2 is current for GNS3 2.x; v3 for GNS3 3.x.
|
|
41
|
+
api_version: v2
|
|
42
|
+
# Verify TLS. GNS3_VERIFY_SSL=false in the env also disables.
|
|
43
|
+
verify_ssl: true
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
USAGE = f"""\
|
|
48
|
+
gns3ctl configuration
|
|
49
|
+
=====================
|
|
50
|
+
|
|
51
|
+
Fastest path:
|
|
52
|
+
|
|
53
|
+
gns3ctl-setup
|
|
54
|
+
|
|
55
|
+
That prompts for URL / user / password and writes an export block to
|
|
56
|
+
your shell rc. Reload the shell and gns3ctl is wired up.
|
|
57
|
+
|
|
58
|
+
Alternatively, edit the config file at:
|
|
59
|
+
{CONFIG_PATH}
|
|
60
|
+
|
|
61
|
+
Env vars (take precedence over the yaml):
|
|
62
|
+
GNS3_URL e.g. http://localhost:3080
|
|
63
|
+
GNS3_USER optional, basic-auth username
|
|
64
|
+
GNS3_PASSWORD optional, basic-auth password
|
|
65
|
+
GNS3_API_VERSION v2 (default) or v3
|
|
66
|
+
GNS3_VERIFY_SSL false to skip TLS verification
|
|
67
|
+
GNS3_DEFAULT_PROJECT id or name used when --project is omitted
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def write_template() -> None:
|
|
72
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
CONFIG_PATH.write_text(TEMPLATE)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def load() -> dict | None:
|
|
77
|
+
if not CONFIG_PATH.exists():
|
|
78
|
+
return None
|
|
79
|
+
with CONFIG_PATH.open() as f:
|
|
80
|
+
return yaml.safe_load(f) or {}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _get(cfg, path):
|
|
84
|
+
node = cfg
|
|
85
|
+
for key in path:
|
|
86
|
+
if not isinstance(node, dict):
|
|
87
|
+
return None
|
|
88
|
+
node = node.get(key)
|
|
89
|
+
return node
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def bootstrap() -> str:
|
|
93
|
+
"""Return 'ok' / 'created' / 'unconfigured'.
|
|
94
|
+
|
|
95
|
+
Env-var config is sufficient; the yaml is only consulted when
|
|
96
|
+
GNS3_URL is not exported.
|
|
97
|
+
"""
|
|
98
|
+
if os.getenv("GNS3_URL"):
|
|
99
|
+
return "ok"
|
|
100
|
+
if not CONFIG_PATH.exists():
|
|
101
|
+
write_template()
|
|
102
|
+
return "created"
|
|
103
|
+
cfg = load() or {}
|
|
104
|
+
url = _get(cfg, ("gns3", "url"))
|
|
105
|
+
if not url or url == "http://localhost:3080" and not _get(cfg, ("authentication", "username")):
|
|
106
|
+
# Default localhost is a perfectly valid value — only treat as
|
|
107
|
+
# unconfigured if the url is missing/blank entirely.
|
|
108
|
+
if not url:
|
|
109
|
+
return "unconfigured"
|
|
110
|
+
return "ok"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def resolve_url(cfg) -> str:
|
|
114
|
+
return (os.getenv("GNS3_URL") or _get(cfg, ("gns3", "url")) or "").strip()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def resolve_api_version(cfg) -> str:
|
|
118
|
+
return (
|
|
119
|
+
os.getenv("GNS3_API_VERSION")
|
|
120
|
+
or _get(cfg, ("settings", "api_version"))
|
|
121
|
+
or "v2"
|
|
122
|
+
).strip().lstrip("v") # stored as plain digit; client re-prefixes
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def resolve_default_project(cfg) -> str | None:
|
|
126
|
+
val = (
|
|
127
|
+
os.getenv("GNS3_DEFAULT_PROJECT")
|
|
128
|
+
or _get(cfg, ("gns3", "default_project"))
|
|
129
|
+
or ""
|
|
130
|
+
).strip()
|
|
131
|
+
return val or None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def resolve_verify_ssl(cfg) -> bool:
|
|
135
|
+
env = os.getenv("GNS3_VERIFY_SSL")
|
|
136
|
+
if env is not None:
|
|
137
|
+
return env.strip().lower() not in ("0", "false", "no", "off", "")
|
|
138
|
+
val = _get(cfg, ("settings", "verify_ssl"))
|
|
139
|
+
if val is None:
|
|
140
|
+
return True
|
|
141
|
+
if isinstance(val, bool):
|
|
142
|
+
return val
|
|
143
|
+
return str(val).strip().lower() not in ("0", "false", "no", "off")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def resolve_auth(cfg):
|
|
147
|
+
"""Return a (username, password) tuple, or None when no creds are set.
|
|
148
|
+
|
|
149
|
+
GNS3 2.x servers default to open; auth is optional. If a username
|
|
150
|
+
is configured but no password can be found, we raise so the user
|
|
151
|
+
knows to set GNS3_PASSWORD.
|
|
152
|
+
"""
|
|
153
|
+
username = (
|
|
154
|
+
os.getenv("GNS3_USER")
|
|
155
|
+
or _get(cfg, ("authentication", "username"))
|
|
156
|
+
or ""
|
|
157
|
+
).strip()
|
|
158
|
+
if not username:
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
password_env = _get(cfg, ("authentication", "password_env")) or "GNS3_PASSWORD"
|
|
162
|
+
password = os.getenv("GNS3_PASSWORD") or os.getenv(password_env)
|
|
163
|
+
if not password:
|
|
164
|
+
raise RuntimeError(
|
|
165
|
+
f"Env var {password_env} is not set. Run gns3ctl-setup or export it manually."
|
|
166
|
+
)
|
|
167
|
+
return (username, password)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def resolve_timeout(cfg) -> int:
|
|
171
|
+
val = _get(cfg, ("settings", "timeout"))
|
|
172
|
+
try:
|
|
173
|
+
return int(val) if val is not None else 30
|
|
174
|
+
except (TypeError, ValueError):
|
|
175
|
+
return 30
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""`gns3ctl-setup` — write GNS3 exports to the user's shell rc.
|
|
2
|
+
|
|
3
|
+
Prompts for URL, username, password, default project, and writes an
|
|
4
|
+
export block to `.zshrc` / `.bashrc` / `.bash_profile`. Re-runs edit
|
|
5
|
+
the existing block in place.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import getpass
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
MARK_START = "# >>> gns3ctl setup >>>"
|
|
18
|
+
MARK_END = "# <<< gns3ctl setup <<<"
|
|
19
|
+
_BLOCK_RE = re.compile(
|
|
20
|
+
re.escape(MARK_START) + r".*?" + re.escape(MARK_END) + r"\n?",
|
|
21
|
+
re.DOTALL,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _detect_rc() -> Path:
|
|
26
|
+
shell = os.environ.get("SHELL", "")
|
|
27
|
+
if shell.endswith("zsh"):
|
|
28
|
+
return Path.home() / ".zshrc"
|
|
29
|
+
if shell.endswith("bash"):
|
|
30
|
+
bashrc = Path.home() / ".bashrc"
|
|
31
|
+
if sys.platform == "darwin" and not bashrc.exists():
|
|
32
|
+
return Path.home() / ".bash_profile"
|
|
33
|
+
return bashrc
|
|
34
|
+
return Path.home() / ".profile"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _shell_escape(value: str) -> str:
|
|
38
|
+
return (
|
|
39
|
+
value.replace("\\", "\\\\")
|
|
40
|
+
.replace('"', '\\"')
|
|
41
|
+
.replace("$", "\\$")
|
|
42
|
+
.replace("`", "\\`")
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _render_block(
|
|
47
|
+
url: str,
|
|
48
|
+
user: str,
|
|
49
|
+
password: str,
|
|
50
|
+
default_project: str,
|
|
51
|
+
api_version: str,
|
|
52
|
+
verify_ssl: bool,
|
|
53
|
+
) -> str:
|
|
54
|
+
lines = [MARK_START, f'export GNS3_URL="{_shell_escape(url)}"']
|
|
55
|
+
if user:
|
|
56
|
+
lines.append(f'export GNS3_USER="{_shell_escape(user)}"')
|
|
57
|
+
if password:
|
|
58
|
+
lines.append(f'export GNS3_PASSWORD="{_shell_escape(password)}"')
|
|
59
|
+
if default_project:
|
|
60
|
+
lines.append(f'export GNS3_DEFAULT_PROJECT="{_shell_escape(default_project)}"')
|
|
61
|
+
if api_version and api_version != "v2":
|
|
62
|
+
lines.append(f'export GNS3_API_VERSION="{_shell_escape(api_version)}"')
|
|
63
|
+
if not verify_ssl:
|
|
64
|
+
lines.append('export GNS3_VERIFY_SSL="false"')
|
|
65
|
+
lines.append(MARK_END)
|
|
66
|
+
return "\n".join(lines) + "\n"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _upsert_block(rc: Path, block: str) -> bool:
|
|
70
|
+
original = rc.read_text() if rc.exists() else ""
|
|
71
|
+
if _BLOCK_RE.search(original):
|
|
72
|
+
updated = _BLOCK_RE.sub(block, original)
|
|
73
|
+
else:
|
|
74
|
+
separator = "" if not original or original.endswith("\n") else "\n"
|
|
75
|
+
updated = original + separator + "\n" + block
|
|
76
|
+
if updated == original:
|
|
77
|
+
return False
|
|
78
|
+
rc.parent.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
rc.write_text(updated)
|
|
80
|
+
try:
|
|
81
|
+
rc.chmod(0o600)
|
|
82
|
+
except OSError:
|
|
83
|
+
pass
|
|
84
|
+
return True
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _prompt(label: str, default: str = "") -> str:
|
|
88
|
+
suffix = f" [{default}]" if default else ""
|
|
89
|
+
value = input(f"{label}{suffix}: ").strip()
|
|
90
|
+
return value or default
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def main() -> int:
|
|
94
|
+
print("gns3ctl-setup — write GNS3 exports to your shell rc.")
|
|
95
|
+
print("Current values (if any) are shown as defaults; press Enter to keep.\n")
|
|
96
|
+
|
|
97
|
+
url = _prompt(
|
|
98
|
+
"GNS3 server URL (e.g. http://localhost:3080)",
|
|
99
|
+
os.environ.get("GNS3_URL", "http://localhost:3080"),
|
|
100
|
+
)
|
|
101
|
+
user = _prompt(
|
|
102
|
+
"GNS3 username (leave blank for an unauthenticated server)",
|
|
103
|
+
os.environ.get("GNS3_USER", ""),
|
|
104
|
+
)
|
|
105
|
+
current_password = os.environ.get("GNS3_PASSWORD", "")
|
|
106
|
+
if user:
|
|
107
|
+
prompt = (
|
|
108
|
+
"GNS3 password (hidden; press Enter to keep existing)"
|
|
109
|
+
if current_password
|
|
110
|
+
else "GNS3 password (hidden)"
|
|
111
|
+
)
|
|
112
|
+
password = getpass.getpass(f"{prompt}: ").strip() or current_password
|
|
113
|
+
else:
|
|
114
|
+
password = ""
|
|
115
|
+
default_project = _prompt(
|
|
116
|
+
"Default project id or name (blank for none)",
|
|
117
|
+
os.environ.get("GNS3_DEFAULT_PROJECT", ""),
|
|
118
|
+
)
|
|
119
|
+
api_version = _prompt(
|
|
120
|
+
"API version (v2 for GNS3 2.x, v3 for 3.x)",
|
|
121
|
+
os.environ.get("GNS3_API_VERSION", "v2"),
|
|
122
|
+
)
|
|
123
|
+
current_verify = os.environ.get("GNS3_VERIFY_SSL", "true").strip().lower()
|
|
124
|
+
default_verify = current_verify not in ("0", "false", "no", "off")
|
|
125
|
+
verify_answer = _prompt(
|
|
126
|
+
"Verify TLS cert? [y/n]", "y" if default_verify else "n"
|
|
127
|
+
)
|
|
128
|
+
verify_ssl = verify_answer.strip().lower() not in ("n", "no", "false", "0")
|
|
129
|
+
|
|
130
|
+
if not url:
|
|
131
|
+
print("error: GNS3 server URL is required.", file=sys.stderr)
|
|
132
|
+
return 2
|
|
133
|
+
if user and not password:
|
|
134
|
+
print("error: a username was given but no password is available.", file=sys.stderr)
|
|
135
|
+
return 2
|
|
136
|
+
|
|
137
|
+
rc = _detect_rc()
|
|
138
|
+
block = _render_block(url, user, password, default_project, api_version, verify_ssl)
|
|
139
|
+
changed = _upsert_block(rc, block)
|
|
140
|
+
|
|
141
|
+
if changed:
|
|
142
|
+
print(f"\nWrote gns3ctl exports to {rc} (chmod 600).")
|
|
143
|
+
else:
|
|
144
|
+
print(f"\nNo changes needed — {rc} already up to date.")
|
|
145
|
+
print(f"Reload with: source {rc}")
|
|
146
|
+
print("Verify with: env | grep GNS3_")
|
|
147
|
+
return 0
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gns3ctl
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CLI for controlling a GNS3 server — projects, nodes, links, templates — via the GNS3 REST API
|
|
5
|
+
Author-email: Jakob Holst <code@jakobholst.dk>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://gitlab.com/jakobholst/gns3ctl
|
|
8
|
+
Project-URL: Repository, https://gitlab.com/jakobholst/gns3ctl
|
|
9
|
+
Keywords: gns3,network,simulator,cli,automation,rest,api
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: System Administrators
|
|
13
|
+
Classifier: Intended Audience :: Information Technology
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: System :: Networking
|
|
18
|
+
Classifier: Topic :: Utilities
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: requests>=2.28
|
|
22
|
+
Requires-Dist: pyyaml>=6.0
|
|
23
|
+
|
|
24
|
+
# gns3ctl
|
|
25
|
+
|
|
26
|
+
`gns3ctl` drives a [GNS3](https://www.gns3.com/) server from the command
|
|
27
|
+
line via its REST API. It covers the day-to-day things you'd otherwise
|
|
28
|
+
have to click through in the GUI: list / open / close projects, see
|
|
29
|
+
and operate on nodes (start / stop / reload / suspend), inspect links,
|
|
30
|
+
templates and computes.
|
|
31
|
+
|
|
32
|
+
| Command | Purpose |
|
|
33
|
+
|--------------------|------------------------------------------------------------------|
|
|
34
|
+
| `gns3ctl` | Main CLI with subcommands (projects, nodes, links, …) |
|
|
35
|
+
| `gns3ctl-setup` | Interactive first-run: writes `GNS3_*` exports to your shell rc |
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install gns3ctl
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Configure
|
|
44
|
+
|
|
45
|
+
### Quickest: `gns3ctl-setup`
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
gns3ctl-setup
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Prompts for URL, user, password, default project; writes an idempotent
|
|
52
|
+
export block into `~/.zshrc` / `~/.bashrc` / `~/.bash_profile`.
|
|
53
|
+
|
|
54
|
+
### Env vars
|
|
55
|
+
|
|
56
|
+
| Variable | Meaning |
|
|
57
|
+
|-------------------------|--------------------------------------------------------|
|
|
58
|
+
| `GNS3_URL` | Base URL, e.g. `http://localhost:3080` |
|
|
59
|
+
| `GNS3_USER` | Basic-auth username (omit for open servers) |
|
|
60
|
+
| `GNS3_PASSWORD` | Basic-auth password |
|
|
61
|
+
| `GNS3_API_VERSION` | `v2` (default) or `v3` |
|
|
62
|
+
| `GNS3_VERIFY_SSL` | `false` to skip TLS verification |
|
|
63
|
+
| `GNS3_DEFAULT_PROJECT` | Id or name used when `--project` is omitted |
|
|
64
|
+
|
|
65
|
+
### YAML (fallback)
|
|
66
|
+
|
|
67
|
+
A stub is written to `~/.local/etc/gns3ctl/config.yaml` on first run if
|
|
68
|
+
`GNS3_URL` isn't exported. Env vars always win.
|
|
69
|
+
|
|
70
|
+
## Usage
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
# Server info
|
|
74
|
+
gns3ctl version
|
|
75
|
+
|
|
76
|
+
# Projects
|
|
77
|
+
gns3ctl projects list
|
|
78
|
+
gns3ctl projects open my-lab
|
|
79
|
+
gns3ctl projects close my-lab
|
|
80
|
+
|
|
81
|
+
# Nodes (requires a project — --project or GNS3_DEFAULT_PROJECT)
|
|
82
|
+
gns3ctl --project my-lab nodes list
|
|
83
|
+
gns3ctl --project my-lab nodes start R1
|
|
84
|
+
gns3ctl --project my-lab nodes stop --all
|
|
85
|
+
gns3ctl --project my-lab nodes reload R1
|
|
86
|
+
gns3ctl --project my-lab nodes suspend R1
|
|
87
|
+
|
|
88
|
+
# Links / templates / computes
|
|
89
|
+
gns3ctl --project my-lab links list
|
|
90
|
+
gns3ctl templates list
|
|
91
|
+
gns3ctl computes list
|
|
92
|
+
|
|
93
|
+
# JSON output, overriding the server URL
|
|
94
|
+
gns3ctl --url http://gns3.lab:3080 --json projects list
|
|
95
|
+
|
|
96
|
+
# Self-signed GNS3 server
|
|
97
|
+
gns3ctl --insecure projects list
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Project and node refs accept either the id or the name — `gns3ctl`
|
|
101
|
+
resolves the name against `GET /projects` or `GET /nodes` and uses the
|
|
102
|
+
id for the subsequent call.
|
|
103
|
+
|
|
104
|
+
## Exit codes
|
|
105
|
+
|
|
106
|
+
| Code | Meaning |
|
|
107
|
+
|------|------------------------------------------------------|
|
|
108
|
+
| 0 | Success |
|
|
109
|
+
| 1 | GNS3 server returned an error (auth, 4xx, 5xx, etc.) |
|
|
110
|
+
| 2 | Usage / configuration problem |
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/gns3ctl/__init__.py
|
|
4
|
+
src/gns3ctl/__main__.py
|
|
5
|
+
src/gns3ctl/cli.py
|
|
6
|
+
src/gns3ctl/client.py
|
|
7
|
+
src/gns3ctl/config.py
|
|
8
|
+
src/gns3ctl/setup.py
|
|
9
|
+
src/gns3ctl.egg-info/PKG-INFO
|
|
10
|
+
src/gns3ctl.egg-info/SOURCES.txt
|
|
11
|
+
src/gns3ctl.egg-info/dependency_links.txt
|
|
12
|
+
src/gns3ctl.egg-info/entry_points.txt
|
|
13
|
+
src/gns3ctl.egg-info/requires.txt
|
|
14
|
+
src/gns3ctl.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gns3ctl
|