mirror of
https://github.com/DaanSelen/meshbook.git
synced 2026-02-20 16:32:11 +00:00
Compare commits
69 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4b6062c0e | ||
|
|
de4fe0258c | ||
|
|
1d4b89a2ed | ||
|
|
b2bf899d42 | ||
|
|
0a211da4d6 | ||
|
|
1450416d62 | ||
|
|
b0f34e9ea0 | ||
|
|
47eef4cfb0 | ||
|
|
ba74e038f7 | ||
|
|
f1df522f61 | ||
|
|
f5453353fe | ||
|
|
898098105c | ||
|
|
6f945d30d7 | ||
|
|
a722c024f5 | ||
|
|
db7ff19bfb | ||
|
|
9caa52f59e | ||
|
|
d62d80fb16 | ||
|
|
ff6e1f6cb7 | ||
|
|
a4335ce8ac | ||
|
|
30d49059c5 | ||
|
|
50e413581a | ||
|
|
64bf28c565 | ||
|
|
4359a40eb3 | ||
|
|
193cb546f4 | ||
|
|
aa1d6a1a97 | ||
|
|
e69ad445e2 | ||
|
|
bd833456d0 | ||
|
|
7f0159a8fa | ||
|
|
03683976a8 | ||
|
|
4f75969ed8 | ||
|
|
77b1cfc73c | ||
|
|
ad220e8c1a | ||
|
|
b7b9fdaea7 | ||
|
|
ab1105b058 | ||
|
|
9494aa14c9 | ||
|
|
6a7ec78fe9 | ||
|
|
1779025a97 | ||
|
|
e0de06c57e | ||
|
|
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 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,5 +1,6 @@
|
||||
*.conf
|
||||
venv
|
||||
books
|
||||
.vscode
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
|
||||
215
README.md
215
README.md
@@ -1,114 +1,183 @@
|
||||
> [!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`, `Details` and `Agent Console` permissions on the targeted devices or groups.<br>
|
||||
|
||||
> I did this through a "Service account" with rights on the device group.
|
||||
|
||||
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>
|
||||
|
||||
```shell
|
||||
### Linux setup:
|
||||
|
||||
```bash
|
||||
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
|
||||
cp ./templates/meshcentral.conf.template ./meshcentral.conf
|
||||
```
|
||||
Then you can use meshbook, for example:
|
||||
|
||||
### Windows setup (PowerShell, not cmd):
|
||||
|
||||
```shell
|
||||
python3 meshbook.py -pb examples/ping.yaml
|
||||
git clone https://github.com/daanselen/meshbook
|
||||
cd ./meshbook
|
||||
python -m venv ./venv # or python3 when done through the Microsoft Store.
|
||||
.\venv\Scripts\activate # Make sure to check the terminal prefix.
|
||||
pip3 install -r ./requirements.txt
|
||||
cp .\templates\meshcentral.conf.template .\meshcentral.conf
|
||||
```
|
||||
|
||||
# Example:
|
||||
Now copy the configuration template from ./templates and fill it in with the correct details (remove .template from the file) this is shown in the last step of the setup(s).<br>
|
||||
The url should start with `wss://`.<br>
|
||||
You can check pre-made examples in the examples directory, make sure the values are set to your situation.<br>
|
||||
After this you can use meshbook, for example:
|
||||
|
||||
For the example, I used the following yaml file:
|
||||
### Linux run:
|
||||
|
||||
```bash
|
||||
python3 .\meshbook.py -pb .\examples\echo.yaml
|
||||
```
|
||||
|
||||
### Windows run:
|
||||
|
||||
```shell
|
||||
.\venv\Scripts\python.exe .\meshbook.py -pb .\examples\echo_example.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"
|
||||
#target_os: "Linux" # <--- according to os_categories.json.
|
||||
powershell: True # <--- this can be important for Windows clients.
|
||||
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>
|
||||
|
||||
### Windows Client Extra-information:
|
||||
|
||||
If you want to launch commands at Windows machines, make sure you have your `os_categories.conf` up-to-date with the correct reported Windows versions.<br>
|
||||
And then make sure to create compatible commands, see: [windows examples](./examples/windows)<br>
|
||||
Related is the yaml option: `powershell: True`.
|
||||
|
||||
### Granual Operating System filtering:
|
||||
|
||||
I have made the program so it can have a filter with the Operating systems. If you have a mixed group, please read:
|
||||
[This explanation](./docs/operating_system_filtering.md)
|
||||
|
||||
### Tag filtering:
|
||||
|
||||
Filtering on MeshCentral tags is also possible with `target_tag` inside the meshbook. This string is case-sensitive, lower- and uppercase must match.<br>
|
||||
This is done because its human made and therefor needs to be keps well administrated.
|
||||
|
||||
# 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"
|
||||
#target_os: "Linux" # <--- according to os_categories.json
|
||||
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
|
||||
{
|
||||
"Batch 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"
|
||||
},
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
~/meshbook$ python3 meshbook.py -pb examples/echo_example.yaml
|
||||
----------------------------------------
|
||||
Playbook: examples/echo_example.yaml
|
||||
Operating System Categorisation file: ./os_categories.json
|
||||
Congiguration file: ./meshcentral.conf
|
||||
Target group: Development
|
||||
Grace: True
|
||||
Silent: False
|
||||
----------------------------------------
|
||||
Trying to load the MeshCentral account credential file...
|
||||
Trying to load the Playbook yaml file and compile it into something workable...
|
||||
Trying to load the Operating System categorisation JSON file...
|
||||
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 target(s): Development.
|
||||
Initiating grace-period...
|
||||
1...
|
||||
2...
|
||||
3...
|
||||
----------------------------------------
|
||||
1. Running: Echo!
|
||||
----------------------------------------
|
||||
{"Task 1": "ALL THE DATA"} # Not sharing due to PID
|
||||
```
|
||||
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.
|
||||
65
docs/operating_system_filtering.md
Normal file
65
docs/operating_system_filtering.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# **Understanding the OS Filtering Mechanism**
|
||||
|
||||
## **Overview**
|
||||
This function filters devices based on their **reachability** and an optional **OS category filter**. It supports:
|
||||
|
||||
- **Broad OS categories** (e.g., `"Linux"` includes all OS versions under `"Linux"`)
|
||||
- **Specific OS categories** (e.g., `"Debian"` only includes OS versions under `"Linux" -> "Debian"`)
|
||||
- **Single category selection** (Only `target_os="Linux"` OR `target_os="Debian"` is used, never both at once)
|
||||
|
||||
---
|
||||
|
||||
## **How It Works (Simplified)**
|
||||
|
||||
### **1. OS Category Expansion**
|
||||
The function first expands the `target_os` category by retrieving all valid OS names under it.
|
||||
|
||||
#### **Example OS Category Structure:**
|
||||
```json
|
||||
{
|
||||
"Linux": {
|
||||
"Debian": [
|
||||
"Debian GNU/Linux 12 (bookworm)",
|
||||
"Debian GNU/Linux 11 (bullseye)"
|
||||
],
|
||||
"Ubuntu": [
|
||||
"Ubuntu 24.04.1 LTS"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### **Expanding Different `target_os` Values:**
|
||||
|
||||
| `target_os` | Expanded OS Versions |
|
||||
|--------------|---------------------------------------------------|
|
||||
| `"Linux"` | `{ "Debian GNU/Linux 12 (bookworm)", "Debian GNU/Linux 11 (bullseye)", "Ubuntu 24.04.1 LTS" }` |
|
||||
| `"Debian"` | `{ "Debian GNU/Linux 12 (bookworm)", "Debian GNU/Linux 11 (bullseye)" }` |
|
||||
|
||||
---
|
||||
|
||||
### **2. Device Filtering**
|
||||
Once the function has the allowed OS versions, it checks each device:
|
||||
|
||||
#### **Example Device List:**
|
||||
```json
|
||||
[
|
||||
{"device_id": "A1", "device_os": "Debian GNU/Linux 12 (bookworm)", "reachable": true},
|
||||
{"device_id": "A2", "device_os": "Ubuntu 24.04.1 LTS", "reachable": true},
|
||||
{"device_id": "A3", "device_os": "Windows 11", "reachable": true},
|
||||
{"device_id": "A4", "device_os": "Debian GNU/Linux 11 (bullseye)", "reachable": false}
|
||||
]
|
||||
```
|
||||
|
||||
#### **Filtering Behavior:**
|
||||
| Device ID | Device OS | Reachable | Matches `target_os="Linux"` | Matches `target_os="Debian"` |
|
||||
|-----------|----------------------------------|-----------|-------------------------------|-------------------------------|
|
||||
| A1 | Debian GNU/Linux 12 (bookworm) | ✅ | ✅ | ✅ |
|
||||
| A2 | Ubuntu 24.04.1 LTS | ✅ | ✅ | ❌ |
|
||||
| A3 | Windows 11 | ✅ | ❌ | ❌ |
|
||||
| A4 | Debian GNU/Linux 11 (bullseye) | ❌ | ❌ (Unreachable) | ❌ (Unreachable) |
|
||||
|
||||
#### **Final Output:**
|
||||
- If `target_os="Linux"`: `["A1", "A2"]`
|
||||
- If `target_os="Debian"`: `["A1"]`
|
||||
- If `target_os=None` or `target_os` is undefined: `["A1", "A2", "A3"]`
|
||||
19
examples/all_variable_usage_example.yaml
Normal file
19
examples/all_variable_usage_example.yaml
Normal file
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: Ping Multiple Points
|
||||
group: "Kubernetes"
|
||||
#target_os: "Debian"
|
||||
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 }}"
|
||||
32
examples/linux/aggregate_example.yaml
Normal file
32
examples/linux/aggregate_example.yaml
Normal file
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: Echo some text in the terminal of the device
|
||||
group: "Development"
|
||||
target_os: "Linux" # <----
|
||||
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"
|
||||
13
examples/linux/apt_update_example.yaml
Normal file
13
examples/linux/apt_update_example.yaml
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: Refresh the apt cache
|
||||
device: "<Device-Name>"
|
||||
#target_os: "Linux"
|
||||
variables:
|
||||
- name: package_manager
|
||||
value: "apt"
|
||||
tasks:
|
||||
- name: refresh the {{ package_manager }} cache
|
||||
command: "{{ package_manager }} update"
|
||||
|
||||
- name: display available upgrades with {{ package_manager }}
|
||||
command: "{{ package_manager }} list --upgradable"
|
||||
19
examples/linux/apt_upgrade_example.yaml
Normal file
19
examples/linux/apt_upgrade_example.yaml
Normal file
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: Refresh the apt cache
|
||||
group: "Dev"
|
||||
#target_os: "Linux"
|
||||
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"
|
||||
8
examples/linux/disk_info.yaml
Normal file
8
examples/linux/disk_info.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
name: Use DF to get drive information in JSON.
|
||||
group: Systemec Development
|
||||
target_os: "Linux"
|
||||
tasks:
|
||||
- name: Get disk-info with df returning JSON.
|
||||
command: >
|
||||
df -Th -x overlay -x tmpfs -x devtmpfs | awk 'NR>1 {printf "%s{\"size\":\"%s\",\"used\":\"%s\",\"available\":\"%s\",\"mount_point\":\"%s\",\"type\":\"%s\"}", (NR==2?"[":","), $3, $4, $5, $7, $2} END {print "]"}'
|
||||
10
examples/linux/echo_example.yaml
Normal file
10
examples/linux/echo_example.yaml
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Echo a string to the terminal through the meshbook example.
|
||||
group: "Development"
|
||||
target_os: "Linux"
|
||||
variables:
|
||||
- name: file
|
||||
value: "/etc/os-release"
|
||||
tasks:
|
||||
- name: Echo!
|
||||
command: "echo $(cat {{ file }})"
|
||||
11
examples/windows/get_sys_info.yaml
Normal file
11
examples/windows/get_sys_info.yaml
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
name: Echo a string to the terminal through the meshbook example.
|
||||
group: "Endpoint"
|
||||
target_os: "Windows"
|
||||
powershell: True
|
||||
#variables:
|
||||
# - name: file
|
||||
# value: "/etc/os-release"
|
||||
tasks:
|
||||
- name: Echo!
|
||||
command: "Get-ComputerInfo | Select-Object CsName, OsName, OsArchitecture, OsLastBootUpTime | Write-Output"
|
||||
8
examples/windows/get_update_info.yaml
Normal file
8
examples/windows/get_update_info.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
name: Echo a string to the terminal through the meshbook example.
|
||||
group: "Endpoint"
|
||||
target_os: "Windows"
|
||||
powershell: True
|
||||
tasks:
|
||||
- name: Get some update information
|
||||
command: "Get-HotFix | Select-Object PSComputerName, HotFixID, InstalledOn"
|
||||
16
examples/windows/multiline_example.yaml
Normal file
16
examples/windows/multiline_example.yaml
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: Echo a string to the terminal through the meshbook example.
|
||||
group: "Endpoint"
|
||||
target_os: "Windows"
|
||||
powershell: True
|
||||
#variables:
|
||||
# - name: file
|
||||
# value: "/etc/os-release"
|
||||
tasks:
|
||||
- name: Echo!
|
||||
command: >
|
||||
$systemInfo = Get-ComputerInfo | Select-Object CsName, OsName, OsArchitecture, OsLastBootUpTime;
|
||||
$systemInfo | Format-Table -AutoSize;
|
||||
Write-Output "I like monkeys.";
|
||||
Get-SystemLanguage | Write-Output;
|
||||
Get-ComputerInfo | Format-List;
|
||||
@@ -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:
|
||||
411
meshbook.py
Normal file
411
meshbook.py
Normal file
@@ -0,0 +1,411 @@
|
||||
#!/bin/python3
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from base64 import b64encode
|
||||
from colorama import just_fix_windows_console
|
||||
from configparser import ConfigParser
|
||||
import json
|
||||
import meshctrl
|
||||
import os
|
||||
import yaml
|
||||
|
||||
grace_period = 3 # Grace period will last for x (by default 3) second(s).
|
||||
|
||||
'''
|
||||
Script utilities are handled in the following section.
|
||||
'''
|
||||
|
||||
class ScriptEndTrigger(Exception):
|
||||
pass
|
||||
|
||||
class text_color:
|
||||
black = "\033[30m"
|
||||
red = "\033[31m"
|
||||
green = "\033[32m"
|
||||
yellow = "\033[33m"
|
||||
blue = "\033[34m"
|
||||
magenta = "\033[35m"
|
||||
cyan = "\033[36m"
|
||||
white = "\033[37m"
|
||||
italic = "\x1B[3m"
|
||||
reset = "\x1B[0m"
|
||||
|
||||
def console(message: str, final: bool=False):
|
||||
'''
|
||||
Helper function for terminal output, with a couple variables for the silent flag. Also clears terminal color each time.
|
||||
'''
|
||||
if final:
|
||||
print(message) # Assuming final message, there is no need for clearing.
|
||||
elif not args.silent:
|
||||
print(message + text_color.reset)
|
||||
|
||||
async def load_config(segment: str = 'meshcentral-account') -> dict:
|
||||
'''
|
||||
Function that loads the segment from the config.conf (by default) file and returns the it in a dict.
|
||||
'''
|
||||
|
||||
conf_file = args.conf
|
||||
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:
|
||||
'''
|
||||
Use the libmeshctrl library to initiate a Secure Websocket (wss) connection to the MeshCentral instance.
|
||||
'''
|
||||
|
||||
session = meshctrl.Session(
|
||||
credentials['hostname'],
|
||||
user=credentials['username'],
|
||||
password=credentials['password']
|
||||
)
|
||||
await session.initialized.wait()
|
||||
return session
|
||||
|
||||
async def translate_nodeid_to_name(target_id: str, group_list: dict) -> str:
|
||||
'''
|
||||
Simple function that looks up nodeid to the human-readable name if existent - otherwise return None.
|
||||
'''
|
||||
|
||||
for group in group_list:
|
||||
for device in group_list[group]:
|
||||
if device["device_id"] == target_id:
|
||||
return device["device_name"]
|
||||
return None
|
||||
|
||||
'''
|
||||
Creation and compilation happends in the following section, where the yaml gets read in, and edited accordingly.
|
||||
'''
|
||||
|
||||
async def compile_book(meshbook_file: dict) -> dict:
|
||||
'''
|
||||
Simple function that opens the file and replaces placeholders through the next function. After that just return it.
|
||||
'''
|
||||
|
||||
meshbook = open(meshbook_file, 'r')
|
||||
meshbook = await replace_placeholders(yaml.safe_load(meshbook))
|
||||
return meshbook
|
||||
|
||||
async def replace_placeholders(meshbook: dict) -> dict:
|
||||
'''
|
||||
Replace the placeholders in both name and command fields of the tasks. According to the variables defined in the variables list.
|
||||
'''
|
||||
|
||||
variables = {}
|
||||
if "variables" in meshbook and isinstance(meshbook["variables"], list):
|
||||
for var in meshbook["variables"]:
|
||||
var_name = var["name"]
|
||||
var_value = var["value"]
|
||||
variables[var_name] = var_value
|
||||
else:
|
||||
return meshbook
|
||||
|
||||
for task in meshbook.get("tasks", []):
|
||||
task_name = task.get("name")
|
||||
for var_name, var_value in variables.items():
|
||||
placeholder = f"{{{{ {var_name} }}}}"
|
||||
task_name = task_name.replace(placeholder, var_value)
|
||||
task["name"] = task_name
|
||||
|
||||
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 meshbook
|
||||
|
||||
'''
|
||||
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:
|
||||
'''
|
||||
Function that retrieves the devices from MeshCentral and compiles it into a efficient list.
|
||||
'''
|
||||
|
||||
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 filter_targets(devices: list[dict], os_categories: dict, target_os: str = None, target_tag: str = None) -> list[str]:
|
||||
'''
|
||||
Filters devices based on reachability and optional OS criteria, supporting nested OS categories.
|
||||
'''
|
||||
|
||||
valid_devices = []
|
||||
|
||||
def get_os_variants(category: str, os_map: dict) -> set:
|
||||
'''
|
||||
Extracts all OS names under a given category if it exists.
|
||||
'''
|
||||
|
||||
for key, value in os_map.items():
|
||||
if key == category:
|
||||
if isinstance(value, dict): # Expand nested categories
|
||||
os_set = set()
|
||||
for subcat in value:
|
||||
os_set.update(get_os_variants(subcat, value))
|
||||
return os_set
|
||||
elif isinstance(value, list): # Direct OS list
|
||||
return set(value)
|
||||
return set()
|
||||
|
||||
allowed_os = set()
|
||||
|
||||
# Identify correct OS filtering scope
|
||||
for key in os_categories:
|
||||
if key == target_os:
|
||||
allowed_os = get_os_variants(target_os, os_categories)
|
||||
break # Stop searching once a match is found
|
||||
|
||||
if isinstance(os_categories[key], dict) and target_os in os_categories[key]:
|
||||
allowed_os = get_os_variants(target_os, os_categories[key])
|
||||
break # Stop searching once a match is found
|
||||
|
||||
# Filter out unwanted or unreachable devices.
|
||||
for device in devices:
|
||||
if not device["reachable"]:
|
||||
continue # Skip unreachable devices.
|
||||
|
||||
print(target_tag)
|
||||
print(device["device_tags"])
|
||||
if target_tag and target_tag not in device["device_tags"]:
|
||||
continue
|
||||
|
||||
if device["device_os"] not in allowed_os:
|
||||
continue
|
||||
|
||||
valid_devices.append(device["device_id"])
|
||||
|
||||
return valid_devices
|
||||
|
||||
async def gather_targets(meshbook: dict, group_list: dict[str, list[dict]], os_categories: dict) -> list[str]:
|
||||
'''
|
||||
Finds target devices based on meshbook criteria (device or group).
|
||||
'''
|
||||
|
||||
target_list = []
|
||||
target_os = meshbook.get("target_os")
|
||||
target_tag = meshbook.get("target_tag")
|
||||
|
||||
async def process_device_or_group(pseudo_target, group_list, os_categories, target_os) -> list[str]:
|
||||
'''
|
||||
Helper function to process devices or groups.
|
||||
'''
|
||||
|
||||
matched_devices = []
|
||||
for group in group_list:
|
||||
for device in group_list[group]:
|
||||
if device["device_name"] == pseudo_target:
|
||||
matched_devices.append(device)
|
||||
|
||||
if matched_devices:
|
||||
return await filter_targets(matched_devices, os_categories, target_os, target_tag)
|
||||
return []
|
||||
|
||||
match meshbook:
|
||||
case {"device": pseudo_target}: # Single device target
|
||||
if isinstance(pseudo_target, str):
|
||||
matched_devices = await process_device_or_group(pseudo_target, group_list, os_categories, target_os)
|
||||
target_list.extend(matched_devices)
|
||||
else:
|
||||
console(text_color.yellow + "Please use devices (Notice the 'S') for multiple devices.", True)
|
||||
|
||||
case {"devices": pseudo_target}: # List of devices
|
||||
if isinstance(pseudo_target, list):
|
||||
for sub_pseudo_device in pseudo_target:
|
||||
matched_devices = await process_device_or_group(sub_pseudo_device, group_list, os_categories, target_os)
|
||||
target_list.extend(matched_devices)
|
||||
|
||||
else:
|
||||
console(text_color.yellow + "The 'devices' method is being used, but only one string is given. Did you mean 'device'?", True)
|
||||
|
||||
case {"group": pseudo_target}: # Single group target
|
||||
if isinstance(pseudo_target, str) and pseudo_target in group_list:
|
||||
matched_devices = await filter_targets(group_list[pseudo_target], os_categories, target_os, target_tag)
|
||||
target_list.extend(matched_devices)
|
||||
elif pseudo_target not in group_list:
|
||||
console(text_color.yellow + "Targeted group not found on the MeshCentral server.", True)
|
||||
else:
|
||||
console(text_color.yellow + "Please use groups (Notice the 'S') for multiple groups.", True)
|
||||
|
||||
case {"groups": pseudo_target}: # List of groups
|
||||
if isinstance(pseudo_target, list):
|
||||
for sub_pseudo_target in pseudo_target:
|
||||
if sub_pseudo_target in group_list:
|
||||
matched_devices = await filter_targets(group_list[sub_pseudo_target], os_categories, target_os, target_tag)
|
||||
target_list.extend(matched_devices)
|
||||
if pseudo_target.lower() == "all":
|
||||
for group in group_list:
|
||||
matched_devices = await filter_targets(group_list[group], os_categories, target_os, target_tag)
|
||||
target_list.extend(matched_devices)
|
||||
else:
|
||||
console(text_color.yellow + "The 'groups' method is being used, but only one string is given. Did you mean 'group'?", True)
|
||||
|
||||
return target_list
|
||||
|
||||
async def execute_meshbook(session: meshctrl.Session, targets: dict, meshbook: dict, group_list: dict) -> None:
|
||||
'''
|
||||
Actual function that handles meshbook execution, also responsible for formatting the resulting JSON.
|
||||
'''
|
||||
|
||||
responses_list = {}
|
||||
round = 1
|
||||
|
||||
for task in meshbook["tasks"]:
|
||||
console(text_color.green + str(round) + ". Running: " + task["name"])
|
||||
if "powershell" in meshbook and meshbook["powershell"]:
|
||||
response = await session.run_command(nodeids=targets, command=task["command"],powershell=True,ignore_output=False,timeout=900)
|
||||
else:
|
||||
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_nodeid_to_name(device, group_list)
|
||||
task_batch.append(response[device])
|
||||
|
||||
responses_list["Task " + str(round)] = {
|
||||
"task_name": task["name"],
|
||||
"data": task_batch
|
||||
}
|
||||
round += 1
|
||||
|
||||
console(text_color.reset + ("-" * 40))
|
||||
if args.indent:
|
||||
console((json.dumps(responses_list,indent=4)), True)
|
||||
|
||||
else:
|
||||
console(json.dumps(responses_list), True)
|
||||
|
||||
async def main():
|
||||
just_fix_windows_console()
|
||||
'''
|
||||
Main function where the program starts. Place from which all comands originate (eventually).
|
||||
'''
|
||||
|
||||
parser = argparse.ArgumentParser(description="Process command-line arguments")
|
||||
parser.add_argument("-mb", "--meshbook", type=str, help="Path to the meshbook yaml file.", required=True)
|
||||
|
||||
parser.add_argument("-oc", "--oscategories", type=str, help="Path to the Operating System categories JSON file.", required=False, default="./os_categories.json")
|
||||
parser.add_argument("--conf", type=str, help="Path for the API configuration file (default: ./config.conf).", required=False, default="./config.conf")
|
||||
parser.add_argument("--nograce", action="store_true", help="Disable the grace 3 seconds before running the meshbook.", required=False)
|
||||
parser.add_argument("-i", "--indent", action="store_true", help="Use an JSON indentation of 4 when this flag is passed.", required=False)
|
||||
parser.add_argument("-s", "--silent", action="store_true", help="Suppress terminal output", required=False)
|
||||
|
||||
global args
|
||||
args = parser.parse_args()
|
||||
local_categories_file = "./os_categories.json"
|
||||
|
||||
try:
|
||||
with open(local_categories_file, "r") as file:
|
||||
os_categories = json.load(file)
|
||||
|
||||
credentials, meshbook = await asyncio.gather(
|
||||
(load_config()),
|
||||
(compile_book(args.meshbook))
|
||||
)
|
||||
|
||||
'''
|
||||
The following section mainly displays used variables and first steps of the program to the console.
|
||||
'''
|
||||
|
||||
console(text_color.reset + ("-" * 40))
|
||||
console("meshbook: " + text_color.yellow + args.meshbook)
|
||||
console("Operating System Categorisation file: " + text_color.yellow + args.oscategories)
|
||||
console("Configuration file: " + text_color.yellow + args.conf)
|
||||
if "target_os" in meshbook:
|
||||
console("Target Operating System category given: " + text_color.yellow + meshbook["target_os"])
|
||||
else:
|
||||
console("Target Operating System category given: " + text_color.yellow + "All")
|
||||
|
||||
if "device" in meshbook:
|
||||
console("Target device: " + text_color.yellow + str(meshbook["device"]))
|
||||
|
||||
elif "group" in meshbook:
|
||||
console("Target group: " + text_color.yellow + str(meshbook["group"]))
|
||||
|
||||
console("Grace: " + text_color.yellow + str((not args.nograce))) # Negation of bool for correct explanation
|
||||
console("Silent: " + text_color.yellow + "False") # Can be pre-defined because if silent flag was passed then none of this would be printed.
|
||||
|
||||
session = await init_connection(credentials)
|
||||
console(text_color.reset + ("-" * 40))
|
||||
console(text_color.italic + "Trying to load the MeshCentral account credential file...")
|
||||
console(text_color.italic + "Trying to load the meshbook yaml file and compile it into something workable...")
|
||||
console(text_color.italic + "Trying to load the Operating System categorisation JSON file...")
|
||||
console(text_color.italic + "Connecting to MeshCentral and establish a session using variables from previous credential file.")
|
||||
console(text_color.italic + "Generating group list with nodes and reference the targets from that.")
|
||||
|
||||
'''
|
||||
End of the main information displaying section.
|
||||
'''
|
||||
|
||||
group_list = await compile_group_list(session)
|
||||
targets_list = await gather_targets(meshbook, group_list, os_categories)
|
||||
|
||||
if len(targets_list) == 0:
|
||||
console(text_color.red + "No targets found or targets unreachable, quitting.", True)
|
||||
console(text_color.reset + ("-" * 40), True)
|
||||
|
||||
else:
|
||||
console(text_color.reset + ("-" * 40))
|
||||
|
||||
match meshbook:
|
||||
case {"group": candidate_target_name}:
|
||||
target_name = candidate_target_name
|
||||
|
||||
case {"groups": candidate_target_name}:
|
||||
target_name = str(candidate_target_name)
|
||||
|
||||
case {"device": candidate_target_name}:
|
||||
target_name = candidate_target_name
|
||||
|
||||
case {"devices": candidate_target_name}:
|
||||
target_name = str(candidate_target_name)
|
||||
|
||||
console(text_color.yellow + "Executing meshbook on the target(s): " + text_color.green + target_name + ".")
|
||||
|
||||
if not args.nograce:
|
||||
console(text_color.yellow + "Initiating grace-period...")
|
||||
|
||||
for x in range(grace_period):
|
||||
console(text_color.yellow + "{}...".format(x+1)) # Countdown!
|
||||
await asyncio.sleep(1)
|
||||
|
||||
console(text_color.reset + ("-" * 40))
|
||||
print(json.dumps(targets_list,indent=4))
|
||||
#await execute_meshbook(session, targets_list, meshbook, group_list)
|
||||
|
||||
await session.close()
|
||||
|
||||
except OSError as message:
|
||||
console(text_color.red + 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 +0,0 @@
|
||||
asyncio==3.4.3
|
||||
configparser==7.1.0
|
||||
pyyaml==6.0.2
|
||||
websockets==14.1
|
||||
25
os_categories.json
Normal file
25
os_categories.json
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
{
|
||||
"Linux": {
|
||||
"Debian": [
|
||||
"Debian GNU/Linux 12 (bookworm)",
|
||||
"Debian GNU/Linux 11 (bullseye)"
|
||||
],
|
||||
"Ubuntu": [
|
||||
"Ubuntu 24.04.1 LTS",
|
||||
"Ubuntu 22.04.5 LTS",
|
||||
"Ubuntu 20.04.6 LTS"
|
||||
]
|
||||
},
|
||||
"MacOS": {
|
||||
"Sequoia": [
|
||||
"macOS 15.0.1"
|
||||
]
|
||||
},
|
||||
"Windows": {
|
||||
"11": [
|
||||
"Microsoft Windows 11 Home - 24H2/26100",
|
||||
"Microsoft Windows 11 Pro - 24H2/26100"
|
||||
]
|
||||
}
|
||||
}
|
||||
3
requirements.txt
Normal file
3
requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
colorama==0.4.6
|
||||
pyyaml==6.0.2
|
||||
libmeshctrl==1.1.2
|
||||
@@ -1,4 +0,0 @@
|
||||
[meshcentral-service]
|
||||
websocket_url =
|
||||
username =
|
||||
password =
|
||||
4
templates/config.conf
Normal file
4
templates/config.conf
Normal file
@@ -0,0 +1,4 @@
|
||||
[meshcentral-account]
|
||||
hostname =
|
||||
username =
|
||||
password =
|
||||
Reference in New Issue
Block a user