mirror of
https://github.com/DaanSelen/meshbook.git
synced 2026-02-21 00:42:14 +00:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74d1e8f3bb | ||
|
|
7dd32902c4 | ||
|
|
0cd653dfe3 | ||
|
|
ba970f585a | ||
|
|
15c8500042 | ||
|
|
234683e49c | ||
|
|
f04e49eb7d | ||
|
|
046c2200db | ||
|
|
876ea0738e | ||
|
|
b5aa645850 | ||
|
|
172ae126ea | ||
|
|
6fb5ec2bc8 | ||
|
|
f67a36f8b7 | ||
|
|
577a8266ee | ||
|
|
5492bd7e2f | ||
|
|
27473583e4 | ||
|
|
32069cd266 | ||
|
|
6a0127be78 | ||
|
|
e5e4aba47e | ||
|
|
e8e08d0d72 | ||
|
|
a1fb69652b | ||
|
|
df2185612a | ||
|
|
8aea76fd1e | ||
|
|
1fd09beaf9 | ||
|
|
c702107b0a | ||
|
|
917e4b3c9e | ||
|
|
48b77f5e66 | ||
|
|
bccebb4707 | ||
|
|
c66c7bbb98 | ||
|
|
88e2115be9 | ||
|
|
f05ab15d4b |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -2,6 +2,9 @@
|
||||
venv
|
||||
.vscode
|
||||
|
||||
# temporary or to prevent big commits
|
||||
examples/
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
189
README.md
189
README.md
@@ -1,114 +1,173 @@
|
||||
> [!NOTE]
|
||||
> *If you experience issues or have suggestions, submit an issue! https://github.com/DaanSelen/meshbook/issues I'll respond ASAP!*
|
||||
|
||||
# Meshbook
|
||||
|
||||
A way to programmatically manage MeshCentral-managed machines, a bit like Ansible does.<br>
|
||||
What problem does it solve? Well, what I wanted to be able to do is to automate system updates through [MeshCentral](https://github.com/ylianst/meshcentral).<br>
|
||||
A way to programmatically manage MeshCentral-managed machines, inspired by applications like [Ansible](https://github.com/ansible/ansible).<br>
|
||||
What problem does it solve? Well, what I wanted to be able to do is to automate system updates through [MeshCentral](https://github.com/ylianst/meshcentral). And some machines are behind unmanaged or 3rd party managed firewalls.<br>
|
||||
And many people will be comfortable with YAML configurations! It's almost like JSON, but different!<br>
|
||||
|
||||
# Quick-start:
|
||||
|
||||
The quickest way to start is to grab a template from the templates folder in this repository.<br>
|
||||
Make sure to correctly pass the MeshCentral websocket API as `wss://<MeshCentral-Host>/control.ashx`.<br>
|
||||
And make sure to fill in the credentails of an account which has remote commands permissions.<br>
|
||||
Make sure to correctly pass the MeshCentral websocket API as `wss://<MeshCentral-Host>`.<br>
|
||||
And make sure to fill in the credentails of an account which has `Remote Commands` permissions on the targeted devices or groups.<br>
|
||||
|
||||
> I did this through a "Global Service" group which I added the meshbook account to!
|
||||
|
||||
Then make a yaml with a target and some commands! See below examples as a guideline. And do not forget to look at the bottom's notice.<br>
|
||||
To install, follow the following commands:<br>
|
||||
|
||||
### Linux setup:
|
||||
|
||||
```shell
|
||||
git clone https://github.com/daanselen/meshbook
|
||||
cd ./meshbook
|
||||
python3 -m venv ./venv
|
||||
source ./venv/bin/activate
|
||||
pip3 install -r requirements.txt
|
||||
pip3 install -r ./requirements.txt
|
||||
```
|
||||
Then you can use meshbook, for example:
|
||||
|
||||
### Windows setup:
|
||||
|
||||
```shell
|
||||
python3 meshbook.py -pb examples/ping.yaml
|
||||
git clone https://github.com/daanselen/meshbook
|
||||
cd ./meshbook
|
||||
python3 -m venv ./venv
|
||||
.\venv\Scripts\activate # Make sure to check the terminal prefix.
|
||||
pip3 install -r ./requirements.txt
|
||||
```
|
||||
|
||||
# Example:
|
||||
Now copy the configuration template from ./templates and fill it in with the correct details. The url should start with `wss://`.<br>
|
||||
After this you can use meshbook, for example:
|
||||
|
||||
For the example, I used the following yaml file:
|
||||
### Linux run:
|
||||
|
||||
```shell
|
||||
python3 .\meshbook.py -pb .\examples\echo.yaml
|
||||
```
|
||||
|
||||
### Windows run:
|
||||
|
||||
```shell
|
||||
.\venv\Scripts\python.exe .\meshbook.py -pb .\examples\echo.yaml
|
||||
```
|
||||
|
||||
### How to check if everything is okay?
|
||||
|
||||
The python virtual environment can get messed up, therefore...<br>
|
||||
To check if everything is in working order, make sure that the lists from the following commands are aligned:
|
||||
|
||||
```
|
||||
python3 -m pip list
|
||||
pip3 list
|
||||
```
|
||||
|
||||
If not, perhaps you are using the wrong executable, the wrong environment and so on...
|
||||
|
||||
# How to create a configuration?
|
||||
|
||||
This paragraph explains how the program interprets certain information.
|
||||
|
||||
### Targeting:
|
||||
|
||||
MeshCentral has `meshes` or `groups`, in this program they are called `group(s)`. Because of the way I designed this.<br>
|
||||
So to target for example a mesh/group in MeshCentral called: "Nerthus" do:
|
||||
|
||||
> If your group has multiple words, then you need to use `"` to group the words.
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: Ping a single Point
|
||||
company: Temp-Agents
|
||||
name: example configuration
|
||||
group: "Nerthus"
|
||||
variables:
|
||||
- name: var1
|
||||
value: "This is the first variable"
|
||||
tasks:
|
||||
- name: Ping Cloudflare
|
||||
command: "ping 1.1.1.1 -c 4"
|
||||
- name: echo the first variable!
|
||||
command: 'echo "{{ var1 }}"'
|
||||
```
|
||||
|
||||
The above group: `Temp-Agents` has four devices, of which one is offline.<br>
|
||||
It is also possible to target a single device, as seen in: [here](./examples/apt_update_example.yaml).<br>
|
||||
|
||||
### Variables:
|
||||
|
||||
Variables are done by replacing the placeholders just before the runtime (the Python program does this, not you).<br>
|
||||
So if you have var1 declared, then the value of that declaration is placed wherever it finds {{ var1 }}.<br>
|
||||
This is done to imitate popular methods. See below [from the example](./examples/variable_usage_example.yaml).<br>
|
||||
|
||||
### Tasks:
|
||||
|
||||
The tasks you want to run should be contained under the `tasks:` with two fields, `name` and `command`.<br>
|
||||
The name field is for the user of meshbook, to clarify what the following command does in a summary.<br>
|
||||
The command field actually gets executed on the end-point.<br>
|
||||
|
||||
### Granual Operating System control:
|
||||
|
||||
I have made the program so it can have a basic filter with the Operating systems. If you have a mixed group, then you need to match the image below like this:
|
||||
|
||||
<img src="./assets/meshcentral_os.png" alt="MeshCentral Operating System Version" width="600"/><br>
|
||||
<img src="./assets/meshbook_yaml_os.png" alt="MeshBook yaml example" width="600"/>
|
||||
|
||||
This will filter the nodes/machines in the MeshCentral group to the ones matching this. Very basic and open for feedback. This must match the full string, not case sensitive.
|
||||
|
||||
# Example:
|
||||
|
||||
For the example, I used the following yaml file (you can find more in [this directory](./examples/)):
|
||||
|
||||
The below group: `Dev` has three devices, of which one is offline, Meshbook checks if the device is reachable.<br>
|
||||
You can expand the command chain as follows:<br>
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: Ping Multiple Points
|
||||
company: Temp-Agents
|
||||
name: Echo a string to the terminal through the meshbook example.
|
||||
group: "Dev"
|
||||
variables:
|
||||
- name: file
|
||||
value: "/etc/os-release"
|
||||
tasks:
|
||||
- name: Ping Cloudflare
|
||||
command: "ping 1.1.1.1 -c 4"
|
||||
|
||||
- name: Ping Google
|
||||
command: "ping 8.8.8.8 -c 4"
|
||||
- name: Echo!
|
||||
command: "echo $(cat {{ file }})"
|
||||
```
|
||||
|
||||
The following response it received when executing the first yaml of the above files.
|
||||
The following response it received when executing the first yaml of the above files (without the `-s` parameters, which just outputs the below JSON).
|
||||
|
||||
```shell
|
||||
python3 meshbook.py -pb examples/ping.yaml -s
|
||||
python3 meshbook.py -pb examples/echo_example.yaml
|
||||
----------------------------------------
|
||||
Trying to load the MeshCentral account credential file...
|
||||
Trying to load the Playbook yaml file and compile it into something workable...
|
||||
Connecting to MeshCentral and establish a session using variables from previous credential file.
|
||||
Generating group list with nodes and reference the targets from that.
|
||||
----------------------------------------
|
||||
Executing playbook on the targets.
|
||||
1. Running: Echo!
|
||||
----------------------------------------
|
||||
{
|
||||
"Batch 1": [
|
||||
"Task 1": [
|
||||
{
|
||||
"action": "msg",
|
||||
"type": "runcommands",
|
||||
"result": "PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.\n64 bytes from 1.1.1.1: icmp_seq=1 ttl=59 time=6.88 ms\n64 bytes from 1.1.1.1: icmp_seq=2 ttl=59 time=6.50 ms\n64 bytes from 1.1.1.1: icmp_seq=3 ttl=59 time=6.46 ms\n64 bytes from 1.1.1.1: icmp_seq=4 ttl=59 time=6.51 ms\n\n--- 1.1.1.1 ping statistics ---\n4 packets transmitted, 4 received, 0% packet loss, time 3005ms\nrtt min/avg/max/mdev = 6.460/6.588/6.879/0.169 ms\n",
|
||||
"responseid": "meshctrl",
|
||||
"nodeid": "MSI"
|
||||
"complete": true,
|
||||
"result": "PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\" NAME=\"Debian GNU/Linux\" VERSION_ID=\"12\" VERSION=\"12 (bookworm)\" VERSION_CODENAME=bookworm ID=debian HOME_URL=\"https://www.debian.org/\" SUPPORT_URL=\"https://www.debian.org/support\" BUG_REPORT_URL=\"https://bugs.debian.org/\"\n",
|
||||
"command": "echo $(cat /etc/os-release)",
|
||||
"device_id": "<Node-Unique>",
|
||||
"device_name": "raspberrypi5"
|
||||
},
|
||||
{
|
||||
"action": "msg",
|
||||
"type": "runcommands",
|
||||
"result": "PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.\n64 bytes from 1.1.1.1: icmp_seq=1 ttl=57 time=6.22 ms\n64 bytes from 1.1.1.1: icmp_seq=2 ttl=57 time=6.07 ms\n64 bytes from 1.1.1.1: icmp_seq=3 ttl=57 time=5.97 ms\n64 bytes from 1.1.1.1: icmp_seq=4 ttl=57 time=5.90 ms\n\n--- 1.1.1.1 ping statistics ---\n4 packets transmitted, 4 received, 0% packet loss, time 3004ms\nrtt min/avg/max/mdev = 5.904/6.038/6.216/0.117 ms\n",
|
||||
"responseid": "meshctrl",
|
||||
"nodeid": "server"
|
||||
},
|
||||
{
|
||||
"action": "msg",
|
||||
"type": "runcommands",
|
||||
"result": "PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.\n64 bytes from 1.1.1.1: icmp_seq=1 ttl=59 time=6.83 ms\n64 bytes from 1.1.1.1: icmp_seq=2 ttl=59 time=6.64 ms\n64 bytes from 1.1.1.1: icmp_seq=3 ttl=59 time=6.65 ms\n64 bytes from 1.1.1.1: icmp_seq=4 ttl=59 time=6.53 ms\n\n--- 1.1.1.1 ping statistics ---\n4 packets transmitted, 4 received, 0% packet loss, time 3005ms\nrtt min/avg/max/mdev = 6.534/6.664/6.834/0.108 ms\n",
|
||||
"responseid": "meshctrl",
|
||||
"nodeid": "raspberrypi5"
|
||||
}
|
||||
],
|
||||
"Batch 2": [
|
||||
{
|
||||
"action": "msg",
|
||||
"type": "runcommands",
|
||||
"result": "PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\n64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=5.69 ms\n64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=5.22 ms\n64 bytes from 8.8.8.8: icmp_seq=3 ttl=118 time=5.19 ms\n64 bytes from 8.8.8.8: icmp_seq=4 ttl=118 time=5.16 ms\n\n--- 8.8.8.8 ping statistics ---\n4 packets transmitted, 4 received, 0% packet loss, time 3004ms\nrtt min/avg/max/mdev = 5.161/5.315/5.694/0.219 ms\n",
|
||||
"responseid": "meshctrl",
|
||||
"nodeid": "MSI"
|
||||
},
|
||||
{
|
||||
"action": "msg",
|
||||
"type": "runcommands",
|
||||
"result": "PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\n64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=5.65 ms\n64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=5.28 ms\n64 bytes from 8.8.8.8: icmp_seq=3 ttl=118 time=5.25 ms\n64 bytes from 8.8.8.8: icmp_seq=4 ttl=118 time=5.25 ms\n\n--- 8.8.8.8 ping statistics ---\n4 packets transmitted, 4 received, 0% packet loss, time 3004ms\nrtt min/avg/max/mdev = 5.246/5.357/5.648/0.168 ms\n",
|
||||
"responseid": "meshctrl",
|
||||
"nodeid": "raspberrypi5"
|
||||
},
|
||||
{
|
||||
"action": "msg",
|
||||
"type": "runcommands",
|
||||
"result": "PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\n64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=4.94 ms\n64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=4.68 ms\n64 bytes from 8.8.8.8: icmp_seq=3 ttl=118 time=4.79 ms\n64 bytes from 8.8.8.8: icmp_seq=4 ttl=118 time=4.77 ms\n\n--- 8.8.8.8 ping statistics ---\n4 packets transmitted, 4 received, 0% packet loss, time 3005ms\nrtt min/avg/max/mdev = 4.678/4.792/4.940/0.094 ms\n",
|
||||
"responseid": "meshctrl",
|
||||
"nodeid": "server"
|
||||
"complete": true,
|
||||
"result": "PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\" NAME=\"Debian GNU/Linux\" VERSION_ID=\"12\" VERSION=\"12 (bookworm)\" VERSION_CODENAME=bookworm ID=debian HOME_URL=\"https://www.debian.org/\" SUPPORT_URL=\"https://www.debian.org/support\" BUG_REPORT_URL=\"https://bugs.debian.org/\"\n",
|
||||
"command": "echo $(cat /etc/os-release)",
|
||||
"device_id": "<Node-Unique>",
|
||||
"device_name": "Cubic"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
The above without `-s` is quite verbose. use `--help` to read about parameters and getting a minimal response for example.
|
||||
|
||||
# Important Notice:
|
||||
|
||||
If you want to use this, make sure to use `NON-BLOCKING` commands. MeshCentral does not work if you send it commands that wait.<br>
|
||||
A couple examples of `BLOCKING COMMANDS` which will never get back to the main MeshCentral server:
|
||||
A couple examples of `BLOCKING COMMANDS` which will never get back to the main MeshCentral server, and Meshbook will quit after the timeout but the agent will not come back:
|
||||
|
||||
```shell
|
||||
apt upgrade # without -y.
|
||||
|
||||
11
SECURITY.md
Normal file
11
SECURITY.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| >= 1.0 | :white_check_mark: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you encounter a vulnerability, report this by sending a email to dselen@nerthus.nl or via the GitHub issues.
|
||||
BIN
assets/meshbook_yaml_os.png
Normal file
BIN
assets/meshbook_yaml_os.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
BIN
assets/meshcentral_os.png
Normal file
BIN
assets/meshcentral_os.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
31
examples/aggregate_example.yaml
Normal file
31
examples/aggregate_example.yaml
Normal file
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: Echo some text in the terminal of the device
|
||||
group: "Dev"
|
||||
variables:
|
||||
- name: package_manager
|
||||
value: "apt"
|
||||
- name: google_dns
|
||||
value: "8.8.8.8"
|
||||
- name: "quad9_dns"
|
||||
value: "9.9.9.9"
|
||||
tasks:
|
||||
- name: refresh the cache
|
||||
command: "{{ package_manager }} update"
|
||||
|
||||
- name: display available upgrades
|
||||
command: "{{ package_manager }} list --upgradable"
|
||||
|
||||
- name: apply upgrades
|
||||
command: "{{ package_manager }} upgrade -y"
|
||||
|
||||
- name: cleanup remaining packages
|
||||
command: "{{ package_manager }} autoremove -y"
|
||||
|
||||
- name: run autoclean
|
||||
command: "{{ package_manager }} autoclean -y"
|
||||
|
||||
- name: Ping Google DNS
|
||||
command: "ping {{ google_dns }} -c 4"
|
||||
|
||||
- name: Ping Quad9 DNS
|
||||
command: "ping {{ quad9_dns }} -c 4"
|
||||
12
examples/apt_update_example.yaml
Normal file
12
examples/apt_update_example.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
name: Refresh the apt cache
|
||||
device: Cubic
|
||||
variables:
|
||||
- name: package_manager
|
||||
value: "apt"
|
||||
tasks:
|
||||
- name: refresh the cache
|
||||
command: "{{ package_manager }} update"
|
||||
|
||||
- name: display available upgrades
|
||||
command: "{{ package_manager }} list --upgradable"
|
||||
18
examples/apt_upgrade_example.yaml
Normal file
18
examples/apt_upgrade_example.yaml
Normal file
@@ -0,0 +1,18 @@
|
||||
---
|
||||
name: Refresh the apt cache
|
||||
group: "Dev"
|
||||
variables:
|
||||
- name: package_manager
|
||||
value: "apt"
|
||||
tasks:
|
||||
- name: refresh the cache
|
||||
command: "{{ package_manager }} update"
|
||||
|
||||
- name: display available upgrades
|
||||
command: "{{ package_manager }} list --upgradable"
|
||||
|
||||
- name: apply upgrades
|
||||
command: "{{ package_manager }} upgrade -y"
|
||||
|
||||
- name: cleanup remaining packages
|
||||
command: "{{ package_manager }} autoremove -y"
|
||||
10
examples/echo_example.yaml
Normal file
10
examples/echo_example.yaml
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Echo a string to the terminal through the meshbook example.
|
||||
group: "Dev"
|
||||
target_os: Debian GnU/Linux 12 (bookworm)
|
||||
variables:
|
||||
- name: file
|
||||
value: "/etc/os-release"
|
||||
tasks:
|
||||
- name: Echo!
|
||||
command: "echo $(cat {{ file }})"
|
||||
18
examples/variable_usage_example.yaml
Normal file
18
examples/variable_usage_example.yaml
Normal file
@@ -0,0 +1,18 @@
|
||||
---
|
||||
name: Ping Multiple Points
|
||||
group: "Kubernetes"
|
||||
variables:
|
||||
- name: host1
|
||||
value: "1.1.1.1"
|
||||
- name: host2
|
||||
value: "9.9.9.9"
|
||||
- name: command1
|
||||
value: "ping"
|
||||
- name: cmd_arguments
|
||||
value: "-c 4"
|
||||
tasks:
|
||||
- name: Ping host1
|
||||
command: "{{ command1 }} {{ host1 }} {{ cmd_arguments }}"
|
||||
|
||||
- name: Ping host2
|
||||
command: "{{ command1 }} {{ host2 }} {{ cmd_arguments }}"
|
||||
@@ -49,29 +49,27 @@ class MeshbookUtilities:
|
||||
|
||||
return ids
|
||||
|
||||
@staticmethod
|
||||
def load_config(conffile: str = None, segment: str = 'meshcentral-service') -> ConfigParser:
|
||||
"""Load and return the configuration from a file."""
|
||||
conffile = conffile or './api.conf'
|
||||
if not os.path.exists(conffile):
|
||||
raise ScriptEndTrigger(f'Missing config file {conffile}. Provide an alternative path.')
|
||||
|
||||
try:
|
||||
my_config = ConfigParser()
|
||||
my_config.read(conffile)
|
||||
except Exception as err:
|
||||
raise ScriptEndTrigger(f'Error reading config file {conffile}: {err}')
|
||||
|
||||
if segment not in my_config:
|
||||
raise ScriptEndTrigger(f'Segment "{segment}" not found in config file {conffile}.')
|
||||
|
||||
return my_config[segment]
|
||||
|
||||
@staticmethod
|
||||
def read_yaml(file_path: str) -> dict:
|
||||
"""Read a YAML file and return its content as a dictionary."""
|
||||
with open(file_path, 'r') as file:
|
||||
return yaml.safe_load(file)
|
||||
|
||||
@staticmethod
|
||||
def replace_placeholders(playbook) -> dict:
|
||||
# Convert 'variables' to a dictionary for quick lookup
|
||||
variables = {var["name"]: var["value"] for var in playbook.get("variables", [])}
|
||||
|
||||
# Traverse 'tasks' to replace placeholders
|
||||
for task in playbook.get("tasks", []):
|
||||
command = task.get("command", "")
|
||||
for var_name, var_value in variables.items():
|
||||
placeholder = f"{{{{ {var_name} }}}}" # Create the placeholder string like "{{ host1 }}"
|
||||
command = command.replace(placeholder, var_value) # Update the command string
|
||||
task["command"] = command # Save the updated command string
|
||||
return playbook
|
||||
|
||||
@staticmethod
|
||||
def translate_nodeids(batches_dict, global_list) -> dict:
|
||||
@@ -220,6 +218,7 @@ class MeshbookProcessor:
|
||||
"""Processes messages received from the WebSocket."""
|
||||
global response_counter
|
||||
temp_responses_list = []
|
||||
|
||||
while True:
|
||||
message = await python_client.received_response_queue.get()
|
||||
action_type = message.get('action')
|
||||
@@ -250,13 +249,12 @@ class MeshcallerActions:
|
||||
"""Processes playbook actions."""
|
||||
|
||||
@staticmethod
|
||||
async def process_arguments(python_client: MeshbookWebsocket, playbook_path: str):
|
||||
async def process_arguments(python_client: MeshbookWebsocket, playbook_yaml: dict):
|
||||
"""Executes tasks defined in the playbook."""
|
||||
global response_counter, expected_responses, target_ids
|
||||
|
||||
await basic_ready_state.wait() # Wait for the basic data to be ready
|
||||
|
||||
playbook_yaml = MeshbookUtilities.read_yaml(playbook_path)
|
||||
target_ids = MeshbookUtilities.get_target_ids(
|
||||
company=playbook_yaml.get('company'),
|
||||
device=playbook_yaml.get('device')
|
||||
@@ -308,9 +306,10 @@ class MeshcallerActions:
|
||||
|
||||
async def main():
|
||||
parser = argparse.ArgumentParser(description="Process command-line arguments")
|
||||
parser.add_argument("-pb", "--playbook", type=str, help="Path to the playbook file.", required=True)
|
||||
|
||||
parser.add_argument("--conf", type=str, help="Path for the API configuration file (default: ./api.conf).")
|
||||
parser.add_argument("--nojson", action="store_true", help="Makes the program not output the JSON response data.")
|
||||
parser.add_argument("-pb", "--playbook", type=str, help="Path to the playbook file.", required=True)
|
||||
parser.add_argument("-s", "--silent", action="store_true", help="Suppress terminal output.")
|
||||
parser.add_argument("-i", "--information", action="store_true", help="Add the calculations and other informational data to the output.")
|
||||
|
||||
@@ -328,7 +327,11 @@ async def main():
|
||||
credentials['password']
|
||||
))
|
||||
processor_task = asyncio.create_task(processor.receive_processor(python_client))
|
||||
await MeshcallerActions.process_arguments(python_client, args.playbook)
|
||||
|
||||
playbook_yaml = MeshbookUtilities.read_yaml(args.playbook)
|
||||
translated_playbook = MeshbookUtilities.replace_placeholders(playbook_yaml)
|
||||
await MeshcallerActions.process_arguments(python_client, translated_playbook)
|
||||
|
||||
await asyncio.gather(websocket_task, processor_task)
|
||||
|
||||
except ScriptEndTrigger as e:
|
||||
197
meshbook.py
Normal file
197
meshbook.py
Normal file
@@ -0,0 +1,197 @@
|
||||
#!/bin/python3
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from base64 import b64encode
|
||||
from configparser import ConfigParser
|
||||
import json
|
||||
import math
|
||||
import meshctrl
|
||||
import os
|
||||
import yaml
|
||||
|
||||
'''
|
||||
Script utilities are handled in the following section.
|
||||
'''
|
||||
|
||||
class ScriptEndTrigger(Exception):
|
||||
pass
|
||||
|
||||
def output_text(message: str, required=False):
|
||||
if required:
|
||||
print(message)
|
||||
elif not args.silent:
|
||||
print(message)
|
||||
|
||||
async def load_config(conf_file: str = './api.conf', segment: str = 'meshcentral-account') -> ConfigParser:
|
||||
if not os.path.exists(conf_file):
|
||||
raise ScriptEndTrigger(f'Missing config file {conf_file}. Provide an alternative path.')
|
||||
|
||||
config = ConfigParser()
|
||||
try:
|
||||
config.read(conf_file)
|
||||
except Exception as err:
|
||||
raise ScriptEndTrigger(f"Error reading configuration file '{conf_file}': {err}")
|
||||
|
||||
if segment not in config:
|
||||
raise ScriptEndTrigger(f'Segment "{segment}" not found in config file {conf_file}.')
|
||||
|
||||
return config[segment]
|
||||
|
||||
async def init_connection(credentials: dict) -> meshctrl.Session:
|
||||
session = meshctrl.Session(
|
||||
credentials['websocket_url'],
|
||||
user=credentials['username'],
|
||||
password=credentials['password']
|
||||
)
|
||||
await session.initialized.wait()
|
||||
return session
|
||||
|
||||
async def translate_id_to_name(target_id: str, group_list: dict) -> str:
|
||||
for group in group_list:
|
||||
for device in group_list[group]:
|
||||
if device["device_id"] == target_id:
|
||||
return device["device_name"]
|
||||
|
||||
'''
|
||||
Creation and compilation happends in the following section, where the yaml gets read in, and edited accordingly.
|
||||
'''
|
||||
|
||||
async def compile_book(playbook_file: dict) -> dict:
|
||||
playbook = open(playbook_file, 'r')
|
||||
playbook = await replace_placeholders(yaml.safe_load(playbook))
|
||||
return playbook
|
||||
|
||||
async def replace_placeholders(playbook: dict) -> dict:
|
||||
variables = {var["name"]: var["value"] for var in playbook.get("variables", [])}
|
||||
|
||||
for task in playbook.get("tasks", []):
|
||||
command = task.get("command", "")
|
||||
for var_name, var_value in variables.items():
|
||||
placeholder = f"{{{{ {var_name} }}}}" # Create the placeholder string like "{{ host1 }}"
|
||||
command = command.replace(placeholder, var_value)
|
||||
task["command"] = command
|
||||
return playbook
|
||||
|
||||
'''
|
||||
Creation and compilation of the MeshCentral nodes list (list of all nodes available to the user in the configuration) is handled in the following section.
|
||||
'''
|
||||
|
||||
async def compile_group_list(session: meshctrl.Session) -> dict:
|
||||
devices_response = await session.list_devices(details=False, timeout=10)
|
||||
|
||||
local_device_list = {}
|
||||
for device in devices_response:
|
||||
if device.meshname not in local_device_list:
|
||||
local_device_list[device.meshname] = []
|
||||
|
||||
local_device_list[device.meshname].append({
|
||||
"device_id": device.nodeid,
|
||||
"device_name": device.name,
|
||||
"device_os": device.os_description,
|
||||
"device_tags": device.tags,
|
||||
"reachable": device.connected
|
||||
})
|
||||
return local_device_list
|
||||
|
||||
async def gather_targets(playbook: dict, group_list: dict) -> dict:
|
||||
target_list = []
|
||||
|
||||
if "device" in playbook and "group" not in playbook:
|
||||
pseudo_target = playbook["device"]
|
||||
|
||||
for group in group_list:
|
||||
for device in group_list[group]:
|
||||
if device["reachable"] and pseudo_target == device["device_name"]:
|
||||
if "target_os" in playbook and str(playbook["target_os"]).lower() == str(device["device_os"]).lower():
|
||||
target_list.append(device["device_id"])
|
||||
elif "target_os" not in playbook:
|
||||
target_list.append(device["device_id"])
|
||||
|
||||
elif "group" in playbook and "device" not in playbook:
|
||||
pseudo_target = playbook["group"]
|
||||
|
||||
for group in group_list:
|
||||
if pseudo_target == group:
|
||||
for device in group_list[group]:
|
||||
if device["reachable"]:
|
||||
if "target_os" in playbook and str(playbook["target_os"]).lower() == str(device["device_os"]).lower():
|
||||
target_list.append(device["device_id"])
|
||||
elif "target_os" not in playbook:
|
||||
target_list.append(device["device_id"])
|
||||
|
||||
return target_list
|
||||
|
||||
async def execute_playbook(session: meshctrl.Session, targets: dict, playbook: dict, group_list: dict) -> None:
|
||||
responses_list = {}
|
||||
round = 1
|
||||
for task in playbook["tasks"]:
|
||||
output_text(("\033[1m\033[92m" + str(round) + ". Running: " + task["name"] + "\033[0m"), False)
|
||||
response = await session.run_command(nodeids=targets, command=task["command"], ignore_output=False, timeout=900)
|
||||
|
||||
task_batch = []
|
||||
for device in response:
|
||||
device_result = response[device]["result"]
|
||||
response[device]["result"] = device_result.replace("Run commands completed.", "")
|
||||
response[device]["device_id"] = device
|
||||
response[device]["device_name"] = await translate_id_to_name(device, group_list)
|
||||
task_batch.append(response[device])
|
||||
|
||||
responses_list["Task " + str(round)] = {
|
||||
"task_name": task["name"],
|
||||
"data": task_batch
|
||||
}
|
||||
round += 1
|
||||
|
||||
output_text(("-" * 40), False)
|
||||
output_text((json.dumps(responses_list,indent=4)), True)
|
||||
|
||||
async def main():
|
||||
parser = argparse.ArgumentParser(description="Process command-line arguments")
|
||||
parser.add_argument("-pb", "--playbook", type=str, help="Path to the playbook file.", required=True)
|
||||
parser.add_argument("--conf", type=str, help="Path for the API configuration file (default: ./api.conf).", required=False)
|
||||
parser.add_argument("--nograce", action="store_true", help="Disable the grace 3 seconds before running the playbook.", required=False)
|
||||
parser.add_argument("-s", "--silent", action="store_true", help="Suppress terminal output", required=False)
|
||||
|
||||
global args
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
output_text(("-" * 40), False)
|
||||
output_text(("\x1B[3mTrying to load the MeshCentral account credential file...\x1B[0m"), False)
|
||||
output_text(("\x1B[3mTrying to load the Playbook yaml file and compile it into something workable...\x1B[0m"), False)
|
||||
|
||||
credentials, playbook = await asyncio.gather(
|
||||
(load_config() if args.conf is None else load_config(args.conf)),
|
||||
(compile_book(args.playbook))
|
||||
)
|
||||
|
||||
output_text(("\x1B[3mConnecting to MeshCentral and establish a session using variables from previous credential file.\x1B[0m"), False)
|
||||
session = await init_connection(credentials)
|
||||
|
||||
output_text(("\x1B[3mGenerating group list with nodes and reference the targets from that.\x1B[0m"), False)
|
||||
group_list = await compile_group_list(session)
|
||||
targets_list = await gather_targets(playbook, group_list)
|
||||
|
||||
if len(targets_list) == 0:
|
||||
output_text(("\033[91mNo targets found or targets unreachable, quitting.\x1B[0m"), True)
|
||||
else:
|
||||
output_text(("-" * 40), False)
|
||||
target_name = playbook["group"] if "group" in playbook else playbook["device"] # Quickly get the name.
|
||||
output_text(("\033[91mExecuting playbook on the target(s): " + target_name + ".\x1B[0m"), False)
|
||||
if not args.nograce:
|
||||
output_text(("\033[91mInitiating grace-period...\x1B[0m"), False)
|
||||
for x in range(3):
|
||||
output_text(("\033[91m{}...\x1B[0m".format(x+1)), False)
|
||||
await asyncio.sleep(1)
|
||||
output_text(("-" * 40), False)
|
||||
await execute_playbook(session, targets_list, playbook, group_list)
|
||||
|
||||
await session.close()
|
||||
|
||||
except OSError as message:
|
||||
output_text(message, True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
name: Refresh the apt cache
|
||||
company: Temp-Agents
|
||||
#device: MSI
|
||||
tasks:
|
||||
- name: refresh the cache
|
||||
command: "apt update"
|
||||
|
||||
- name: display available upgrades
|
||||
command: "apt list --upgradable"
|
||||
|
||||
- name: apply upgrades
|
||||
command: "apt upgrade -y"
|
||||
|
||||
- name: cleanup remaining packages
|
||||
command: "apt autoremove -y"
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: Ping Multiple Points
|
||||
company: Temp-Agents
|
||||
tasks:
|
||||
- name: Ping Cloudflare
|
||||
command: "ping 1.1.1.1 -c 4"
|
||||
|
||||
- name: Ping Google
|
||||
command: "ping 8.8.8.8 -c 4"
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: Refresh the apt cache
|
||||
company: Temp-Agents
|
||||
tasks:
|
||||
- name: refresh the cache
|
||||
command: "apt update"
|
||||
|
||||
- name: display available upgrades
|
||||
command: "apt list --upgradable"
|
||||
@@ -1,4 +1,4 @@
|
||||
asyncio==3.4.3
|
||||
configparser==7.1.0
|
||||
pyyaml==6.0.2
|
||||
websockets==14.1
|
||||
libmeshctrl==1.1.0
|
||||
@@ -1,4 +1,4 @@
|
||||
[meshcentral-service]
|
||||
[meshcentral-account]
|
||||
websocket_url =
|
||||
username =
|
||||
password =
|
||||
Reference in New Issue
Block a user