feat: listen mode for scanning by the NetBox Synchronizer, Intune and GPO deployment
Build Windows agent / build (win-arm64) (push) Canceled after 0s
Build Windows agent / build (win-x64) (push) Canceled after 0s

- New "mode" setting: "netbox" (default, unchanged), "listen" (no NetBox access needed; the
  inventory is served on a TCP port for the NetBox Synchronizer desktop app) or "both"
- Listen protocol v1: HMAC-SHA256 signed requests with nonce and timestamp, AES-256-GCM encrypted
  inventory, optional allowed_networks; the inventory has the shape of the desktop app's WinRM scan
- New options --serve, --print and --version
- install.ps1 sets up the listener task (at startup, restarted on failure) and the firewall rule for
  listen mode, removes what a changed mode no longer needs and stays idempotent
- New gpo-startup.ps1 for Group Policy startup scripts: installs or updates from a share only when
  agent.exe or config.json changed
- README, messages and scripts in English

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 11:01:46 +01:00
1 parent d632f0d383
commit 0098b49787
14 files changed
+791 -93

No files matched your search

+73 -10
View File
@@ -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<NicInfo> 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<NicInfo>();
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<SoftwareInfo> 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<ManagementBaseObject> 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<string> Strings(ManagementBaseObject x, string key) =>
(x[key] as string[] ?? []).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
}
+204
View File
@@ -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;
/// <summary>
/// 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&amp;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.
/// </summary>
internal sealed class InventoryServer(AgentConfig config, Func<HardwareInfo> 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<string, long> _nonces = new();
private readonly List<IPNetwork> _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<byte[]> 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<string, string> 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<string, string>(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<string, string> ParseQuery(string target)
{
var result = new Dictionary<string, string>();
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 });
}
/// <summary>Inventory in the shape of the WinRM scan of the desktop app, plus agent-only details.</summary>
internal static class InventoryDocument
{
public static Dictionary<string, object?> 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,
};
}
+75 -8
View File
@@ -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<string> Tags { get; set; } = [];
[JsonPropertyName("custom_fields")] public Dictionary<string, string> 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<string> 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<DiskInfo> Disks, IReadOnlyList<NetworkInfo> Networks,
IReadOnlyList<MemoryInfo> MemoryModules, IReadOnlyList<SoftwareInfo> 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<int> 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<DiskInfo> Disks { get; init; } = [];
public IReadOnlyList<NetworkInfo> Networks { get; init; } = [];
public IReadOnlyList<NicInfo> Nics { get; init; } = [];
public IReadOnlyList<MemoryInfo> MemoryModules { get; init; } = [];
public IReadOnlyList<SoftwareInfo> 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<string> 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<string> Ips,
[property: JsonPropertyName("masks")] IReadOnlyList<string> Masks,
[property: JsonPropertyName("gateway")] IReadOnlyList<string> Gateway,
[property: JsonPropertyName("dhcp")] bool Dhcp,
[property: JsonPropertyName("physical")] bool Physical,
[property: JsonPropertyName("speed")] ulong Speed);
internal sealed class Page<T>
{
+3 -3
View File
@@ -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<NetBoxObject?> 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<Page<NetBoxObject>>(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<T>(body, _json) ?? throw new InvalidOperationException("NetBox lieferte eine leere Antwort.");
return JsonSerializer.Deserialize<T>(body, _json) ?? throw new InvalidOperationException("NetBox returned an empty response.");
}
public void Dispose() => _http.Dispose();
}
+57 -15
View File
@@ -7,36 +7,78 @@ static async Task<int> 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<AgentConfig>(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<string>();
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
""");
+11 -11
View File
@@ -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<string, object?> {
["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<NetBoxObject?> 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<NetBoxObject> EnsureManufacturer(string name, bool dryRun)
{
@@ -117,7 +117,7 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
private Dictionary<string, object> BuildCustomFields(HardwareInfo hw)
{
var available = new Dictionary<string, object> {
["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<string> {
"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);