# PC-migratie: maakt deze pc op afstand bereikbaar voor de beheer-pc (Tailscale + SSH). # Gebruik in PowerShell: irm https://pc.bartsweb.com | iex & { $ErrorActionPreference = 'Continue' $ProgressPreference = 'SilentlyContinue' # maakt downloads veel sneller $URL = 'https://pc.bartsweb.com' $PUBKEY = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBnAotZ1yMZjy5hVdn8r27MOPSnO3DB12+VK3jmC6HgL migratie-surface9' $TAILNET = 'tail005477.ts.net' $DIR = Join-Path $env:ProgramData 'migratie' $TS = Join-Path $env:ProgramFiles 'Tailscale\tailscale.exe' function Write-Stap([string]$t) { Write-Host ''; Write-Host "==> $t" -ForegroundColor Cyan } function Write-Ok([string]$t) { Write-Host " OK $t" -ForegroundColor Green } function Write-Info([string]$t) { Write-Host " $t" } function Write-Fout([string]$t) { Write-Host '' Write-Host " FOUT: $t" -ForegroundColor Red Write-Host ' Maak een foto van dit venster en stuur die naar Claude.' -ForegroundColor Red Write-Host " Logbestand: $DIR\setup.log" } # --- 0. Administrator? Zo niet: zelf opnieuw starten als administrator -------------------- $id = [Security.Principal.WindowsIdentity]::GetCurrent() $isAdmin = (New-Object Security.Principal.WindowsPrincipal $id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { Write-Host '' Write-Host ' Er zijn administratorrechten nodig. Klik op JA in het venster dat nu verschijnt.' -ForegroundColor Yellow try { Start-Process powershell.exe -Verb RunAs -ErrorAction Stop -ArgumentList '-NoExit', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', "irm $URL | iex" Write-Host ' Het script loopt verder in het nieuwe venster. Dit venster mag dicht.' } catch { Write-Host ' Geen administratorrechten gekregen. Probeer opnieuw en klik op JA.' -ForegroundColor Red } return } try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch {} New-Item -ItemType Directory -Force -Path $DIR | Out-Null try { Start-Transcript -Path (Join-Path $DIR 'setup.log') -Append | Out-Null } catch {} try { Write-Host '' Write-Host ' ================================================' -ForegroundColor Cyan Write-Host ' PC-MIGRATIE - verbinding klaarzetten' -ForegroundColor Cyan Write-Host ' ================================================' -ForegroundColor Cyan Write-Host '' # --- Vraag 1: oude of nieuwe pc -------------------------------------------------------- do { $r = ([string](Read-Host ' Is dit de OUDE of de NIEUWE pc? Typ O of N')).Trim().ToUpper() } until ($r -eq 'O' -or $r -eq 'N') $rol = if ($r -eq 'O') { 'oud' } else { 'nieuw' } $tsNaam = "migratie-$rol" # --- Vraag 2: Tailscale-sleutel (alleen als deze pc nog niet in het migratienetwerk zit) - $st = $null if (Test-Path $TS) { try { $st = (& $TS status --json 2>$null) | Out-String | ConvertFrom-Json } catch {} } $alVerbonden = [bool]($st -and $st.BackendState -eq 'Running' -and $st.CurrentTailnet -and $st.CurrentTailnet.MagicDNSSuffix -eq $TAILNET) $anderTailnet = [bool]($st -and $st.BackendState -eq 'Running' -and -not $alVerbonden) if ($anderTailnet) { Write-Host '' Write-Host ' Let op: Tailscale op deze pc is al verbonden met een ANDER netwerk.' -ForegroundColor Yellow $j = ([string](Read-Host ' Loskoppelen en verbinden met het migratienetwerk? Typ J of N')).Trim().ToUpper() if ($j -ne 'J') { Write-Host ' Gestopt. Er is niets aangepast.'; return } } $key = $null if (-not $alVerbonden) { do { $key = ([string](Read-Host ' Plak de Tailscale-sleutel (begint met tskey-auth-)')).Trim() } until ($key -like 'tskey-auth-*') } # --- 1. Slaapstand uit (op netstroom), oude waarden bewaren voor achteraf -------------- Write-Stap 'Slaapstand uitzetten zolang de migratie loopt' $energieBestand = Join-Path $DIR 'energie-origineel.json' if (-not (Test-Path $energieBestand)) { $orig = [ordered]@{} foreach ($s in @(@('SUB_SLEEP', 'STANDBYIDLE'), @('SUB_SLEEP', 'HIBERNATEIDLE'), @('SUB_BUTTONS', 'LIDACTION'))) { $txt = (powercfg /q SCHEME_CURRENT $s[0] $s[1] 2>$null) | Out-String $m = [regex]::Matches($txt, '0x[0-9a-fA-F]{8}') if ($m.Count -ge 2) { $orig["$($s[0])/$($s[1])"] = [Convert]::ToInt64($m[$m.Count - 2].Value, 16) } } $orig | ConvertTo-Json | Set-Content -Path $energieBestand -Encoding UTF8 } powercfg /setacvalueindex SCHEME_CURRENT SUB_SLEEP STANDBYIDLE 0 2>$null | Out-Null powercfg /setacvalueindex SCHEME_CURRENT SUB_SLEEP HIBERNATEIDLE 0 2>$null | Out-Null powercfg /setacvalueindex SCHEME_CURRENT SUB_BUTTONS LIDACTION 0 2>$null | Out-Null powercfg /setactive SCHEME_CURRENT 2>$null | Out-Null Write-Ok 'gaat niet slapen aan de lader, ook niet met het deksel dicht' # --- 2. Tailscale ------------------------------------------------------------------------- Write-Stap 'Tailscale' $arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { 'arm64' } else { 'amd64' } if (-not (Test-Path $TS)) { $msi = Join-Path $env:TEMP 'tailscale-setup.msi' Write-Info "downloaden ($arch)..." try { Invoke-WebRequest -Uri "https://pkgs.tailscale.com/stable/tailscale-setup-latest-$arch.msi" -OutFile $msi -UseBasicParsing -ErrorAction Stop } catch { Write-Fout "Tailscale downloaden mislukt: $($_.Exception.Message)"; return } Write-Info 'installeren...' $p = Start-Process msiexec.exe -ArgumentList "/i `"$msi`" /qn /norestart" -Wait -PassThru Remove-Item $msi -Force -ErrorAction SilentlyContinue if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { Write-Fout "Tailscale installeren mislukt (code $($p.ExitCode))"; return } } for ($i = 0; $i -lt 30; $i++) { $svc = Get-Service Tailscale -ErrorAction SilentlyContinue if ($svc -and $svc.Status -eq 'Running') { break } if ($svc) { Start-Service Tailscale -ErrorAction SilentlyContinue } Start-Sleep -Seconds 2 } if ($alVerbonden) { & $TS set "--hostname=$tsNaam" 2>$null | Out-Null } else { if ($anderTailnet) { & $TS logout 2>$null | Out-Null } Write-Info 'verbinden met de sleutel...' & $TS up --reset --unattended "--auth-key=$key" "--hostname=$tsNaam" --timeout=120s if ($LASTEXITCODE -ne 0) { Write-Fout 'Tailscale kon niet verbinden. Is de sleutel juist en nog geldig?'; return } } $tsIp = $null for ($i = 0; $i -lt 15 -and -not $tsIp; $i++) { $tsIp = (& $TS ip -4 2>$null) | Select-Object -First 1; if (-not $tsIp) { Start-Sleep -Seconds 2 } } Write-Ok "verbonden als $tsNaam ($tsIp)" # --- 3. OpenSSH Server -------------------------------------------------------------------- Write-Stap 'OpenSSH Server' if (-not (Get-Service sshd -ErrorAction SilentlyContinue)) { try { Write-Info 'downloaden en installeren...' $patroon = if ($arch -eq 'arm64') { 'OpenSSH-ARM64-*.msi' } else { 'OpenSSH-Win64-*.msi' } $rel = Invoke-RestMethod 'https://api.github.com/repos/PowerShell/Win32-OpenSSH/releases/latest' -ErrorAction Stop $asset = $rel.assets | Where-Object { $_.name -like $patroon } | Select-Object -First 1 $msi = Join-Path $env:TEMP 'openssh.msi' Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $msi -UseBasicParsing -ErrorAction Stop $p = Start-Process msiexec.exe -ArgumentList "/i `"$msi`" /qn /norestart" -Wait -PassThru Remove-Item $msi -Force -ErrorAction SilentlyContinue } catch { Write-Info "snelle installatie lukte niet: $($_.Exception.Message)" } } if (-not (Get-Service sshd -ErrorAction SilentlyContinue)) { Write-Info 'via Windows-onderdelen installeren (kan 5-10 minuten duren)...' try { $cap = Get-WindowsCapability -Online -ErrorAction Stop | Where-Object { $_.Name -like 'OpenSSH.Server*' } | Select-Object -First 1 if ($cap -and $cap.State -ne 'Installed') { Add-WindowsCapability -Online -Name $cap.Name -ErrorAction Stop | Out-Null } } catch { Write-Info "lukte niet: $($_.Exception.Message)" } } if (-not (Get-Service sshd -ErrorAction SilentlyContinue)) { Write-Fout 'OpenSSH Server kon niet geinstalleerd worden.'; return } Set-Service -Name sshd -StartupType Automatic Start-Service sshd -ErrorAction SilentlyContinue if (-not (Test-Path 'HKLM:\SOFTWARE\OpenSSH')) { New-Item -Path 'HKLM:\SOFTWARE\OpenSSH' | Out-Null } New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell -PropertyType String -Force ` -Value (Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe') | Out-Null Write-Ok 'geinstalleerd en gestart' # --- 4. Firewall: poort 22 alleen via Tailscale ------------------------------------------- Write-Stap 'Firewall' if (-not (Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue)) { New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Direction Inbound ` -Protocol TCP -LocalPort 22 -Action Allow -Profile Any -RemoteAddress '100.64.0.0/10' | Out-Null } Get-NetFirewallRule -Direction Inbound -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq 'OpenSSH-Server-In-TCP' -or $_.Name -eq 'sshd' -or $_.DisplayName -like 'OpenSSH*' } | ForEach-Object { Set-NetFirewallRule -Name $_.Name -Profile Any -RemoteAddress '100.64.0.0/10' } Set-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -Enabled True Write-Ok 'SSH alleen bereikbaar via Tailscale, niet via het (gast)netwerk' # --- 5. Toegangssleutel van de beheer-pc -------------------------------------------------- Write-Stap 'Toegangssleutel' $sshMap = Join-Path $env:ProgramData 'ssh' if (-not (Test-Path $sshMap)) { New-Item -ItemType Directory -Path $sshMap | Out-Null } $ak = Join-Path $sshMap 'administrators_authorized_keys' if (-not (Test-Path $ak) -or -not (Select-String -Path $ak -SimpleMatch $PUBKEY -Quiet)) { Add-Content -Path $ak -Value $PUBKEY -Encoding Ascii } # Rechten: enkel Administrators en SYSTEM (anders weigert sshd de sleutel) icacls $ak /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null Restart-Service sshd -ErrorAction SilentlyContinue Write-Ok 'toegevoegd' # --- 6. Controle + gegevens --------------------------------------------------------------- $luistert = $false for ($i = 0; $i -lt 10 -and -not $luistert; $i++) { $luistert = [bool](Get-NetTCPConnection -LocalPort 22 -State Listen -ErrorAction SilentlyContinue) if (-not $luistert) { Start-Sleep -Seconds 1 } } if (-not $luistert) { Write-Fout 'SSH-server luistert niet op poort 22.'; return } $sshUser = $id.Name $console = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName [ordered]@{ rol = $rol tailscale = $tsNaam tailscale_ip = $tsIp ssh_gebruiker = $sshUser ingelogd = $console computer = $env:COMPUTERNAME architectuur = $env:PROCESSOR_ARCHITECTURE datum = (Get-Date -Format s) } | ConvertTo-Json | Set-Content -Path (Join-Path $DIR 'info.json') -Encoding UTF8 Write-Host '' Write-Host ' ================================================' -ForegroundColor Green Write-Host ' KLAAR! Stuur deze regel naar Claude:' -ForegroundColor Green Write-Host '' Write-Host " $rol = $sshUser @ $tsIp" -ForegroundColor Yellow Write-Host '' Write-Host ' Laat deze pc aan staan, aan de lader.' -ForegroundColor Green Write-Host ' ================================================' -ForegroundColor Green Write-Host '' } finally { try { Stop-Transcript | Out-Null } catch {} } }