diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index c5fc01f..9a83736 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -23,6 +23,8 @@ jobs:
path: |
dist/${{ matrix.runtime }}/agent.exe
config.example.json
+ config.listen.example.json
scripts/install.ps1
scripts/uninstall.ps1
+ scripts/gpo-startup.ps1
diff --git a/NetBoxAgent.csproj b/NetBoxAgent.csproj
index 7d8ada3..649bf63 100644
--- a/NetBoxAgent.csproj
+++ b/NetBoxAgent.csproj
@@ -6,7 +6,7 @@
enable
agent
NetBoxWindowsAgent
- 0.1.0
+ 0.2.0
diff --git a/README.md b/README.md
index 7170f3d..46be72a 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# NetBox Client Agent for Windows
-Inventories a Windows PC automatically in NetBox and in the
+Inventories a Windows PC for NetBox and the
[netbox-inventory](https://github.com/ArnesSI/netbox-inventory) plugin. The
result is a single, self-contained `agent.exe`; the client does not need .NET
installed.
@@ -10,11 +10,27 @@ installed.
| **Type** | Command-line agent (.NET 8) |
| **Platform** | Windows (x64, ARM64) |
| **NetBox** | `4.2` or newer recommended |
+| **Deployment** | Intune (Win32 app) or Group Policy (startup script), fully unattended |
| **Repository** | |
+## Modes
+
+The agent runs in one of three modes, set by `mode` in `config.json`:
+
+| Mode | What it does | Needs on the client |
+|---|---|---|
+| `netbox` (default) | Writes the PC directly to NetBox once a day | NetBox URL and API token |
+| `listen` | Serves the inventory on a TCP port; the **NetBox Synchronizer** desktop app scans IP ranges and transfers the PCs to NetBox after a preview | Only a shared scan key – **no NetBox access** |
+| `both` | Both of the above | Both |
+
+The agent is invisible to users: it runs as SYSTEM in the background (session
+0), shows no window and causes no prompts. The installer creates the firewall
+rule before the listener starts, so Windows never asks users to allow network
+access.
+
## Features
-After the first run, the agent creates or updates:
+In mode `netbox`, the agent creates or updates after the first run:
- a `DCIM > Device` for the Windows PC,
- a linked inventory asset,
@@ -30,8 +46,19 @@ the existing objects. No NetBox objects are ever deleted.
> from 4.2 on. Modules are meant for replaceable hardware in NetBox; for PC
> inventory, CPU, memory and disks are deliberately mapped onto this model.
+In mode `listen`, the NetBox Synchronizer (page *Windows-Clients*, target
+mode *NetBox-Agent*) scans IP ranges, lists every PC that answers and
+transfers the selected ones with model, serial number, operating system,
+interfaces, MAC and IP addresses – the same way as its agentless WinRM scan.
+Disks, memory modules and the software list are shown in the app as well.
+
## Requirements
+Building requires the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)
+or newer.
+
+For mode `netbox`:
+
1. `netbox-inventory` is installed.
2. A device role with the slug `windows-client` exists.
3. The site and location named in the configuration exist, if used.
@@ -45,8 +72,8 @@ The agent deliberately does not create sites or device roles. NetBox requires a
site for every device; a location is optional. Manufacturers, device types and
detected hardware types are created as needed.
-Building requires the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)
-or newer.
+For mode `listen`: the NetBox Synchronizer desktop app and TCP access from the
+admin PC to the clients on `listen_port` (default 8731).
## Installation
@@ -63,20 +90,34 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
-Runtime win-x64
```
-The result is `dist\win-x64\agent.exe`.
+The result is `dist\win-x64\agent.exe` (`-Runtime win-arm64` for ARM devices).
### 2. Create the configuration
+Mode `netbox`:
+
```powershell
Copy-Item .\config.example.json .\dist\win-x64\config.json
notepad .\dist\win-x64\config.json
```
+Mode `listen`: in the NetBox Synchronizer open *Windows-Clients*, choose
+*NetBox-Agent (Netzwerk-Scan)*, create a key and click
+*Agent-Konfiguration speichern …*. This writes a ready `config.json`
+(see also `config.listen.example.json`).
+
See [Configuration](#configuration) for all options.
-### 3. Test the connection
+### 3. Test
-The dry run reads hardware and NetBox but deliberately writes nothing:
+Show what the agent collects (any mode):
+
+```powershell
+.\dist\win-x64\agent.exe --config .\dist\win-x64\config.json --print
+```
+
+Mode `netbox` – the dry run reads hardware and NetBox but deliberately writes
+nothing:
```powershell
.\dist\win-x64\agent.exe `
@@ -84,14 +125,25 @@ The dry run reads hardware and NetBox but deliberately writes nothing:
--dry-run
```
-Expected output (the agent's messages are in German):
+Expected output:
```text
-Erfasst: CLIENT01, LENOVO 21MW, S/N ABC123
-Dry-Run erfolgreich; keine Änderungen geschrieben.
+Collected: CLIENT01, LENOVO 21MW, S/N ABC123
+Dry run successful; nothing was written.
```
-### 4. First real synchronisation
+Mode `listen` – serve in the foreground (Ctrl+C stops) and scan this PC from
+the NetBox Synchronizer:
+
+```powershell
+.\dist\win-x64\agent.exe --config .\dist\win-x64\config.json --serve
+```
+
+When started by hand like this, Windows Firewall may ask once whether
+`agent.exe` may accept connections – this only happens in manual tests. An
+installed agent has its firewall rule and never asks.
+
+### 4. First real synchronisation (mode `netbox`)
```powershell
.\dist\win-x64\agent.exe `
@@ -101,7 +153,7 @@ Dry-Run erfolgreich; keine Änderungen geschrieben.
Expected output:
```text
-Synchronisiert: Device #123, Asset #456
+Synchronized: device #123, asset #456
```
### 5. Install permanently
@@ -119,9 +171,21 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
The script:
- copies the executable and configuration to `C:\Program Files\NetBox Windows Agent`,
-- restricts access to the API token to SYSTEM and local administrators,
-- creates the daily scheduled task `NetBox Windows Agent`,
-- starts the first synchronisation immediately.
+- restricts access to the API token and scan key to SYSTEM and local administrators,
+- mode `netbox`/`both`: creates the daily scheduled task `NetBox Windows Agent`
+ and starts the first synchronisation immediately,
+- mode `listen`/`both`: adds the inbound firewall rule `NetBox Windows Agent`
+ for `listen_port` (domain and private profile, limited to
+ `allowed_networks`), then creates and starts the scheduled task
+ `NetBox Windows Agent Listener` (runs as SYSTEM at startup, restarted after
+ failures),
+- removes tasks and the firewall rule that a changed mode no longer needs,
+- can be run again at any time to update the agent or its configuration.
+
+The installation state only depends on the installed executable, configuration
+and scheduled tasks. A temporary NetBox or network error during the first
+synchronisation does not undo the installation; the scheduled task retries the
+synchronisation later.
## Uninstall
@@ -132,12 +196,15 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
-File .\scripts\uninstall.ps1
```
+This removes both scheduled tasks, the firewall rule and the install folder.
+
## Configuration
-Minimal example:
+### Mode `netbox`
```json
{
+ "mode": "netbox",
"netbox_url": "https://netbox.example.com",
"api_token": "YOUR_NETBOX_TOKEN",
"region": "emea",
@@ -155,9 +222,47 @@ Minimal example:
}
```
-`site` must be the slug of an existing NetBox site, since NetBox requires a site
-for every device. `location` is optional and may be removed or set to `null`.
-`region` narrows the site lookup.
+`mode` may be omitted; `netbox` is the default. `site` must be the slug of an
+existing NetBox site, since NetBox requires a site for every device. `location`
+is optional and may be removed or set to `null`. `region` narrows the site
+lookup.
+
+### Mode `listen`
+
+```json
+{
+ "mode": "listen",
+ "listen_port": 8731,
+ "scan_key": "the key from the NetBox Synchronizer",
+ "allowed_networks": ["10.0.0.0/24"],
+ "inventory_cache_seconds": 300,
+ "collect_software": true,
+ "max_software_entries": 250
+}
+```
+
+| Setting | Meaning |
+|---|---|
+| `listen_port` | TCP port of the agent (default 8731) |
+| `scan_key` | Shared secret of all agents of one customer (at least 16 characters); only a NetBox Synchronizer with the same key can read the inventory |
+| `allowed_networks` | Optional networks in CIDR notation that may connect, e.g. the admin network. Empty = any address. Used for the firewall rule and checked by the agent |
+| `inventory_cache_seconds` | The inventory is collected on request and reused for this time |
+
+For mode `both`, combine the settings of both modes.
+
+### Security of the listen mode
+
+- `GET /v1/info` answers without authentication, with the agent name and
+ version only.
+- `GET /v1/inventory` needs an HMAC-SHA256 signature (key derived from
+ `scan_key`) over a random nonce and the current time. Requests older than five
+ minutes and repeated nonces are rejected.
+- The inventory is returned encrypted with AES-256-GCM (a separate key derived
+ from `scan_key`), so serial numbers and software lists never cross the network
+ in clear text – without needing TLS certificates.
+- The clocks of client and admin PC may differ by at most five minutes (domain
+ time synchronisation is enough).
+- The agent only reads data; it accepts no commands.
### Self-signed certificate
@@ -200,6 +305,10 @@ Custom fields are not required by default. To use them, create them for
## Usage
+Both distribution methods are fully unattended: the installer runs as SYSTEM,
+needs no user interaction and no administrator on the client, and the agent
+stays invisible to users.
+
### Distribution with Intune
Package these four files together as a Win32 app (`.intunewin`):
@@ -223,23 +332,82 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\uninstall.ps1
Install behavior:
System
+Device restart behavior:
+No specific action
+
Detection rule (rule type "File"):
Path: C:\Program Files\NetBox Windows Agent
File or folder: agent.exe
-Detection method: File or folder exists
+Detection method: String (version)
+Operator: Greater than or equal to
+Value: 0.2.0 (the version of agent.exe, see agent.exe --version)
Associated with a 32-bit app on 64-bit clients: No
```
+Assign the app as **Required** to a device group so it installs without user
+action. The version rule lets Intune update clients with an older agent. After
+changes to `agent.exe`, `config.json` or the installation scripts, rebuild the
+`.intunewin` package and upload it again under
+**App > Properties > App package file** – a change in the local repository does
+not update a package that was already uploaded. A changed `config.json` alone
+(for example a new scan key) is not detected by the version rule; publish it as
+a new app that supersedes the old one, or use Group Policy.
+
+### Distribution with Group Policy
+
+1. Create a folder on a share that the group **Domain Computers** can read, for
+ example `\\fileserver\NetBoxAgent$`, and copy these files into it:
+
+ ```text
+ agent.exe
+ config.json
+ install.ps1
+ uninstall.ps1
+ gpo-startup.ps1
+ ```
+
+2. Create a GPO linked to the OU of the computers:
+ **Computer Configuration > Policies > Windows Settings > Scripts
+ (Startup/Shutdown) > Startup > PowerShell Scripts > Add** – script name
+ `\\fileserver\NetBoxAgent$\gpo-startup.ps1`, no parameters.
+
+3. Make sure the share is reachable at startup:
+ **Computer Configuration > Policies > Administrative Templates > System >
+ Logon > Always wait for the network at computer startup and logon** =
+ *Enabled*.
+
+At every startup the script compares `agent.exe` and `config.json` on the share
+with the installed version. If nothing changed, it does nothing; if a file
+changed or the agent is missing, it runs `install.ps1` from the share. To update
+all computers, replace the files on the share. The script logs to
+`C:\ProgramData\NetBox Windows Agent\gpo-startup.log`.
+
+To remove the agent from all computers of the GPO, add the script parameter
+`-Uninstall`.
+
+> `config.json` on the share is readable by all domain computers. In mode
+> `listen` it contains the scan key, in mode `netbox` the NetBox API token – use
+> a token with only the permissions listed above.
+
### Troubleshooting
-**`agent.exe fehlt im Quellverzeichnis`** (agent.exe missing in source
-directory) — `SourceDirectory` must be the folder that contains both
-`agent.exe` and `config.json`:
+**`agent.exe is missing in the source directory`** — `SourceDirectory` must be
+the folder that contains both `agent.exe` and `config.json`:
```powershell
-SourceDirectory .\dist\win-x64
```
+**The NetBox Synchronizer does not find an agent** — check that the task
+`NetBox Windows Agent Listener` is running, test the port from the admin PC with
+`Test-NetConnection -Port 8731`, check firewalls between the networks
+and that the admin PC is inside `allowed_networks`. The firewall rule applies to
+the *Domain* and *Private* network profiles, not to *Public*.
+
+**"Agent-Schlüssel stimmt nicht" in the NetBox Synchronizer** (wrong key) — the
+key in the app and `scan_key` on the client differ; distribute the
+configuration again.
+
**`RemoteCertificateNameMismatch` or `RemoteCertificateChainErrors`** — set
`allow_insecure_tls` to `true` for testing. Permanently, install the correct
internal CA and use a certificate name that matches the URL.
@@ -265,9 +433,8 @@ Enter the slug of an existing site in `config.json`:
detection rule, the `Path` field must contain only the folder. `agent.exe`
belongs in the separate `File or folder` field.
-**`400 Bad Request`** — the full response after `FEHLER:` (error) names the
-field NetBox rejected. Often the configured device role, site or location is
-missing.
+**`400 Bad Request`** — the full response after `ERROR:` names the field NetBox
+rejected. Often the configured device role, site or location is missing.
## Development
diff --git a/config.example.json b/config.example.json
index 2d8687f..1f986a3 100644
--- a/config.example.json
+++ b/config.example.json
@@ -1,4 +1,5 @@
{
+ "mode": "netbox",
"netbox_url": "https://netbox.example.com",
"api_token": "CHANGE_ME",
"region": "emea",
diff --git a/config.listen.example.json b/config.listen.example.json
new file mode 100644
index 0000000..39579c9
--- /dev/null
+++ b/config.listen.example.json
@@ -0,0 +1,9 @@
+{
+ "mode": "listen",
+ "listen_port": 8731,
+ "scan_key": "CHANGE_ME_TO_THE_KEY_FROM_THE_NETBOX_SYNCHRONIZER",
+ "allowed_networks": ["10.0.0.0/24"],
+ "inventory_cache_seconds": 300,
+ "collect_software": true,
+ "max_software_entries": 250
+}
diff --git a/scripts/gpo-startup.ps1 b/scripts/gpo-startup.ps1
new file mode 100644
index 0000000..a4aeb0d
--- /dev/null
+++ b/scripts/gpo-startup.ps1
@@ -0,0 +1,62 @@
+<#
+.SYNOPSIS
+ Group Policy computer startup script: installs or updates the NetBox Windows Agent from a share.
+
+.DESCRIPTION
+ Put agent.exe, config.json, install.ps1 and this script into one folder on a share that
+ "Domain Computers" can read, e.g. \\fileserver\NetBoxAgent$ or \\domain\NETLOGON\NetBoxAgent,
+ and add this script as a PowerShell startup script:
+ Computer Configuration > Policies > Windows Settings > Scripts (Startup/Shutdown) > Startup
+ > PowerShell Scripts > \\fileserver\NetBoxAgent$\gpo-startup.ps1
+ It runs as SYSTEM at every startup. When agent.exe and config.json on the share are unchanged and
+ the agent is installed, it does nothing. Otherwise it runs install.ps1 from the share.
+ Set -Uninstall to remove the agent from all computers of the GPO.
+ A log is written to %ProgramData%\NetBox Windows Agent\gpo-startup.log.
+#>
+param(
+ [string]$SourceDirectory = $PSScriptRoot,
+ [string]$InstallDirectory = "$env:ProgramFiles\NetBox Windows Agent",
+ [switch]$Uninstall
+)
+$ErrorActionPreference = 'Stop'
+$logDirectory = Join-Path $env:ProgramData 'NetBox Windows Agent'
+New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
+$log = Join-Path $logDirectory 'gpo-startup.log'
+function Write-Log([string]$Text) { Add-Content -LiteralPath $log -Value "$(Get-Date -Format s) $Text" -Encoding UTF8 }
+
+try {
+ if ($Uninstall) {
+ if (Test-Path -LiteralPath $InstallDirectory) {
+ & (Join-Path $SourceDirectory 'uninstall.ps1') -InstallDirectory $InstallDirectory
+ Write-Log 'Uninstalled.'
+ }
+ exit 0
+ }
+ $sourceAgent = Join-Path $SourceDirectory 'agent.exe'
+ $sourceConfig = Join-Path $SourceDirectory 'config.json'
+ if (-not (Test-Path -LiteralPath $sourceAgent) -or -not (Test-Path -LiteralPath $sourceConfig)) {
+ throw "agent.exe or config.json not found in $SourceDirectory (share not reachable yet?)"
+ }
+ $wanted = @{
+ agent = (Get-FileHash -LiteralPath $sourceAgent -Algorithm SHA256).Hash
+ config = (Get-FileHash -LiteralPath $sourceConfig -Algorithm SHA256).Hash
+ }
+ $stateFile = Join-Path $InstallDirectory 'install-state.json'
+ $current = if (Test-Path -LiteralPath $stateFile) { Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json } else { $null }
+ $installed = (Test-Path -LiteralPath (Join-Path $InstallDirectory 'agent.exe')) -and $current -and
+ $current.agent -eq $wanted.agent -and $current.config -eq $wanted.config
+ $tasksPresent = (Get-ScheduledTask -TaskName 'NetBox Windows Agent*' -ErrorAction SilentlyContinue)
+ if ($installed -and $tasksPresent) {
+ # Up to date – make sure the listener runs (it normally starts by its own startup trigger).
+ if ($current.mode -in 'listen', 'both') { Start-ScheduledTask -TaskName 'NetBox Windows Agent Listener' -ErrorAction SilentlyContinue }
+ exit 0
+ }
+ Write-Log "Installing from $SourceDirectory"
+ $output = & (Join-Path $SourceDirectory 'install.ps1') -SourceDirectory $SourceDirectory -InstallDirectory $InstallDirectory 2>&1
+ $output | ForEach-Object { Write-Log " $_" }
+ Write-Log 'Done.'
+ exit 0
+} catch {
+ Write-Log "ERROR: $($_.Exception.Message)"
+ exit 1
+}
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 9662c88..7ca59af 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -1,3 +1,16 @@
+<#
+.SYNOPSIS
+ Installs or updates the NetBox Windows Agent (Intune Win32 app, GPO startup script or manual).
+
+.DESCRIPTION
+ Copies agent.exe and config.json to the install directory, restricts access to SYSTEM and
+ administrators and sets up what the configured mode needs:
+ netbox daily scheduled task "NetBox Windows Agent" that writes to NetBox
+ listen scheduled task "NetBox Windows Agent Listener" (at startup, restarted on failure) and an
+ inbound firewall rule, so the NetBox Synchronizer desktop app can scan the inventory
+ both both of the above
+ The script is idempotent: running it again updates the files and the tasks.
+#>
param(
[string]$SourceDirectory = $PSScriptRoot,
[string]$InstallDirectory = "$env:ProgramFiles\NetBox Windows Agent",
@@ -5,11 +18,34 @@ param(
[string]$StartTime = '09:00'
)
$ErrorActionPreference = 'Stop'
-if (-not (Test-Path (Join-Path $SourceDirectory 'agent.exe'))) { throw 'agent.exe fehlt im Quellverzeichnis.' }
-if (-not (Test-Path (Join-Path $SourceDirectory 'config.json'))) { throw 'config.json fehlt im Quellverzeichnis.' }
+$syncTask = 'NetBox Windows Agent'
+$listenerTask = 'NetBox Windows Agent Listener'
+$firewallRule = 'NetBoxWindowsAgent'
+
+$sourceAgent = Join-Path $SourceDirectory 'agent.exe'
+$sourceConfig = Join-Path $SourceDirectory 'config.json'
+if (-not (Test-Path -LiteralPath $sourceAgent)) { throw 'agent.exe is missing in the source directory.' }
+if (-not (Test-Path -LiteralPath $sourceConfig)) { throw 'config.json is missing in the source directory.' }
+if ($Schedule -ne 'DAILY') { throw "Only the schedule 'DAILY' is supported." }
+
+$config = Get-Content -LiteralPath $sourceConfig -Raw | ConvertFrom-Json
+$mode = if ($config.mode) { [string]$config.mode } else { 'netbox' }
+if ($mode -notin 'netbox', 'listen', 'both') { throw "config.json: mode must be 'netbox', 'listen' or 'both'." }
+$port = if ($config.listen_port) { [int]$config.listen_port } else { 8731 }
+$allowed = @($config.allowed_networks | Where-Object { $_ })
+$syncs = $mode -in 'netbox', 'both'
+$listens = $mode -in 'listen', 'both'
+
+# A running listener locks agent.exe – stop it before the files are replaced.
+Stop-ScheduledTask -TaskName $listenerTask -ErrorAction SilentlyContinue
+Get-Process -Name agent -ErrorAction SilentlyContinue |
+ Where-Object { $_.Path -and $_.Path.StartsWith($InstallDirectory, [StringComparison]::OrdinalIgnoreCase) } |
+ Stop-Process -Force -ErrorAction SilentlyContinue
+Start-Sleep -Milliseconds 500
+
New-Item -ItemType Directory -Path $InstallDirectory -Force | Out-Null
-Copy-Item (Join-Path $SourceDirectory 'agent.exe') (Join-Path $InstallDirectory 'agent.exe') -Force
-Copy-Item (Join-Path $SourceDirectory 'config.json') (Join-Path $InstallDirectory 'config.json') -Force
+Copy-Item -LiteralPath $sourceAgent -Destination (Join-Path $InstallDirectory 'agent.exe') -Force
+Copy-Item -LiteralPath $sourceConfig -Destination (Join-Path $InstallDirectory 'config.json') -Force
$acl = Get-Acl $InstallDirectory
$acl.SetAccessRuleProtection($true, $false)
$administratorsSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')
@@ -19,21 +55,59 @@ $system = New-Object System.Security.AccessControl.FileSystemAccessRule($systemS
$acl.SetAccessRule($admins); $acl.SetAccessRule($system); Set-Acl $InstallDirectory $acl
$agentPath = Join-Path $InstallDirectory 'agent.exe'
$configPath = Join-Path $InstallDirectory 'config.json'
-if ($Schedule -ne 'DAILY') { throw "Derzeit wird nur Schedule 'DAILY' unterstützt." }
-$action = New-ScheduledTaskAction -Execute $agentPath -Argument "--config `"$configPath`""
-$trigger = New-ScheduledTaskTrigger -Daily -At $StartTime
$principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest
-$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 15)
-Register-ScheduledTask -TaskName 'NetBox Windows Agent' -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
-& $agentPath --config $configPath
-$syncExitCode = $LASTEXITCODE
-if ($syncExitCode -ne 0) {
- Write-Warning "Der Agent wurde installiert, aber die erste NetBox-Synchronisation ist mit Exitcode $syncExitCode fehlgeschlagen. Die geplante Aufgabe versucht es erneut."
+
+# --- NetBox sync (mode netbox/both) -------------------------------------------------------------
+if ($syncs) {
+ $action = New-ScheduledTaskAction -Execute $agentPath -Argument "--config `"$configPath`""
+ $trigger = New-ScheduledTaskTrigger -Daily -At $StartTime
+ $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 15)
+ Register-ScheduledTask -TaskName $syncTask -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
} else {
- Write-Host 'Die erste NetBox-Synchronisation war erfolgreich.'
+ Unregister-ScheduledTask -TaskName $syncTask -Confirm:$false -ErrorAction SilentlyContinue
}
-if (-not (Test-Path -LiteralPath $agentPath)) { throw 'Installation fehlgeschlagen: agent.exe wurde nicht installiert.' }
-if (-not (Test-Path -LiteralPath $configPath)) { throw 'Installation fehlgeschlagen: config.json wurde nicht installiert.' }
-if (-not (Get-ScheduledTask -TaskName 'NetBox Windows Agent' -ErrorAction SilentlyContinue)) { throw 'Installation fehlgeschlagen: Die geplante Aufgabe fehlt.' }
-Write-Host 'NetBox Windows Agent wurde erfolgreich installiert.'
+
+# --- Listener for the NetBox Synchronizer (mode listen/both) ------------------------------------
+Remove-NetFirewallRule -Name $firewallRule -ErrorAction SilentlyContinue
+if ($listens) {
+ $action = New-ScheduledTaskAction -Execute $agentPath -Argument "--config `"$configPath`" --serve"
+ $trigger = New-ScheduledTaskTrigger -AtStartup
+ $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
+ -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) `
+ -MultipleInstances IgnoreNew
+ Register-ScheduledTask -TaskName $listenerTask -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
+ $remote = if ($allowed.Count -gt 0) { $allowed } else { 'Any' }
+ New-NetFirewallRule -Name $firewallRule -DisplayName 'NetBox Windows Agent' -Direction Inbound -Protocol TCP `
+ -LocalPort $port -Program $agentPath -RemoteAddress $remote -Profile Domain, Private -Action Allow | Out-Null
+ Start-ScheduledTask -TaskName $listenerTask
+} else {
+ Unregister-ScheduledTask -TaskName $listenerTask -Confirm:$false -ErrorAction SilentlyContinue
+}
+
+# --- First NetBox sync ----------------------------------------------------------------------------
+if ($syncs) {
+ & $agentPath --config $configPath
+ $syncExitCode = $LASTEXITCODE
+ if ($syncExitCode -ne 0) {
+ Write-Warning "The agent is installed, but the first NetBox sync failed with exit code $syncExitCode. The scheduled task retries it."
+ } else {
+ Write-Host 'The first NetBox sync was successful.'
+ }
+}
+
+# --- Checks (decide the Intune installation state) -----------------------------------------------
+if (-not (Test-Path -LiteralPath $agentPath)) { throw 'Installation failed: agent.exe was not installed.' }
+if (-not (Test-Path -LiteralPath $configPath)) { throw 'Installation failed: config.json was not installed.' }
+if ($syncs -and -not (Get-ScheduledTask -TaskName $syncTask -ErrorAction SilentlyContinue)) { throw 'Installation failed: the scheduled task is missing.' }
+if ($listens -and -not (Get-ScheduledTask -TaskName $listenerTask -ErrorAction SilentlyContinue)) { throw 'Installation failed: the listener task is missing.' }
+
+# Fingerprint of the installed files, used by gpo-startup.ps1 to skip unchanged installations.
+$state = [ordered]@{
+ agent = (Get-FileHash -LiteralPath $agentPath -Algorithm SHA256).Hash
+ config = (Get-FileHash -LiteralPath $configPath -Algorithm SHA256).Hash
+ mode = $mode
+ installed = (Get-Date).ToString('o')
+}
+$state | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $InstallDirectory 'install-state.json') -Encoding UTF8
+Write-Host "NetBox Windows Agent was installed successfully (mode '$mode')."
exit 0
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index ecb40e5..abf500e 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -1,9 +1,16 @@
param([string]$InstallDirectory = "$env:ProgramFiles\NetBox Windows Agent")
$ErrorActionPreference = 'Stop'
Unregister-ScheduledTask -TaskName 'NetBox Windows Agent' -Confirm:$false -ErrorAction SilentlyContinue
+Stop-ScheduledTask -TaskName 'NetBox Windows Agent Listener' -ErrorAction SilentlyContinue
+Unregister-ScheduledTask -TaskName 'NetBox Windows Agent Listener' -Confirm:$false -ErrorAction SilentlyContinue
+Remove-NetFirewallRule -Name 'NetBoxWindowsAgent' -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath $InstallDirectory) {
$resolved = (Resolve-Path -LiteralPath $InstallDirectory).Path
$programFiles = (Resolve-Path -LiteralPath $env:ProgramFiles).Path
- if (-not $resolved.StartsWith($programFiles + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Unsicheres Ziel: $resolved" }
+ if (-not $resolved.StartsWith($programFiles + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Unsafe target: $resolved" }
+ Get-Process -Name agent -ErrorAction SilentlyContinue |
+ Where-Object { $_.Path -and $_.Path.StartsWith($resolved, [StringComparison]::OrdinalIgnoreCase) } |
+ Stop-Process -Force -ErrorAction SilentlyContinue
+ Start-Sleep -Milliseconds 500
Remove-Item -LiteralPath $resolved -Recurse -Force
}
diff --git a/src/HardwareCollector.cs b/src/HardwareCollector.cs
index a69c080..ffe84c0 100644
--- a/src/HardwareCollector.cs
+++ b/src/HardwareCollector.cs
@@ -7,27 +7,76 @@ internal static class HardwareCollector
{
public static HardwareInfo Collect(bool collectSoftware = true, int maxSoftwareEntries = 250)
{
- var computer = First("Win32_ComputerSystem", "Manufacturer", "Model", "TotalPhysicalMemory");
- var product = First("Win32_ComputerSystemProduct", "UUID");
- var bios = First("Win32_BIOS", "SerialNumber");
- var os = First("Win32_OperatingSystem", "Caption", "Version", "OSArchitecture");
- var cpu = First("Win32_Processor", "Name");
+ var computer = First("Win32_ComputerSystem", "Name", "Domain", "PartOfDomain", "Manufacturer", "Model",
+ "TotalPhysicalMemory", "UserName");
+ var product = First("Win32_ComputerSystemProduct", "UUID", "Name", "Version");
+ var bios = First("Win32_BIOS", "SerialNumber", "SMBIOSBIOSVersion");
+ var os = First("Win32_OperatingSystem", "Caption", "Version", "BuildNumber", "OSArchitecture", "InstallDate",
+ "LastBootUpTime");
+ var enclosure = FirstOrDefault("Win32_SystemEnclosure", "ChassisTypes");
+ var processors = Query("Win32_Processor", "Name", "NumberOfCores").ToList();
var disks = Query("Win32_DiskDrive", "DeviceID", "Model", "SerialNumber", "Size")
.Select(x => new DiskInfo(S(x, "DeviceID"), S(x, "Model"), S(x, "SerialNumber"), U(x, "Size"))).ToList();
var networks = Query("Win32_NetworkAdapterConfiguration", "Description", "MACAddress", "IPAddress")
.Where(x => x["MACAddress"] is not null)
.Select(x => new NetworkInfo(S(x, "Description"), S(x, "MACAddress"),
- (x["IPAddress"] as string[] ?? []).Where(ip => !ip.StartsWith("169.254.")).ToList())).ToList();
+ Strings(x, "IPAddress").Where(ip => !ip.StartsWith("169.254.")).ToList())).ToList();
var memoryModules = Query("Win32_PhysicalMemory", "BankLabel", "DeviceLocator", "Manufacturer", "PartNumber", "SerialNumber", "Capacity")
.Select(x => new MemoryInfo(
string.IsNullOrWhiteSpace(S(x, "BankLabel")) ? S(x, "DeviceLocator") : S(x, "BankLabel"),
S(x, "Manufacturer"), S(x, "PartNumber"), S(x, "SerialNumber"), U(x, "Capacity"))).ToList();
- return new HardwareInfo(Environment.MachineName, S(computer, "Manufacturer"), S(computer, "Model"),
- S(bios, "SerialNumber"), S(product, "UUID"), S(os, "Caption"), S(os, "Version"),
- S(os, "OSArchitecture"), S(cpu, "Name"), U(computer, "TotalPhysicalMemory"), disks, networks,
- memoryModules, collectSoftware ? CollectSoftware(maxSoftwareEntries) : []);
+ return new HardwareInfo
+ {
+ Hostname = Environment.MachineName,
+ Domain = S(computer, "Domain"),
+ PartOfDomain = computer["PartOfDomain"] is true,
+ Manufacturer = S(computer, "Manufacturer"),
+ Model = S(computer, "Model"),
+ ProductName = S(product, "Name"),
+ ProductVersion = S(product, "Version"),
+ Serial = S(bios, "SerialNumber"),
+ Uuid = S(product, "UUID"),
+ BiosVersion = S(bios, "SMBIOSBIOSVersion"),
+ Chassis = enclosure?["ChassisTypes"] is ushort[] types ? types.Select(t => (int)t).ToList() : [],
+ User = S(computer, "UserName"),
+ WindowsCaption = S(os, "Caption"),
+ WindowsVersion = S(os, "Version"),
+ WindowsBuild = S(os, "BuildNumber"),
+ WindowsDisplayVersion = RegistryString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "DisplayVersion"),
+ Architecture = S(os, "OSArchitecture"),
+ Installed = CimDate(S(os, "InstallDate")),
+ LastBoot = CimDate(S(os, "LastBootUpTime")),
+ Processor = processors.Count > 0 ? S(processors[0], "Name") : "",
+ Cores = processors.Sum(p => (int)U(p, "NumberOfCores")),
+ MemoryBytes = U(computer, "TotalPhysicalMemory"),
+ Disks = disks,
+ Networks = networks,
+ Nics = CollectNics(),
+ MemoryModules = memoryModules,
+ Software = collectSoftware ? CollectSoftware(maxSoftwareEntries) : [],
+ };
+ }
+
+ private static IReadOnlyList CollectNics()
+ {
+ var adapters = Query("Win32_NetworkAdapter", "InterfaceIndex", "PhysicalAdapter", "NetConnectionID", "Speed")
+ .Where(x => x["PhysicalAdapter"] is true)
+ .GroupBy(x => U(x, "InterfaceIndex"))
+ .ToDictionary(g => g.Key, g => g.First());
+ var nics = new List();
+ foreach (var config in Query("Win32_NetworkAdapterConfiguration", "IPEnabled", "InterfaceIndex", "Description",
+ "MACAddress", "IPAddress", "IPSubnet", "DefaultIPGateway", "DHCPEnabled"))
+ {
+ if (config["IPEnabled"] is not true) continue;
+ adapters.TryGetValue(U(config, "InterfaceIndex"), out var adapter);
+ nics.Add(new NicInfo(adapter is null ? "" : S(adapter, "NetConnectionID"), S(config, "Description"),
+ S(config, "MACAddress"), Strings(config, "IPAddress"), Strings(config, "IPSubnet"),
+ Strings(config, "DefaultIPGateway"), config["DHCPEnabled"] is true, adapter is not null,
+ adapter is null ? 0 : U(adapter, "Speed")));
+ }
+ return nics;
}
private static IReadOnlyList CollectSoftware(int maximum)
@@ -51,7 +100,19 @@ internal static class HardwareCollector
return software.Values.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase).Take(Math.Clamp(maximum, 0, 1000)).ToList();
}
+ private static string RegistryString(string key, string value)
+ {
+ using var hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
+ using var sub = hive.OpenSubKey(key);
+ return Convert.ToString(sub?.GetValue(value))?.Trim() ?? "";
+ }
+
+ // CIM datetime "20240115083000.000000+060" -> "2024-01-15T08:30:00"
+ private static string CimDate(string value) =>
+ value.Length >= 14 ? $"{value[..4]}-{value[4..6]}-{value[6..8]}T{value[8..10]}:{value[10..12]}:{value[12..14]}" : "";
+
private static ManagementBaseObject First(string cls, params string[] fields) => Query(cls, fields).First();
+ private static ManagementBaseObject? FirstOrDefault(string cls, params string[] fields) => Query(cls, fields).FirstOrDefault();
private static IEnumerable Query(string cls, params string[] fields)
{
using var searcher = new ManagementObjectSearcher($"SELECT {string.Join(',', fields)} FROM {cls}");
@@ -59,4 +120,6 @@ internal static class HardwareCollector
}
private static string S(ManagementBaseObject x, string key) => Convert.ToString(x[key])?.Trim() ?? "";
private static ulong U(ManagementBaseObject x, string key) => ulong.TryParse(Convert.ToString(x[key]), out var n) ? n : 0;
+ private static List Strings(ManagementBaseObject x, string key) =>
+ (x[key] as string[] ?? []).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
}
diff --git a/src/InventoryServer.cs b/src/InventoryServer.cs
new file mode 100644
index 0000000..68bdc86
--- /dev/null
+++ b/src/InventoryServer.cs
@@ -0,0 +1,204 @@
+using System.Collections.Concurrent;
+using System.Net;
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+
+namespace NetBoxWindowsAgent;
+
+///
+/// Serves the inventory to the NetBox Synchronizer desktop app ("listen" mode).
+///
+/// Protocol v1 over plain HTTP:
+/// GET /v1/info unauthenticated: agent name, version and protocol
+/// GET /v1/inventory?nonce=N&ts=T header X-Agent-Signature: hex(HMAC-SHA256(authKey, "GET\n/v1/inventory\nN\nT"))
+/// The inventory is returned encrypted with AES-256-GCM (encKey, random 12 byte IV, the request nonce as
+/// associated data): {"protocol":1,"iv":base64,"data":base64(ciphertext||tag)}.
+/// authKey = HMAC-SHA256(UTF8(scan_key), "netbox-agent auth v1"), encKey = HMAC-SHA256(UTF8(scan_key), "netbox-agent enc v1").
+/// Requests older than 5 minutes and repeated nonces are rejected.
+///
+internal sealed class InventoryServer(AgentConfig config, Func collect)
+{
+ private static readonly Regex NonceFormat = new("^[0-9a-f]{32}$", RegexOptions.Compiled);
+ private readonly byte[] _authKey = DeriveKey(config.ScanKey, "netbox-agent auth v1");
+ private readonly byte[] _encKey = DeriveKey(config.ScanKey, "netbox-agent enc v1");
+ private readonly ConcurrentDictionary _nonces = new();
+ private readonly List _allowed = config.AllowedNetworks.Select(IPNetwork.Parse).ToList();
+ private readonly SemaphoreSlim _collectLock = new(1, 1);
+ private byte[]? _cached;
+ private DateTime _cachedAt;
+
+ public static byte[] DeriveKey(string secret, string purpose) =>
+ HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes(purpose));
+
+ public async Task Run(CancellationToken cancel)
+ {
+ var listener = new TcpListener(IPAddress.IPv6Any, config.ListenPort);
+ listener.Server.DualMode = true;
+ listener.Start();
+ Console.WriteLine($"Listening on TCP port {config.ListenPort} (protocol v{AgentInfo.Protocol}).");
+ while (!cancel.IsCancellationRequested)
+ {
+ var client = await listener.AcceptTcpClientAsync(cancel);
+ _ = Task.Run(() => Handle(client), cancel);
+ }
+ }
+
+ private async Task Handle(TcpClient client)
+ {
+ using (client)
+ {
+ try
+ {
+ client.ReceiveTimeout = client.SendTimeout = 10000;
+ var stream = client.GetStream();
+ var remote = (client.Client.RemoteEndPoint as IPEndPoint)?.Address ?? IPAddress.None;
+ if (remote.IsIPv4MappedToIPv6) remote = remote.MapToIPv4();
+ var (status, body) = await Respond(stream, remote);
+ var bytes = Encoding.UTF8.GetBytes(body);
+ var header = $"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\n" +
+ "Cache-Control: no-store\r\nConnection: close\r\n\r\n";
+ await stream.WriteAsync(Encoding.ASCII.GetBytes(header));
+ await stream.WriteAsync(bytes);
+ }
+ catch (Exception ex) when (ex is IOException or SocketException or ObjectDisposedException)
+ {
+ // client went away
+ }
+ }
+ }
+
+ private async Task<(string Status, string Body)> Respond(NetworkStream stream, IPAddress remote)
+ {
+ if (_allowed.Count > 0 && !_allowed.Any(network => network.Contains(remote)))
+ return ("403 Forbidden", Error("address not allowed"));
+ var request = await ReadRequest(stream);
+ if (request is null) return ("400 Bad Request", Error("bad request"));
+ var (method, target, headers) = request.Value;
+ if (method != "GET") return ("405 Method Not Allowed", Error("only GET"));
+ var path = target.Split('?')[0];
+ var query = ParseQuery(target);
+ if (path == "/v1/info")
+ return ("200 OK", JsonSerializer.Serialize(new { agent = "netbox-windows-agent", version = AgentInfo.Version,
+ protocol = AgentInfo.Protocol }));
+ if (path != "/v1/inventory") return ("404 Not Found", Error("not found"));
+
+ var nonce = query.GetValueOrDefault("nonce", "");
+ if (!NonceFormat.IsMatch(nonce) || !long.TryParse(query.GetValueOrDefault("ts", ""), out var ts))
+ return ("400 Bad Request", Error("nonce or ts missing"));
+ var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+ if (Math.Abs(now - ts) > 300) return ("401 Unauthorized", Error("clock skew too large"));
+ var expected = HMACSHA256.HashData(_authKey, Encoding.UTF8.GetBytes($"GET\n/v1/inventory\n{nonce}\n{ts}"));
+ byte[] given;
+ try { given = Convert.FromHexString(headers.GetValueOrDefault("x-agent-signature", "")); }
+ catch (FormatException) { given = []; }
+ if (!CryptographicOperations.FixedTimeEquals(expected, given)) return ("401 Unauthorized", Error("wrong key"));
+ foreach (var old in _nonces.Where(item => now - item.Value > 600).Select(item => item.Key).ToList())
+ _nonces.TryRemove(old, out _);
+ if (!_nonces.TryAdd(nonce, now)) return ("401 Unauthorized", Error("nonce reused"));
+
+ var plain = await Inventory();
+ var iv = RandomNumberGenerator.GetBytes(12);
+ var cipher = new byte[plain.Length];
+ var tag = new byte[16];
+ using (var aes = new AesGcm(_encKey, 16)) aes.Encrypt(iv, plain, cipher, tag, Encoding.ASCII.GetBytes(nonce));
+ return ("200 OK", JsonSerializer.Serialize(new { protocol = AgentInfo.Protocol, iv = Convert.ToBase64String(iv),
+ data = Convert.ToBase64String([.. cipher, .. tag]) }));
+ }
+
+ private async Task Inventory()
+ {
+ await _collectLock.WaitAsync();
+ try
+ {
+ if (_cached is null || DateTime.UtcNow - _cachedAt > TimeSpan.FromSeconds(Math.Max(0, config.InventoryCacheSeconds)))
+ {
+ _cached = JsonSerializer.SerializeToUtf8Bytes(InventoryDocument.Build(collect()));
+ _cachedAt = DateTime.UtcNow;
+ }
+ return _cached;
+ }
+ finally { _collectLock.Release(); }
+ }
+
+ private static async Task<(string Method, string Target, Dictionary Headers)?> ReadRequest(NetworkStream stream)
+ {
+ var buffer = new byte[8192];
+ var length = 0;
+ while (length < buffer.Length)
+ {
+ var read = await stream.ReadAsync(buffer.AsMemory(length));
+ if (read == 0) break;
+ length += read;
+ if (Encoding.ASCII.GetString(buffer, 0, length).Contains("\r\n\r\n")) break;
+ }
+ var text = Encoding.ASCII.GetString(buffer, 0, length);
+ var end = text.IndexOf("\r\n\r\n", StringComparison.Ordinal);
+ if (end < 0) return null;
+ var lines = text[..end].Split("\r\n");
+ var first = lines[0].Split(' ');
+ if (first.Length != 3) return null;
+ var headers = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var line in lines.Skip(1))
+ {
+ var colon = line.IndexOf(':');
+ if (colon > 0) headers[line[..colon].Trim().ToLowerInvariant()] = line[(colon + 1)..].Trim();
+ }
+ return (first[0], first[1], headers);
+ }
+
+ private static Dictionary ParseQuery(string target)
+ {
+ var result = new Dictionary();
+ var index = target.IndexOf('?');
+ if (index < 0) return result;
+ foreach (var part in target[(index + 1)..].Split('&', StringSplitOptions.RemoveEmptyEntries))
+ {
+ var pair = part.Split('=', 2);
+ result[Uri.UnescapeDataString(pair[0])] = pair.Length > 1 ? Uri.UnescapeDataString(pair[1]) : "";
+ }
+ return result;
+ }
+
+ private static string Error(string text) => JsonSerializer.Serialize(new { error = text });
+}
+
+/// Inventory in the shape of the WinRM scan of the desktop app, plus agent-only details.
+internal static class InventoryDocument
+{
+ public static Dictionary Build(HardwareInfo hw) => new()
+ {
+ ["ok"] = true,
+ ["source"] = "agent",
+ ["agent_version"] = AgentInfo.Version,
+ ["collected_at"] = DateTimeOffset.UtcNow.ToString("O"),
+ ["name"] = hw.Hostname,
+ ["domain"] = hw.Domain,
+ ["part_of_domain"] = hw.PartOfDomain,
+ ["manufacturer"] = hw.Manufacturer,
+ ["model"] = hw.Model,
+ ["product_name"] = hw.ProductName,
+ ["product_version"] = hw.ProductVersion,
+ ["serial"] = hw.Serial,
+ ["uuid"] = hw.Uuid,
+ ["bios_version"] = hw.BiosVersion,
+ ["chassis"] = hw.Chassis,
+ ["user"] = hw.User,
+ ["memory"] = hw.MemoryBytes,
+ ["cpu"] = hw.Processor,
+ ["cores"] = hw.Cores,
+ ["os"] = hw.WindowsCaption,
+ ["os_version"] = hw.WindowsVersion,
+ ["os_build"] = hw.WindowsBuild,
+ ["os_display_version"] = hw.WindowsDisplayVersion,
+ ["os_architecture"] = hw.Architecture,
+ ["installed"] = hw.Installed,
+ ["last_boot"] = hw.LastBoot,
+ ["nics"] = hw.Nics,
+ ["disks"] = hw.Disks,
+ ["memory_modules"] = hw.MemoryModules,
+ ["software"] = hw.Software,
+ };
+}
diff --git a/src/Models.cs b/src/Models.cs
index f904b05..55989b2 100644
--- a/src/Models.cs
+++ b/src/Models.cs
@@ -2,8 +2,17 @@ using System.Text.Json.Serialization;
namespace NetBoxWindowsAgent;
+internal static class AgentInfo
+{
+ public const string Version = "0.2.0";
+ public const int Protocol = 1;
+}
+
internal sealed class AgentConfig
{
+ // "netbox": write to NetBox directly (default), "listen": only serve the inventory to the
+ // NetBox Synchronizer desktop app, "both": do both.
+ [JsonPropertyName("mode")] public string Mode { get; set; } = "netbox";
[JsonPropertyName("netbox_url")] public string NetBoxUrl { get; set; } = "";
[JsonPropertyName("api_token")] public string ApiToken { get; set; } = "";
[JsonPropertyName("region")] public string Region { get; set; } = "";
@@ -19,17 +28,75 @@ internal sealed class AgentConfig
[JsonPropertyName("create_interfaces")] public bool CreateInterfaces { get; set; } = true;
[JsonPropertyName("tags")] public List Tags { get; set; } = [];
[JsonPropertyName("custom_fields")] public Dictionary CustomFields { get; set; } = new();
+ // Listen mode
+ [JsonPropertyName("listen_port")] public int ListenPort { get; set; } = 8731;
+ [JsonPropertyName("scan_key")] public string ScanKey { get; set; } = "";
+ [JsonPropertyName("allowed_networks")] public List AllowedNetworks { get; set; } = [];
+ [JsonPropertyName("inventory_cache_seconds")] public int InventoryCacheSeconds { get; set; } = 300;
+
+ [JsonIgnore] public bool SyncsNetBox => Mode is "netbox" or "both";
+ [JsonIgnore] public bool Listens => Mode is "listen" or "both";
}
-internal sealed record HardwareInfo(
- string Hostname, string Manufacturer, string Model, string Serial, string Uuid,
- string WindowsCaption, string WindowsVersion, string Architecture, string Processor,
- ulong MemoryBytes, IReadOnlyList Disks, IReadOnlyList Networks,
- IReadOnlyList MemoryModules, IReadOnlyList Software);
-internal sealed record DiskInfo(string DeviceId, string Model, string Serial, ulong SizeBytes);
+internal sealed class HardwareInfo
+{
+ public string Hostname { get; init; } = "";
+ public string Domain { get; init; } = "";
+ public bool PartOfDomain { get; init; }
+ public string Manufacturer { get; init; } = "";
+ public string Model { get; init; } = "";
+ public string ProductName { get; init; } = "";
+ public string ProductVersion { get; init; } = "";
+ public string Serial { get; init; } = "";
+ public string Uuid { get; init; } = "";
+ public string BiosVersion { get; init; } = "";
+ public IReadOnlyList Chassis { get; init; } = [];
+ public string User { get; init; } = "";
+ public string WindowsCaption { get; init; } = "";
+ public string WindowsVersion { get; init; } = "";
+ public string WindowsBuild { get; init; } = "";
+ public string WindowsDisplayVersion { get; init; } = "";
+ public string Architecture { get; init; } = "";
+ public string Installed { get; init; } = "";
+ public string LastBoot { get; init; } = "";
+ public string Processor { get; init; } = "";
+ public int Cores { get; init; }
+ public ulong MemoryBytes { get; init; }
+ public IReadOnlyList Disks { get; init; } = [];
+ public IReadOnlyList Networks { get; init; } = [];
+ public IReadOnlyList Nics { get; init; } = [];
+ public IReadOnlyList MemoryModules { get; init; } = [];
+ public IReadOnlyList Software { get; init; } = [];
+}
+
+internal sealed record DiskInfo(
+ [property: JsonPropertyName("device_id")] string DeviceId,
+ [property: JsonPropertyName("model")] string Model,
+ [property: JsonPropertyName("serial")] string Serial,
+ [property: JsonPropertyName("size")] ulong SizeBytes);
internal sealed record NetworkInfo(string Name, string MacAddress, IReadOnlyList IpAddresses);
-internal sealed record MemoryInfo(string Bank, string Manufacturer, string PartNumber, string Serial, ulong CapacityBytes);
-internal sealed record SoftwareInfo(string Name, string Version, string Publisher);
+internal sealed record MemoryInfo(
+ [property: JsonPropertyName("bank")] string Bank,
+ [property: JsonPropertyName("manufacturer")] string Manufacturer,
+ [property: JsonPropertyName("part_number")] string PartNumber,
+ [property: JsonPropertyName("serial")] string Serial,
+ [property: JsonPropertyName("capacity")] ulong CapacityBytes);
+internal sealed record SoftwareInfo(
+ [property: JsonPropertyName("name")] string Name,
+ [property: JsonPropertyName("version")] string Version,
+ [property: JsonPropertyName("publisher")] string Publisher);
+
+// Same shape as the WinRM scan of the NetBox Synchronizer desktop app.
+internal sealed record NicInfo(
+ [property: JsonPropertyName("name")] string Name,
+ [property: JsonPropertyName("description")] string Description,
+ [property: JsonPropertyName("mac")] string Mac,
+ [property: JsonPropertyName("ips")] IReadOnlyList Ips,
+ [property: JsonPropertyName("masks")] IReadOnlyList Masks,
+ [property: JsonPropertyName("gateway")] IReadOnlyList Gateway,
+ [property: JsonPropertyName("dhcp")] bool Dhcp,
+ [property: JsonPropertyName("physical")] bool Physical,
+ [property: JsonPropertyName("speed")] ulong Speed);
internal sealed class Page
{
diff --git a/src/NetBoxClient.cs b/src/NetBoxClient.cs
index d2361dd..4ed09b6 100644
--- a/src/NetBoxClient.cs
+++ b/src/NetBoxClient.cs
@@ -17,7 +17,7 @@ internal sealed class NetBoxClient : IDisposable
_http = new HttpClient(handler) { BaseAddress = new Uri(config.NetBoxUrl.TrimEnd('/') + "/"), Timeout = TimeSpan.FromSeconds(config.TimeoutSeconds) };
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", config.ApiToken);
_http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- _http.DefaultRequestHeaders.UserAgent.ParseAdd("NetBox-Windows-Agent/0.1.0");
+ _http.DefaultRequestHeaders.UserAgent.ParseAdd($"NetBox-Windows-Agent/{AgentInfo.Version}");
}
public async Task FindOne(string endpoint, params (string Key, string? Value)[] filters)
@@ -25,7 +25,7 @@ internal sealed class NetBoxClient : IDisposable
var query = string.Join('&', filters.Where(f => !string.IsNullOrWhiteSpace(f.Value))
.Select(f => $"{Uri.EscapeDataString(f.Key)}={Uri.EscapeDataString(f.Value!)}"));
var page = await Send>(HttpMethod.Get, $"api/{endpoint}/?limit=2&{query}");
- if (page.Count > 1) throw new InvalidOperationException($"NetBox-Abfrage für {endpoint} ist nicht eindeutig.");
+ if (page.Count > 1) throw new InvalidOperationException($"NetBox query for {endpoint} is ambiguous.");
return page.Results.SingleOrDefault();
}
@@ -42,7 +42,7 @@ internal sealed class NetBoxClient : IDisposable
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
throw new InvalidOperationException($"NetBox {method} {uri}: {(int)response.StatusCode} {response.ReasonPhrase}: {body}");
- return JsonSerializer.Deserialize(body, _json) ?? throw new InvalidOperationException("NetBox lieferte eine leere Antwort.");
+ return JsonSerializer.Deserialize(body, _json) ?? throw new InvalidOperationException("NetBox returned an empty response.");
}
public void Dispose() => _http.Dispose();
}
diff --git a/src/Program.cs b/src/Program.cs
index 6c95281..7d4dbaa 100644
--- a/src/Program.cs
+++ b/src/Program.cs
@@ -7,36 +7,78 @@ static async Task MainAsync(string[] args)
{
try
{
- var configPath = ValueAfter(args, "--config") ?? Path.Combine(AppContext.BaseDirectory, "config.json");
- var dryRun = args.Contains("--dry-run");
if (args.Contains("--help")) { Usage(); return 0; }
- if (!File.Exists(configPath)) throw new FileNotFoundException("Konfigurationsdatei nicht gefunden.", configPath);
+ if (args.Contains("--version")) { Console.WriteLine(AgentInfo.Version); return 0; }
+ var configPath = ValueAfter(args, "--config") ?? Path.Combine(AppContext.BaseDirectory, "config.json");
+ if (!File.Exists(configPath)) throw new FileNotFoundException("Configuration file not found.", configPath);
var config = JsonSerializer.Deserialize(await File.ReadAllTextAsync(configPath), new JsonSerializerOptions(JsonSerializerDefaults.Web))
- ?? throw new InvalidOperationException("Konfiguration ist leer.");
+ ?? throw new InvalidOperationException("Configuration is empty.");
Validate(config);
- var hardware = HardwareCollector.Collect(config.CollectSoftware, config.MaxSoftwareEntries);
- Console.WriteLine($"Erfasst: {hardware.Hostname}, {hardware.Manufacturer} {hardware.Model}, S/N {hardware.Serial}");
+ HardwareInfo Collect() => HardwareCollector.Collect(config.CollectSoftware, config.MaxSoftwareEntries);
+
+ if (args.Contains("--print"))
+ {
+ Console.WriteLine(JsonSerializer.Serialize(InventoryDocument.Build(Collect()), new JsonSerializerOptions { WriteIndented = true }));
+ return 0;
+ }
+ if (args.Contains("--serve"))
+ {
+ if (!config.Listens) throw new InvalidOperationException("--serve requires \"mode\": \"listen\" or \"both\".");
+ using var cancel = new CancellationTokenSource();
+ Console.CancelKeyPress += (_, e) => { e.Cancel = true; cancel.Cancel(); };
+ await new InventoryServer(config, Collect).Run(cancel.Token);
+ return 0;
+ }
+ if (!config.SyncsNetBox)
+ {
+ Console.WriteLine("Mode \"listen\": nothing to sync. The inventory is served by \"agent.exe --serve\".");
+ return 0;
+ }
+
+ var dryRun = args.Contains("--dry-run");
+ var hardware = Collect();
+ Console.WriteLine($"Collected: {hardware.Hostname}, {hardware.Manufacturer} {hardware.Model}, S/N {hardware.Serial}");
using var client = new NetBoxClient(config);
var result = await new SyncService(client, config).Sync(hardware, dryRun);
- Console.WriteLine(dryRun ? "Dry-Run erfolgreich; keine Änderungen geschrieben." : $"Synchronisiert: Device #{result.DeviceId}, Asset #{result.AssetId}");
+ Console.WriteLine(dryRun ? "Dry run successful; nothing was written." : $"Synchronized: device #{result.DeviceId}, asset #{result.AssetId}");
return 0;
}
- catch (Exception ex)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
var messages = new List();
for (Exception? current = ex; current is not null; current = current.InnerException)
if (!messages.Contains(current.Message)) messages.Add(current.Message);
- Console.Error.WriteLine($"FEHLER: {string.Join(" -> ", messages)}");
+ Console.Error.WriteLine($"ERROR: {string.Join(" -> ", messages)}");
return 1;
}
+ catch (OperationCanceledException)
+ {
+ return 0;
+ }
}
static string? ValueAfter(string[] args, string key) { var i = Array.IndexOf(args, key); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; }
static void Validate(AgentConfig c)
{
- if (!Uri.TryCreate(c.NetBoxUrl, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")) throw new InvalidOperationException("netbox_url ist ungültig.");
- if (string.IsNullOrWhiteSpace(c.ApiToken) || c.ApiToken == "CHANGE_ME") throw new InvalidOperationException("api_token fehlt.");
- if (string.IsNullOrWhiteSpace(c.DeviceRole)) throw new InvalidOperationException("device_role fehlt.");
- if (string.IsNullOrWhiteSpace(c.Site)) throw new InvalidOperationException("site fehlt. NetBox verlangt für jedes DCIM Device eine Site; nur location ist optional.");
- if (c.MaxSoftwareEntries < 0 || c.MaxSoftwareEntries > 1000) throw new InvalidOperationException("max_software_entries muss zwischen 0 und 1000 liegen.");
+ if (c.Mode is not ("netbox" or "listen" or "both")) throw new InvalidOperationException("mode must be \"netbox\", \"listen\" or \"both\".");
+ if (c.MaxSoftwareEntries < 0 || c.MaxSoftwareEntries > 1000) throw new InvalidOperationException("max_software_entries must be between 0 and 1000.");
+ if (c.SyncsNetBox)
+ {
+ if (!Uri.TryCreate(c.NetBoxUrl, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")) throw new InvalidOperationException("netbox_url is invalid.");
+ if (string.IsNullOrWhiteSpace(c.ApiToken) || c.ApiToken == "CHANGE_ME") throw new InvalidOperationException("api_token is missing.");
+ if (string.IsNullOrWhiteSpace(c.DeviceRole)) throw new InvalidOperationException("device_role is missing.");
+ if (string.IsNullOrWhiteSpace(c.Site)) throw new InvalidOperationException("site is missing. NetBox requires a site for every DCIM device; only location is optional.");
+ }
+ if (c.Listens)
+ {
+ if (c.ScanKey.Length < 16 || c.ScanKey == "CHANGE_ME") throw new InvalidOperationException("scan_key must have at least 16 characters.");
+ if (c.ListenPort is < 1 or > 65535) throw new InvalidOperationException("listen_port is invalid.");
+ foreach (var network in c.AllowedNetworks)
+ if (!System.Net.IPNetwork.TryParse(network, out _)) throw new InvalidOperationException($"allowed_networks: \"{network}\" is not a network in CIDR notation.");
+ }
}
-static void Usage() => Console.WriteLine("agent.exe [--config PFAD] [--dry-run] [--help]");
+static void Usage() => Console.WriteLine("""
+ agent.exe [--config PATH] [--dry-run] collect and write to NetBox (mode "netbox" or "both")
+ agent.exe [--config PATH] --serve serve the inventory to the NetBox Synchronizer (mode "listen" or "both")
+ agent.exe [--config PATH] --print print the collected inventory as JSON
+ agent.exe --version | --help
+ """);
diff --git a/src/SyncService.cs b/src/SyncService.cs
index 33b6ef5..726e760 100644
--- a/src/SyncService.cs
+++ b/src/SyncService.cs
@@ -9,7 +9,7 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
var manufacturer = await EnsureManufacturer(hw.Manufacturer, dryRun);
var deviceType = await EnsureDeviceType(manufacturer, hw.Model, dryRun);
var role = await client.FindOne("dcim/device-roles", ("slug", config.DeviceRole))
- ?? throw new InvalidOperationException($"Geräterolle '{config.DeviceRole}' fehlt in NetBox.");
+ ?? throw new InvalidOperationException($"Device role '{config.DeviceRole}' does not exist in NetBox.");
var device = await client.FindOne("dcim/devices", ("serial", hw.Serial));
var customFields = BuildCustomFields(hw);
@@ -33,7 +33,7 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
var assetPayload = new Dictionary {
["name"] = hw.Hostname, ["serial"] = hw.Serial, ["status"] = "used",
["device_type"] = deviceType.Id, ["device"] = device.Id,
- ["description"] = $"Windows-Client; UUID {hw.Uuid}", ["comments"] = inventoryReport
+ ["description"] = $"Windows client; UUID {hw.Uuid}", ["comments"] = inventoryReport
};
if (asset is null) {
if (dryRun) return (device.Id, 0);
@@ -90,13 +90,13 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
var filters = new List<(string, string?)> { ("slug", config.Site) };
if (!string.IsNullOrWhiteSpace(config.Region)) filters.Add(("region", config.Region));
return await client.FindOne("dcim/sites", filters.ToArray())
- ?? throw new InvalidOperationException($"Standort '{config.Site}' (Region '{config.Region}') fehlt in NetBox.");
+ ?? throw new InvalidOperationException($"Site '{config.Site}' (region '{config.Region}') does not exist in NetBox.");
}
private async Task ResolveLocation(NetBoxObject? site)
{
if (string.IsNullOrWhiteSpace(config.Location)) return null;
return await client.FindOne("dcim/locations", ("slug", config.Location), ("site_id", site?.Id.ToString()))
- ?? throw new InvalidOperationException($"Lokation '{config.Location}' fehlt in NetBox.");
+ ?? throw new InvalidOperationException($"Location '{config.Location}' does not exist in NetBox.");
}
private async Task EnsureManufacturer(string name, bool dryRun)
{
@@ -117,7 +117,7 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
private Dictionary BuildCustomFields(HardwareInfo hw)
{
var available = new Dictionary {
- ["agent_version"] = "0.1.0", ["windows_version"] = hw.WindowsVersion,
+ ["agent_version"] = AgentInfo.Version, ["windows_version"] = hw.WindowsVersion,
["device_uuid"] = hw.Uuid, ["last_sync"] = DateTimeOffset.UtcNow.ToString("O")
};
return config.CustomFields.Where(x => available.ContainsKey(x.Key)).ToDictionary(x => x.Value, x => available[x.Key]);
@@ -125,17 +125,17 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
private static string HardwareSummary(HardwareInfo hw)
{
var lines = new List {
- "Automatisch durch NetBox Windows Agent aktualisiert.", "", "## Hardware",
- $"- System: {hw.Manufacturer} {hw.Model}", $"- Seriennummer: {hw.Serial}", $"- UUID: {hw.Uuid}",
- $"- Betriebssystem: {hw.WindowsCaption} {hw.WindowsVersion} ({hw.Architecture})",
- $"- CPU: {hw.Processor}", $"- RAM: {hw.MemoryBytes / 1073741824d:F1} GiB", "", "### Datenträger"
+ "Updated automatically by the NetBox Windows Agent.", "", "## Hardware",
+ $"- System: {hw.Manufacturer} {hw.Model}", $"- Serial number: {hw.Serial}", $"- UUID: {hw.Uuid}",
+ $"- Operating system: {hw.WindowsCaption} {hw.WindowsVersion} ({hw.Architecture})",
+ $"- CPU: {hw.Processor}", $"- RAM: {hw.MemoryBytes / 1073741824d:F1} GiB", "", "### Disks"
};
lines.AddRange(hw.Disks.Select(d => $"- {d.Model} — {d.SizeBytes / 1000000000d:F0} GB — S/N {d.Serial} — {d.DeviceId}"));
- lines.AddRange(["", "### Netzwerk"]);
+ lines.AddRange(["", "### Network"]);
lines.AddRange(hw.Networks.Select(n => $"- {n.Name} — {n.MacAddress} — {string.Join(", ", n.IpAddresses)}"));
if (hw.Software.Count > 0)
{
- lines.AddRange(["", $"## Installierte Software ({hw.Software.Count})"]);
+ lines.AddRange(["", $"## Installed software ({hw.Software.Count})"]);
lines.AddRange(hw.Software.Select(s => $"- {s.Name}{(string.IsNullOrWhiteSpace(s.Version) ? "" : $" {s.Version}")}{(string.IsNullOrWhiteSpace(s.Publisher) ? "" : $" — {s.Publisher}")}"));
}
return string.Join('\n', lines);