feat: Phase 8 — Network Discovery + Windows Dev-Setup-Skripte

Network Discovery:
- Go Agent: internal/scanner/scanner.go mit TCP-Sweep (Port 445/80/22/443),
  ARP-Tabellen-Parser (Windows: arp -a, Linux: /proc/net/arp), Reverse-DNS,
  50 gleichzeitige Goroutines mit Semaphore
- Go Agent main.go: COMMAND_TYPE_NETWORK_SCAN Case → scanner.Scan() → JSON stdout
- Backend: NetworkDevice Model (Id, AgentId, IpAddress, MacAddress, Hostname,
  Vendor, IsManaged, FirstSeen, LastSeen)
- Backend: EF Migration AddNetworkDevices + Index auf IpAddress + MacAddress
- Backend: NetworkDevicesController GET /api/v1/network-devices + DELETE /{id}
- Backend: AgentGrpcService.ProcessNetworkScanResultAsync — upsert via MAC,
  IsManaged=true wenn IP einem bekannten Agent entspricht
- Frontend: NetworkPage.tsx mit Scan-Panel, Device-Tabelle, Filter, Delete
- Frontend: App.tsx — 'Netzwerk' Nav-Eintrag mit Network Icon

Windows Dev-Setup:
- dev-start.ps1 — Startet Docker/Postgres, EF-Migrationen, Backend+Frontend
  in separaten PowerShell-Fenstern; Voraussetzungen-Check (docker/dotnet/node/go)
- dev-stop.ps1 — Stoppt alle NexusRMM-Prozesse + PostgreSQL Container
- build-agent.ps1 — Baut nexus-agent.exe (Windows) + optional nexus-agent-linux

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Claude Agent
2026-03-19 14:53:35 +01:00
parent 55e016c07d
commit 4c40e88718
16 changed files with 1733 additions and 13 deletions

View File

@@ -2,6 +2,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
@@ -16,6 +17,7 @@ import (
"nexusrmm.local/agent/internal/deployer"
"nexusrmm.local/agent/internal/executor"
"nexusrmm.local/agent/internal/meshagent"
"nexusrmm.local/agent/internal/scanner"
pb "nexusrmm.local/agent/pkg/proto"
)
@@ -142,6 +144,21 @@ func executeCommand(ctx context.Context, client *connection.GrpcClient, agentID
result = deployer.Install(ctx, cmd.Payload)
case pb.CommandType_COMMAND_TYPE_UNINSTALL_SOFTWARE:
result = deployer.Uninstall(ctx, cmd.Payload)
case pb.CommandType_COMMAND_TYPE_NETWORK_SCAN:
var params struct {
Subnet string `json:"subnet"`
}
_ = json.Unmarshal([]byte(cmd.Payload), &params)
devices, err := scanner.Scan(ctx, params.Subnet)
if err != nil {
result = &executor.Result{ExitCode: 1, Stderr: err.Error()}
} else {
result = &executor.Result{
ExitCode: 0,
Stdout: scanner.ToJSON(devices),
Success: true,
}
}
default:
result = &executor.Result{ExitCode: -1, Stderr: fmt.Sprintf("unknown command type: %v", cmd.Type)}
}

View File

@@ -0,0 +1,274 @@
package scanner
import (
"context"
"encoding/json"
"fmt"
"net"
"os/exec"
"runtime"
"strings"
"sync"
"time"
)
// Device represents a discovered network device.
type Device struct {
IP string `json:"ip"`
MAC string `json:"mac"`
Hostname string `json:"hostname"`
Vendor string `json:"vendor"`
}
// Scan scans the given subnet (e.g. "192.168.1.0/24").
// If subnet is empty, the local network is auto-detected.
func Scan(ctx context.Context, subnet string) ([]Device, error) {
// Auto-detect subnet if not provided
if subnet == "" {
detected, err := detectLocalSubnet()
if err != nil {
return nil, fmt.Errorf("auto-detect subnet: %w", err)
}
subnet = detected
}
// Parse CIDR
_, ipNet, err := net.ParseCIDR(subnet)
if err != nil {
return nil, fmt.Errorf("parse subnet %q: %w", subnet, err)
}
// Collect all host IPs in the subnet
hosts := hostsInNet(ipNet)
// Concurrent ping sweep using TCP fallback (no raw ICMP needed)
const maxConcurrent = 50
sem := make(chan struct{}, maxConcurrent)
var mu sync.Mutex
alive := make(map[string]bool)
var wg sync.WaitGroup
for _, ip := range hosts {
// Check context before spawning
select {
case <-ctx.Done():
break
default:
}
wg.Add(1)
sem <- struct{}{}
go func(ipStr string) {
defer wg.Done()
defer func() { <-sem }()
if isAlive(ipStr) {
mu.Lock()
alive[ipStr] = true
mu.Unlock()
}
}(ip.String())
}
wg.Wait()
if len(alive) == 0 {
return []Device{}, nil
}
// Read ARP table to get MAC addresses
arpTable, err := readARPTable()
if err != nil {
// Non-fatal: continue without MAC info
arpTable = map[string]string{}
}
// Build results with reverse DNS lookups
var devices []Device
for ip := range alive {
d := Device{IP: ip}
if mac, ok := arpTable[ip]; ok {
d.MAC = mac
}
// Reverse DNS lookup with short timeout
hostname := reverseLookup(ip)
d.Hostname = hostname
devices = append(devices, d)
}
return devices, nil
}
// ToJSON serialises a slice of Devices to a JSON string.
func ToJSON(devices []Device) string {
b, _ := json.Marshal(devices)
return string(b)
}
// detectLocalSubnet returns the CIDR of the first non-loopback IPv4 interface.
func detectLocalSubnet() (string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, iface := range ifaces {
if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
var ip net.IP
var mask net.IPMask
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
mask = v.Mask
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue
}
// Reconstruct CIDR from network address
network := ip.Mask(mask)
ones, _ := mask.Size()
return fmt.Sprintf("%s/%d", network.String(), ones), nil
}
}
return "", fmt.Errorf("no suitable network interface found")
}
// hostsInNet returns all usable host addresses within the given network.
func hostsInNet(ipNet *net.IPNet) []net.IP {
var ips []net.IP
// Start from network address, increment
ip := cloneIP(ipNet.IP)
// Increment past network address
inc(ip)
for ipNet.Contains(ip) {
// Skip broadcast (last address)
next := cloneIP(ip)
inc(next)
if !ipNet.Contains(next) {
break // current ip is broadcast, stop
}
ips = append(ips, cloneIP(ip))
inc(ip)
}
return ips
}
func cloneIP(ip net.IP) net.IP {
clone := make(net.IP, len(ip))
copy(clone, ip)
return clone
}
func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
// isAlive attempts a TCP connection to common ports to determine if a host is up.
func isAlive(ip string) bool {
timeout := 300 * time.Millisecond
ports := []string{"445", "80", "22", "443"}
for _, port := range ports {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), timeout)
if err == nil {
conn.Close()
return true
}
}
return false
}
// readARPTable reads the ARP cache and returns a map of IP -> MAC.
func readARPTable() (map[string]string, error) {
table := make(map[string]string)
if runtime.GOOS == "windows" {
return readARPWindows(table)
}
return readARPLinux(table)
}
// readARPWindows parses `arp -a` output on Windows.
// Example line: " 192.168.1.1 aa-bb-cc-dd-ee-ff dynamic"
func readARPWindows(table map[string]string) (map[string]string, error) {
out, err := exec.Command("arp", "-a").Output()
if err != nil {
return table, err
}
for _, line := range strings.Split(string(out), "\n") {
line = strings.TrimSpace(line)
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
ip := fields[0]
if net.ParseIP(ip) == nil {
continue
}
mac := fields[1]
// Normalise aa-bb-cc-dd-ee-ff → aa:bb:cc:dd:ee:ff
mac = strings.ReplaceAll(mac, "-", ":")
if len(mac) == 17 {
table[ip] = mac
}
}
return table, nil
}
// readARPLinux parses /proc/net/arp on Linux.
// Format: IP address HW type Flags HW address Mask Device
func readARPLinux(table map[string]string) (map[string]string, error) {
data, err := readFile("/proc/net/arp")
if err != nil {
return table, err
}
lines := strings.Split(string(data), "\n")
// Skip header line
for _, line := range lines[1:] {
fields := strings.Fields(line)
if len(fields) < 4 {
continue
}
ip := fields[0]
mac := fields[3]
if net.ParseIP(ip) != nil && len(mac) == 17 && mac != "00:00:00:00:00:00" {
table[ip] = mac
}
}
return table, nil
}
// readFile is a thin wrapper so we can test Linux ARP parsing on any OS.
func readFile(path string) ([]byte, error) {
return exec.Command("cat", path).Output()
}
// reverseLookup returns the hostname for an IP via reverse DNS, with a short timeout.
func reverseLookup(ip string) string {
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
names, err := net.DefaultResolver.LookupAddr(ctx, ip)
if err != nil || len(names) == 0 {
return ""
}
// Strip trailing dot from FQDN
return strings.TrimSuffix(names[0], ".")
}

View File

@@ -0,0 +1,52 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NexusRMM.Infrastructure.Data;
namespace NexusRMM.Api.Controllers;
[ApiController]
[Route("api/v1/network-devices")]
public class NetworkDevicesController : ControllerBase
{
private readonly RmmDbContext _db;
public NetworkDevicesController(RmmDbContext db) => _db = db;
[HttpGet]
public async Task<IActionResult> GetAll([FromQuery] Guid? agentId)
{
var query = _db.NetworkDevices.AsQueryable();
if (agentId.HasValue)
query = query.Where(d => d.AgentId == agentId.Value);
var devices = await query
.OrderBy(d => d.IpAddress)
.Select(d => new
{
d.Id,
d.AgentId,
d.IpAddress,
d.MacAddress,
d.Hostname,
d.Vendor,
d.IsManaged,
d.FirstSeen,
d.LastSeen
})
.ToListAsync();
return Ok(devices);
}
[HttpDelete("{id:int}")]
public async Task<IActionResult> Delete(int id)
{
var device = await _db.NetworkDevices.FindAsync(id);
if (device is null)
return NotFound();
_db.NetworkDevices.Remove(device);
await _db.SaveChangesAsync();
return NoContent();
}
}

View File

@@ -114,12 +114,12 @@ public class AgentGrpcService : AgentService.AgentServiceBase
public override async Task<CommandResultResponse> ReportCommandResult(CommandResult request, ServerCallContext context)
{
var taskId = Guid.Parse(request.CommandId);
var task = await _db.Tasks.FindAsync(taskId)
var taskItem = await _db.Tasks.FindAsync(taskId)
?? throw new RpcException(new Status(StatusCode.NotFound, "Task not found"));
task.Status = request.Success ? CoreTaskStatus.Completed : CoreTaskStatus.Failed;
task.CompletedAt = DateTime.UtcNow;
task.Result = JsonSerializer.SerializeToElement(new
taskItem.Status = request.Success ? CoreTaskStatus.Completed : CoreTaskStatus.Failed;
taskItem.CompletedAt = DateTime.UtcNow;
taskItem.Result = JsonSerializer.SerializeToElement(new
{
request.ExitCode,
request.Stdout,
@@ -129,6 +129,11 @@ public class AgentGrpcService : AgentService.AgentServiceBase
await _db.SaveChangesAsync();
if (taskItem.Type == NexusRMM.Core.Models.TaskType.NetworkScan && request.Success && !string.IsNullOrWhiteSpace(request.Stdout))
{
await ProcessNetworkScanResultAsync(request.AgentId, request.Stdout);
}
// SignalR: Command-Ergebnis an agent-Gruppe pushen
await _hub.Clients.Group($"agent-{request.AgentId}")
.CommandResultUpdated(request.CommandId, request.AgentId, request.Success, request.ExitCode);
@@ -136,6 +141,73 @@ public class AgentGrpcService : AgentService.AgentServiceBase
return new CommandResultResponse();
}
private async Task ProcessNetworkScanResultAsync(string agentIdStr, string stdout)
{
try
{
var scannedDevices = JsonSerializer.Deserialize<List<ScanDevice>>(stdout, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (scannedDevices is null || scannedDevices.Count == 0)
return;
Guid? agentId = Guid.TryParse(agentIdStr, out var parsedId) ? parsedId : null;
var knownAgentIps = await _db.Agents
.Select(a => a.IpAddress)
.Where(ip => ip != null && ip != string.Empty)
.ToHashSetAsync();
var now = DateTime.UtcNow;
foreach (var scanned in scannedDevices)
{
if (string.IsNullOrWhiteSpace(scanned.Mac))
continue;
var existing = await _db.NetworkDevices
.FirstOrDefaultAsync(d => d.MacAddress == scanned.Mac);
if (existing is not null)
{
existing.LastSeen = now;
existing.IpAddress = scanned.Ip ?? existing.IpAddress;
existing.IsManaged = knownAgentIps.Contains(scanned.Ip ?? string.Empty);
}
else
{
_db.NetworkDevices.Add(new NexusRMM.Core.Models.NetworkDevice
{
AgentId = agentId,
IpAddress = scanned.Ip ?? string.Empty,
MacAddress = scanned.Mac,
Hostname = scanned.Hostname ?? string.Empty,
Vendor = scanned.Vendor ?? string.Empty,
IsManaged = knownAgentIps.Contains(scanned.Ip ?? string.Empty),
FirstSeen = now,
LastSeen = now
});
}
}
await _db.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to process NetworkScan result for agent {AgentId}", agentIdStr);
}
}
private class ScanDevice
{
public string? Ip { get; set; }
public string? Mac { get; set; }
public string? Hostname { get; set; }
public string? Vendor { get; set; }
}
private static CommandType MapTaskType(NexusRMM.Core.Models.TaskType type) => type switch
{
NexusRMM.Core.Models.TaskType.Shell => CommandType.Shell,

View File

@@ -0,0 +1,14 @@
namespace NexusRMM.Core.Models;
public class NetworkDevice
{
public int Id { get; set; }
public Guid? AgentId { get; set; } // Welcher Agent hat es entdeckt
public string IpAddress { get; set; } = string.Empty;
public string MacAddress { get; set; } = string.Empty;
public string Hostname { get; set; } = string.Empty;
public string Vendor { get; set; } = string.Empty;
public bool IsManaged { get; set; } // Ist dieses Gerät ein bekannter RMM-Agent?
public DateTime FirstSeen { get; set; }
public DateTime LastSeen { get; set; }
}

View File

@@ -14,6 +14,7 @@ public class RmmDbContext : DbContext
public DbSet<AlertRule> AlertRules => Set<AlertRule>();
public DbSet<Alert> Alerts => Set<Alert>();
public DbSet<SoftwarePackage> SoftwarePackages => Set<SoftwarePackage>();
public DbSet<NetworkDevice> NetworkDevices => Set<NetworkDevice>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -65,5 +66,12 @@ public class RmmDbContext : DbContext
e.HasKey(p => p.Id);
e.HasIndex(p => new { p.Name, p.Version, p.OsType }).IsUnique();
});
modelBuilder.Entity<NetworkDevice>(e =>
{
e.HasKey(d => d.Id);
e.HasIndex(d => d.IpAddress);
e.HasIndex(d => d.MacAddress);
});
}
}

View File

@@ -0,0 +1,413 @@
// <auto-generated />
using System;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NexusRMM.Infrastructure.Data;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace NexusRMM.Infrastructure.Migrations
{
[DbContext(typeof(RmmDbContext))]
[Migration("20260319135017_AddNetworkDevices")]
partial class AddNetworkDevices
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("NexusRMM.Core.Models.Agent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AgentVersion")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EnrolledAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("IpAddress")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("LastSeen")
.HasColumnType("timestamp with time zone");
b.Property<string>("MacAddress")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MeshAgentId")
.HasColumnType("text");
b.Property<int>("OsType")
.HasColumnType("integer");
b.Property<string>("OsVersion")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Status")
.HasColumnType("integer");
b.PrimitiveCollection<string>("Tags")
.IsRequired()
.HasColumnType("jsonb");
b.HasKey("Id");
b.HasIndex("Hostname");
b.HasIndex("MacAddress");
b.ToTable("Agents");
});
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<Guid>("AgentId")
.HasColumnType("uuid");
b.Property<JsonElement>("Metrics")
.HasColumnType("jsonb");
b.Property<DateTime>("Timestamp")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AgentId");
b.HasIndex("Timestamp");
b.ToTable("AgentMetrics");
});
modelBuilder.Entity("NexusRMM.Core.Models.Alert", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<bool>("Acknowledged")
.HasColumnType("boolean");
b.Property<Guid>("AgentId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Message")
.IsRequired()
.HasColumnType("text");
b.Property<int>("RuleId")
.HasColumnType("integer");
b.Property<int>("Severity")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AgentId");
b.HasIndex("CreatedAt");
b.HasIndex("RuleId");
b.ToTable("Alerts");
});
modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<string>("MetricPath")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Operator")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Severity")
.HasColumnType("integer");
b.Property<double>("Threshold")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("AlertRules");
});
modelBuilder.Entity("NexusRMM.Core.Models.NetworkDevice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<Guid?>("AgentId")
.HasColumnType("uuid");
b.Property<DateTime>("FirstSeen")
.HasColumnType("timestamp with time zone");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("IpAddress")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsManaged")
.HasColumnType("boolean");
b.Property<DateTime>("LastSeen")
.HasColumnType("timestamp with time zone");
b.Property<string>("MacAddress")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Vendor")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("IpAddress");
b.HasIndex("MacAddress");
b.ToTable("NetworkDevices");
});
modelBuilder.Entity("NexusRMM.Core.Models.SoftwarePackage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Checksum")
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("InstallerUrl")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("OsType")
.HasColumnType("integer");
b.Property<string>("PackageManager")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PackageName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SilentArgs")
.HasColumnType("text");
b.Property<string>("Version")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Name", "Version", "OsType")
.IsUnique();
b.ToTable("SoftwarePackages");
});
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AgentId")
.HasColumnType("uuid");
b.Property<DateTime?>("CompletedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<JsonElement?>("Payload")
.HasColumnType("jsonb");
b.Property<JsonElement?>("Result")
.HasColumnType("jsonb");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AgentId");
b.ToTable("Tasks");
});
modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<Guid?>("AgentId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Priority")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AgentId");
b.ToTable("Tickets");
});
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>
{
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
.WithMany("Metrics")
.HasForeignKey("AgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Agent");
});
modelBuilder.Entity("NexusRMM.Core.Models.Alert", b =>
{
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
.WithMany("Alerts")
.HasForeignKey("AgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("NexusRMM.Core.Models.AlertRule", "Rule")
.WithMany("Alerts")
.HasForeignKey("RuleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Agent");
b.Navigation("Rule");
});
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
{
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
.WithMany("Tasks")
.HasForeignKey("AgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Agent");
});
modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b =>
{
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
.WithMany("Tickets")
.HasForeignKey("AgentId");
b.Navigation("Agent");
});
modelBuilder.Entity("NexusRMM.Core.Models.Agent", b =>
{
b.Navigation("Alerts");
b.Navigation("Metrics");
b.Navigation("Tasks");
b.Navigation("Tickets");
});
modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b =>
{
b.Navigation("Alerts");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,53 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace NexusRMM.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddNetworkDevices : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "NetworkDevices",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
AgentId = table.Column<Guid>(type: "uuid", nullable: true),
IpAddress = table.Column<string>(type: "text", nullable: false),
MacAddress = table.Column<string>(type: "text", nullable: false),
Hostname = table.Column<string>(type: "text", nullable: false),
Vendor = table.Column<string>(type: "text", nullable: false),
IsManaged = table.Column<bool>(type: "boolean", nullable: false),
FirstSeen = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
LastSeen = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_NetworkDevices", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_NetworkDevices_IpAddress",
table: "NetworkDevices",
column: "IpAddress");
migrationBuilder.CreateIndex(
name: "IX_NetworkDevices_MacAddress",
table: "NetworkDevices",
column: "MacAddress");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "NetworkDevices");
}
}
}

View File

@@ -74,7 +74,7 @@ namespace NexusRMM.Infrastructure.Migrations
b.HasIndex("MacAddress");
b.ToTable("Agents", (string)null);
b.ToTable("Agents");
});
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>
@@ -100,7 +100,7 @@ namespace NexusRMM.Infrastructure.Migrations
b.HasIndex("Timestamp");
b.ToTable("AgentMetrics", (string)null);
b.ToTable("AgentMetrics");
});
modelBuilder.Entity("NexusRMM.Core.Models.Alert", b =>
@@ -138,7 +138,7 @@ namespace NexusRMM.Infrastructure.Migrations
b.HasIndex("RuleId");
b.ToTable("Alerts", (string)null);
b.ToTable("Alerts");
});
modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b =>
@@ -172,7 +172,52 @@ namespace NexusRMM.Infrastructure.Migrations
b.HasKey("Id");
b.ToTable("AlertRules", (string)null);
b.ToTable("AlertRules");
});
modelBuilder.Entity("NexusRMM.Core.Models.NetworkDevice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<Guid?>("AgentId")
.HasColumnType("uuid");
b.Property<DateTime>("FirstSeen")
.HasColumnType("timestamp with time zone");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("IpAddress")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsManaged")
.HasColumnType("boolean");
b.Property<DateTime>("LastSeen")
.HasColumnType("timestamp with time zone");
b.Property<string>("MacAddress")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Vendor")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("IpAddress");
b.HasIndex("MacAddress");
b.ToTable("NetworkDevices");
});
modelBuilder.Entity("NexusRMM.Core.Models.SoftwarePackage", b =>
@@ -219,7 +264,7 @@ namespace NexusRMM.Infrastructure.Migrations
b.HasIndex("Name", "Version", "OsType")
.IsUnique();
b.ToTable("SoftwarePackages", (string)null);
b.ToTable("SoftwarePackages");
});
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
@@ -253,7 +298,7 @@ namespace NexusRMM.Infrastructure.Migrations
b.HasIndex("AgentId");
b.ToTable("Tasks", (string)null);
b.ToTable("Tasks");
});
modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b =>
@@ -291,7 +336,7 @@ namespace NexusRMM.Infrastructure.Migrations
b.HasIndex("AgentId");
b.ToTable("Tickets", (string)null);
b.ToTable("Tickets");
});
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>

View File

@@ -1,11 +1,12 @@
import { useState } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { LayoutDashboard, Ticket, Bell, Package, Menu, X } from 'lucide-react'
import { LayoutDashboard, Ticket, Bell, Package, Network, Menu, X } from 'lucide-react'
import { DashboardPage } from './pages/DashboardPage'
import { AgentDetailPage } from './pages/AgentDetailPage'
import TicketsPage from './pages/TicketsPage'
import AlertsPage from './pages/AlertsPage'
import SoftwarePage from './pages/SoftwarePage'
import NetworkPage from './pages/NetworkPage'
import { cn } from './lib/utils'
const queryClient = new QueryClient({
@@ -17,7 +18,7 @@ const queryClient = new QueryClient({
},
})
type Page = 'dashboard' | 'agent-detail' | 'tickets' | 'alerts' | 'software'
type Page = 'dashboard' | 'agent-detail' | 'tickets' | 'alerts' | 'network' | 'software'
interface NavItem {
id: Page
@@ -29,6 +30,7 @@ const navItems: NavItem[] = [
{ id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard size={18} /> },
{ id: 'tickets', label: 'Tickets', icon: <Ticket size={18} /> },
{ id: 'alerts', label: 'Alerts', icon: <Bell size={18} /> },
{ id: 'network', label: 'Netzwerk', icon: <Network size={18} /> },
{ id: 'software', label: 'Software', icon: <Package size={18} /> },
]
@@ -112,6 +114,7 @@ function AppContent() {
)}
{page === 'tickets' && <TicketsPage />}
{page === 'alerts' && <AlertsPage />}
{page === 'network' && <NetworkPage />}
{page === 'software' && <SoftwarePage />}
</main>
</div>

View File

@@ -15,6 +15,7 @@ import type {
DeployRequest,
DeployResponse,
RemoteSessionInfo,
NetworkDevice,
} from './types'
const BASE_URL = '/api/v1'
@@ -104,3 +105,22 @@ export const remoteDesktopApi = {
getSession: (agentId: string) =>
request<RemoteSessionInfo>(`/agents/${agentId}/remote-session`),
}
// Network Devices
export const networkDevicesApi = {
list: (agentId?: string) => {
const param = agentId ? `?agentId=${agentId}` : ''
return request<NetworkDevice[]>(`/network-devices${param}`)
},
delete: (id: number) =>
request<void>(`/network-devices/${id}`, { method: 'DELETE' }),
}
// Network Scan triggern (nutzt tasksApi intern)
export const networkScanApi = {
trigger: (agentId: string, subnet?: string) =>
request<TaskItem>('/tasks', {
method: 'POST',
body: JSON.stringify({ agentId, type: 'NetworkScan', payload: { subnet: subnet ?? '' } }),
}),
}

View File

@@ -184,3 +184,15 @@ export interface RemoteSessionInfo {
sessionUrl?: string
meshCentralBaseUrl?: string
}
export interface NetworkDevice {
id: number
agentId: string | null
ipAddress: string
macAddress: string
hostname: string
vendor: string
isManaged: boolean
firstSeen: string
lastSeen: string
}

View File

@@ -0,0 +1,285 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Network, Trash2, Play, Wifi, WifiOff } from 'lucide-react'
import { networkDevicesApi, networkScanApi } from '../api/client'
import { cn } from '../lib/utils'
function formatRelativeTime(dateString: string): string {
const now = new Date()
const date = new Date(dateString)
const diffMs = now.getTime() - date.getTime()
const diffSeconds = Math.floor(diffMs / 1000)
const diffMinutes = Math.floor(diffSeconds / 60)
const diffHours = Math.floor(diffMinutes / 60)
const diffDays = Math.floor(diffHours / 24)
if (diffSeconds < 60) {
return 'gerade eben'
}
if (diffMinutes < 60) {
return `vor ${diffMinutes} Min.`
}
if (diffHours < 24) {
return `vor ${diffHours} Std.`
}
return `vor ${diffDays} Tagen`
}
export default function NetworkPage() {
const [agentIdInput, setAgentIdInput] = useState('')
const [subnetInput, setSubnetInput] = useState('')
const [filterUnknown, setFilterUnknown] = useState(false)
const [isScanPending, setIsScanPending] = useState(false)
const queryClient = useQueryClient()
const devicesQuery = useQuery({
queryKey: ['networkDevices'],
queryFn: () => networkDevicesApi.list(),
})
const scanMutation = useMutation({
mutationFn: ({ agentId, subnet }: { agentId: string; subnet?: string }) =>
networkScanApi.trigger(agentId, subnet),
onSuccess: () => {
setIsScanPending(true)
// Refresh after a brief delay to show updated results
setTimeout(() => {
queryClient.invalidateQueries({ queryKey: ['networkDevices'] })
setIsScanPending(false)
}, 3000)
},
onError: () => {
setIsScanPending(false)
},
})
const deleteMutation = useMutation({
mutationFn: (id: number) => networkDevicesApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['networkDevices'] })
},
})
const handleScan = () => {
if (!agentIdInput.trim()) return
setIsScanPending(true)
scanMutation.mutate({
agentId: agentIdInput.trim(),
subnet: subnetInput.trim() || undefined,
})
}
const handleDelete = (id: number) => {
if (window.confirm('Möchten Sie dieses Gerät wirklich löschen?')) {
deleteMutation.mutate(id)
}
}
const devices = devicesQuery.data ?? []
const filteredDevices = filterUnknown
? devices.filter((d) => !d.isManaged)
: devices
return (
<div className="space-y-6 p-6">
{/* Header */}
<div className="flex items-center gap-3">
<Network size={24} className="text-primary" />
<div>
<h1 className="text-3xl font-bold text-foreground">Netzwerk-Discovery</h1>
<p className="text-muted-foreground text-sm mt-1">
Geräte im Netzwerk erkennen und verwalten
</p>
</div>
</div>
{/* Scan Panel */}
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">Netzwerk-Scan starten</h2>
<div className="flex flex-col sm:flex-row gap-3">
<input
type="text"
value={agentIdInput}
onChange={(e) => setAgentIdInput(e.target.value)}
placeholder="Agent-ID (erforderlich)"
className="flex-1 bg-background border border-border rounded-lg px-3 py-2 text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
/>
<input
type="text"
value={subnetInput}
onChange={(e) => setSubnetInput(e.target.value)}
placeholder="Subnetz (optional, z.B. 192.168.1.0/24)"
className="flex-1 bg-background border border-border rounded-lg px-3 py-2 text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
/>
<button
onClick={handleScan}
disabled={!agentIdInput.trim() || scanMutation.isPending || isScanPending}
className={cn(
'flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap',
)}
>
<Play size={16} />
{isScanPending ? 'Scan läuft...' : 'Scan starten'}
</button>
</div>
{scanMutation.isError && (
<p className="text-red-400 text-sm mt-2">
Fehler beim Starten des Scans: {String(scanMutation.error)}
</p>
)}
{isScanPending && !scanMutation.isError && (
<p className="text-muted-foreground text-sm mt-2 flex items-center gap-2">
<span className="inline-block w-2 h-2 rounded-full bg-primary animate-pulse" />
Scan wurde gestartet. Ergebnisse werden in Kürze aktualisiert...
</p>
)}
</div>
{/* Results Table */}
<div className="bg-card border border-border rounded-lg p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold text-foreground">
Erkannte Geräte
{devicesQuery.isSuccess && (
<span className="ml-2 text-sm font-normal text-muted-foreground">
({filteredDevices.length} von {devices.length})
</span>
)}
</h2>
{/* Filter Toggle */}
<div className="flex gap-2">
<button
onClick={() => setFilterUnknown(false)}
className={cn(
'px-3 py-1 rounded text-sm transition-colors',
!filterUnknown
? 'bg-primary text-primary-foreground'
: 'bg-accent text-foreground hover:bg-accent/80',
)}
>
Alle
</button>
<button
onClick={() => setFilterUnknown(true)}
className={cn(
'px-3 py-1 rounded text-sm transition-colors',
filterUnknown
? 'bg-primary text-primary-foreground'
: 'bg-accent text-foreground hover:bg-accent/80',
)}
>
Nur unbekannte Geräte
</button>
</div>
</div>
{/* Loading State */}
{devicesQuery.isLoading && (
<p className="text-muted-foreground py-4">Lädt...</p>
)}
{/* Error State */}
{devicesQuery.isError && (
<p className="text-red-400 py-4">
Fehler beim Laden der Geräte
</p>
)}
{/* Empty State */}
{devicesQuery.isSuccess && filteredDevices.length === 0 && (
<div className="text-center py-12 text-muted-foreground">
<Network size={40} className="mx-auto mb-3 opacity-30" />
<p>
{filterUnknown
? 'Keine unbekannten Geräte gefunden'
: 'Keine Geräte gefunden. Starten Sie einen Scan.'}
</p>
</div>
)}
{/* Table */}
{devicesQuery.isSuccess && filteredDevices.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="bg-accent border-b border-border">
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
IP-Adresse
</th>
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
MAC-Adresse
</th>
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
Hostname
</th>
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
Hersteller
</th>
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
Status
</th>
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
Zuletzt gesehen
</th>
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
Aktion
</th>
</tr>
</thead>
<tbody>
{filteredDevices.map((device) => (
<tr
key={device.id}
className="border-b border-border hover:bg-card/50 transition-colors"
>
<td className="px-4 py-3 font-mono text-foreground">
{device.ipAddress}
</td>
<td className="px-4 py-3 font-mono text-xs text-muted-foreground">
{device.macAddress || '—'}
</td>
<td className="px-4 py-3 text-foreground">
{device.hostname || '—'}
</td>
<td className="px-4 py-3 text-muted-foreground">
{device.vendor || '—'}
</td>
<td className="px-4 py-3">
{device.isManaged ? (
<span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-500/20 text-green-400 border border-green-500/30">
<Wifi size={12} />
Verwaltet
</span>
) : (
<span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-muted/50 text-muted-foreground border border-border">
<WifiOff size={12} />
Unbekannt
</span>
)}
</td>
<td className="px-4 py-3 text-muted-foreground text-xs">
{formatRelativeTime(device.lastSeen)}
</td>
<td className="px-4 py-3">
<button
onClick={() => handleDelete(device.id)}
disabled={deleteMutation.isPending}
className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50"
>
<Trash2 size={12} />
Löschen
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
)
}

169
build-agent.ps1 Normal file
View File

@@ -0,0 +1,169 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Baut den NexusRMM Agent für Windows (und optional Linux/amd64)
.DESCRIPTION
Sucht die Go-Binary, baut den Agent für Windows und optional für Linux.
Erstellt eine Standard-Konfigurationsdatei, wenn noch keine vorhanden ist.
.PARAMETER Linux
Baut zusätzlich eine Linux-Binary (nexus-agent-linux).
.EXAMPLE
.\build-agent.ps1
.\build-agent.ps1 -Linux
#>
param(
[switch]$Linux
)
$ErrorActionPreference = "Stop"
$AgentDir = "D:\001_Projekte\IT_Tool\Agent"
$ConfigFile = "$AgentDir\nexus-agent.yaml"
# ---------------------------------------------------------------------------
# Helper
# ---------------------------------------------------------------------------
function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan }
function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green }
function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow }
function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red }
function Format-FileSize {
param([long]$Bytes)
if ($Bytes -ge 1MB) { return "{0:N1} MB" -f ($Bytes / 1MB) }
return "{0:N0} KB" -f ($Bytes / 1KB)
}
# ---------------------------------------------------------------------------
# 1. Go-Binary finden
# ---------------------------------------------------------------------------
Write-Step "Suche Go-Installation..."
# Kandidaten: expliziter Standardpfad zuerst, dann PATH
$goCandidates = @(
"C:\Program Files\Go\bin\go.exe",
"C:\Go\bin\go.exe"
)
$goExe = $null
foreach ($candidate in $goCandidates) {
if (Test-Path $candidate) {
$goExe = $candidate
break
}
}
if ($null -eq $goExe) {
# Fallback: PATH
$fromPath = Get-Command "go" -ErrorAction SilentlyContinue
if ($null -ne $fromPath) {
$goExe = $fromPath.Source
}
}
if ($null -eq $goExe) {
Write-Fail "Go wurde nicht gefunden. Bitte Go installieren (https://go.dev/dl/) oder PATH prüfen."
exit 1
}
$goVersion = & $goExe version
Write-OK "Go gefunden: $goExe"
Write-OK "Version: $goVersion"
# ---------------------------------------------------------------------------
# 2. Ins Agent-Verzeichnis wechseln
# ---------------------------------------------------------------------------
if (-not (Test-Path $AgentDir)) {
Write-Fail "Agent-Verzeichnis nicht gefunden: $AgentDir"
exit 1
}
Push-Location $AgentDir
try {
# -----------------------------------------------------------------------
# 3. Windows-Build
# -----------------------------------------------------------------------
Write-Step "Baue Windows-Binary (nexus-agent.exe)..."
$env:GOOS = "windows"
$env:GOARCH = "amd64"
$env:CGO_ENABLED = "0"
$winOut = "$AgentDir\nexus-agent.exe"
& $goExe build -ldflags="-s -w" -o $winOut ./cmd/agent/
if ($LASTEXITCODE -ne 0) {
Write-Fail "Windows-Build fehlgeschlagen."
exit 1
}
$winSize = (Get-Item $winOut).Length
Write-OK "Windows-Binary erstellt:"
Write-OK " Pfad: $winOut"
Write-OK " Groesse: $(Format-FileSize $winSize)"
# -----------------------------------------------------------------------
# 4. Linux-Build (optional)
# -----------------------------------------------------------------------
if ($Linux) {
Write-Step "Baue Linux-Binary (nexus-agent-linux)..."
$env:GOOS = "linux"
$env:GOARCH = "amd64"
$env:CGO_ENABLED = "0"
$linuxOut = "$AgentDir\nexus-agent-linux"
& $goExe build -ldflags="-s -w" -o $linuxOut ./cmd/agent/
if ($LASTEXITCODE -ne 0) {
Write-Fail "Linux-Build fehlgeschlagen."
exit 1
}
$linuxSize = (Get-Item $linuxOut).Length
Write-OK "Linux-Binary erstellt:"
Write-OK " Pfad: $linuxOut"
Write-OK " Groesse: $(Format-FileSize $linuxSize)"
} else {
Write-Warn "Linux-Build übersprungen. Mit -Linux Parameter ausführen um Linux-Binary zu bauen."
}
} finally {
# Umgebungsvariablen zurücksetzen
Remove-Item Env:\GOOS -ErrorAction SilentlyContinue
Remove-Item Env:\GOARCH -ErrorAction SilentlyContinue
Remove-Item Env:\CGO_ENABLED -ErrorAction SilentlyContinue
Pop-Location
}
# ---------------------------------------------------------------------------
# 5. Konfigurationsdatei erstellen (nur wenn nicht vorhanden)
# ---------------------------------------------------------------------------
Write-Step "Prüfe Konfigurationsdatei..."
if (Test-Path $ConfigFile) {
Write-OK "Konfiguration bereits vorhanden: $ConfigFile (wird nicht überschrieben)"
} else {
Write-Warn "Keine Konfigurationsdatei gefunden. Erstelle Standard-Konfiguration..."
$defaultConfig = @"
# NexusRMM Agent Konfiguration
server_address: localhost:5001
heartbeat_interval: 30
tls_enabled: false
mesh_enabled: false
mesh_central_url: ""
"@
Set-Content -Path $ConfigFile -Value $defaultConfig -Encoding UTF8
Write-OK "Konfiguration erstellt: $ConfigFile"
}
# ---------------------------------------------------------------------------
# 6. Zusammenfassung
# ---------------------------------------------------------------------------
Write-Host ""
Write-Host "Build abgeschlossen." -ForegroundColor Green
Write-Host "Agent starten: .\Agent\nexus-agent.exe" -ForegroundColor Yellow
Write-Host "Konfiguration: $ConfigFile" -ForegroundColor Yellow

188
dev-start.ps1 Normal file
View File

@@ -0,0 +1,188 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Startet die NexusRMM Entwicklungsumgebung
.DESCRIPTION
Startet Docker (Postgres + MeshCentral), führt DB-Migrationen aus,
startet Backend und Frontend in separaten Fenstern.
#>
$ErrorActionPreference = "Stop"
$Root = "D:\001_Projekte\IT_Tool"
# ---------------------------------------------------------------------------
# Helper-Funktionen
# ---------------------------------------------------------------------------
function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan }
function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green }
function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow }
function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red }
# ---------------------------------------------------------------------------
# 1. Voraussetzungen prüfen
# ---------------------------------------------------------------------------
Write-Step "Prüfe Voraussetzungen..."
$missing = $false
$tools = @(
@{ Name = "docker"; Desc = "Docker Desktop" },
@{ Name = "dotnet"; Desc = ".NET SDK" },
@{ Name = "node"; Desc = "Node.js" },
@{ Name = "npm"; Desc = "npm" },
@{ Name = "go"; Desc = "Go" }
)
foreach ($tool in $tools) {
$cmd = Get-Command $tool.Name -ErrorAction SilentlyContinue
if ($null -eq $cmd) {
Write-Fail "$($tool.Desc) ($($tool.Name)) nicht gefunden. Bitte installieren."
$missing = $true
} else {
Write-OK "$($tool.Desc): $($cmd.Source)"
}
}
if ($missing) {
Write-Fail "Fehlende Voraussetzungen Abbruch."
exit 1
}
# dotnet-ef prüfen
$efInstalled = dotnet tool list --global 2>$null | Select-String "dotnet-ef"
if (-not $efInstalled) {
Write-Warn "dotnet-ef nicht global installiert. Installiere jetzt..."
dotnet tool install --global dotnet-ef
if ($LASTEXITCODE -ne 0) {
Write-Fail "dotnet-ef konnte nicht installiert werden."
exit 1
}
Write-OK "dotnet-ef installiert."
} else {
Write-OK "dotnet-ef: vorhanden"
}
# ---------------------------------------------------------------------------
# 2. PostgreSQL per Docker starten
# ---------------------------------------------------------------------------
Write-Step "Starte PostgreSQL..."
Push-Location $Root
try {
docker compose up -d nexusrmm-postgres
if ($LASTEXITCODE -ne 0) {
Write-Fail "docker compose up fehlgeschlagen."
exit 1
}
} finally {
Pop-Location
}
# Warte bis PostgreSQL bereit ist (max 30 Sekunden, Intervall 2 Sekunden)
Write-Host " Warte auf PostgreSQL..." -ForegroundColor Cyan
$maxWait = 30
$waited = 0
$pgReady = $false
while ($waited -lt $maxWait) {
$result = docker exec nexusrmm-postgres pg_isready -U nexusrmm -q 2>&1
if ($LASTEXITCODE -eq 0) {
$pgReady = $true
break
}
Start-Sleep -Seconds 2
$waited += 2
}
if (-not $pgReady) {
Write-Fail "PostgreSQL ist nach $maxWait Sekunden nicht erreichbar."
exit 1
}
Write-OK "PostgreSQL bereit (Port 5433)."
# ---------------------------------------------------------------------------
# 3. EF Core Migrationen ausführen
# ---------------------------------------------------------------------------
Write-Step "Führe Datenbank-Migrationen aus..."
Push-Location "$Root\Backend"
try {
# --project: Migration-Projekt (Infrastructure enthält DbContext + Migrations)
# --startup-project: Startup-Projekt mit Verbindungsstring
dotnet ef database update `
--project "src\NexusRMM.Infrastructure" `
--startup-project "src\NexusRMM.Api" `
--no-build
if ($LASTEXITCODE -ne 0) {
# --no-build schlägt fehl wenn noch kein Build vorhanden Build nachholen
Write-Warn "Migration mit --no-build fehlgeschlagen, baue zuerst..."
dotnet build "src\NexusRMM.Api" --configuration Debug -q
if ($LASTEXITCODE -ne 0) {
Write-Fail "dotnet build fehlgeschlagen."
exit 1
}
dotnet ef database update `
--project "src\NexusRMM.Infrastructure" `
--startup-project "src\NexusRMM.Api"
if ($LASTEXITCODE -ne 0) {
Write-Fail "dotnet ef database update fehlgeschlagen."
exit 1
}
}
} finally {
Pop-Location
}
Write-OK "Migrationen erfolgreich."
# ---------------------------------------------------------------------------
# 4. Backend in neuem PowerShell-Fenster starten
# ---------------------------------------------------------------------------
Write-Step "Starte Backend..."
$backendCmd = "Set-Location '$Root\Backend'; Write-Host 'NexusRMM Backend' -ForegroundColor Cyan; dotnet run --project src/NexusRMM.Api"
Start-Process powershell -ArgumentList @(
"-NoExit",
"-Command",
$backendCmd
) -WindowStyle Normal
Write-OK "Backend-Fenster geöffnet."
# ---------------------------------------------------------------------------
# 5. Kurz warten damit das Backend starten kann
# ---------------------------------------------------------------------------
Write-Host "`n Warte 5 Sekunden damit das Backend hochfahren kann..." -ForegroundColor Cyan
Start-Sleep -Seconds 5
# ---------------------------------------------------------------------------
# 6. Frontend in neuem PowerShell-Fenster starten
# ---------------------------------------------------------------------------
Write-Step "Starte Frontend..."
$frontendCmd = "Set-Location '$Root\Frontend'; Write-Host 'NexusRMM Frontend' -ForegroundColor Cyan; npm run dev"
Start-Process powershell -ArgumentList @(
"-NoExit",
"-Command",
$frontendCmd
) -WindowStyle Normal
Write-OK "Frontend-Fenster geöffnet."
# ---------------------------------------------------------------------------
# 7. Zusammenfassung
# ---------------------------------------------------------------------------
Write-Host ""
Write-Host "╔══════════════════════════════════════════╗" -ForegroundColor Green
Write-Host "║ NexusRMM ist bereit! ║" -ForegroundColor Green
Write-Host "╠══════════════════════════════════════════╣" -ForegroundColor Green
Write-Host "║ Frontend: http://localhost:5173 ║" -ForegroundColor Green
Write-Host "║ Backend: http://localhost:5000 ║" -ForegroundColor Green
Write-Host "║ Swagger: http://localhost:5000/swagger ║" -ForegroundColor Green
Write-Host "║ gRPC: http://localhost:5001 ║" -ForegroundColor Green
Write-Host "║ MeshCentral: https://localhost:4430 ║" -ForegroundColor Green
Write-Host "╚══════════════════════════════════════════╝" -ForegroundColor Green
Write-Host ""
Write-Host "Agent starten: .\Agent\nexus-agent.exe" -ForegroundColor Yellow
Write-Host "Alles stoppen: .\dev-stop.ps1" -ForegroundColor Yellow

95
dev-stop.ps1 Normal file
View File

@@ -0,0 +1,95 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Stoppt die NexusRMM Entwicklungsumgebung
.DESCRIPTION
Beendet alle PowerShell-Fenster mit "NexusRMM" im Titel und
fährt den PostgreSQL-Container herunter (ohne Volumes zu löschen).
MeshCentral wird NICHT gestoppt.
#>
$ErrorActionPreference = "Stop"
$Root = "D:\001_Projekte\IT_Tool"
# ---------------------------------------------------------------------------
# Helper
# ---------------------------------------------------------------------------
function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan }
function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green }
function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow }
function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red }
# ---------------------------------------------------------------------------
# 1. PowerShell-Fenster mit "NexusRMM" im Hauptfenstertitel schließen
# ---------------------------------------------------------------------------
Write-Step "Schliesse NexusRMM PowerShell-Fenster..."
Add-Type -AssemblyName System.Diagnostics.Process -ErrorAction SilentlyContinue
$currentPid = $PID
$killed = 0
# GetProcesses liefert alle powershell / pwsh Instanzen
$psProcesses = Get-Process -Name @("powershell", "pwsh") -ErrorAction SilentlyContinue
foreach ($proc in $psProcesses) {
if ($proc.Id -eq $currentPid) { continue } # dieses Skript selbst nicht beenden
# Fenstertitel auslesen (MainWindowTitle ist leer bei verborgenen Fenstern)
$title = $proc.MainWindowTitle
if ($title -match "NexusRMM") {
try {
$proc | Stop-Process -Force
Write-OK "Prozess beendet: PID $($proc.Id) '$title'"
$killed++
} catch {
Write-Warn "Konnte Prozess PID $($proc.Id) nicht beenden: $_"
}
}
}
if ($killed -eq 0) {
Write-Warn "Keine laufenden NexusRMM-Fenster gefunden."
} else {
Write-OK "$killed Fenster geschlossen."
}
# ---------------------------------------------------------------------------
# 2. PostgreSQL-Container stoppen (ohne Volume zu entfernen)
# ---------------------------------------------------------------------------
Write-Step "Stoppe PostgreSQL-Container..."
# Prüfen ob Docker läuft
$dockerCmd = Get-Command docker -ErrorAction SilentlyContinue
if ($null -eq $dockerCmd) {
Write-Warn "Docker nicht gefunden überspringe Container-Stop."
} else {
Push-Location $Root
try {
# Nur nexusrmm-postgres stoppen, MeshCentral bleibt unberührt
$containerRunning = docker ps --filter "name=nexusrmm-postgres" --format "{{.Names}}" 2>$null
if ($containerRunning -match "nexusrmm-postgres") {
docker compose stop nexusrmm-postgres
if ($LASTEXITCODE -eq 0) {
Write-OK "nexusrmm-postgres gestoppt."
} else {
Write-Fail "docker compose stop fehlgeschlagen."
}
} else {
Write-Warn "nexusrmm-postgres läuft nicht (bereits gestoppt)."
}
} finally {
Pop-Location
}
}
# ---------------------------------------------------------------------------
# 3. Zusammenfassung
# ---------------------------------------------------------------------------
Write-Host ""
Write-Host "NexusRMM Entwicklungsumgebung gestoppt." -ForegroundColor Green
Write-Host "Volumes wurden behalten (Datenbankdaten bleiben erhalten)." -ForegroundColor Yellow
Write-Host "MeshCentral wurde nicht gestoppt." -ForegroundColor Yellow
Write-Host ""
Write-Host "Neu starten: .\dev-start.ps1" -ForegroundColor Cyan
Write-Host "Alles inkl. Volumes loeschen: docker compose down -v" -ForegroundColor Cyan