Files
scripts/mmfb-winrm.ps1

86 lines
6.2 KiB
PowerShell
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Служебное подключение для удалённой поддержки (WinRM). Запуск: PowerShell от имени администратора.
# Идемпотентно — можно запускать повторно. Ничего не скачивает и не устанавливает.
$ErrorActionPreference = "Continue"
$U = "claude"
$PW = $env:KP
$SRC = "https://git.dttb.ru/oleg/scripts/raw/branch/main/mmfb-winrm.ps1"
$ALLOW = @("10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","100.70.0.0/16") # офисная сеть и служебная сеть, не интернет
# 32-битная консоль (Ассистент/AnyDesk) -> перезапуск в 64-бит, иначе нет New-LocalUser и реестр уезжает в WOW6432Node
if ($env:PROCESSOR_ARCHITEW6432 -eq "AMD64") {
& "$env:WINDIR\SysNative\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol='Tls12'; `$env:KP='$PW'; irm $SRC | iex"
return
}
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) { Write-Host "Нужен запуск PowerShell от имени администратора." -ForegroundColor Red; return }
if (-not $PW) {
$PW = -join ((48..57 + 65..90 + 97..122) | Get-Random -Count 14 | ForEach-Object { [char]$_ })
Write-Host "Пароль не задан — сгенерирован: $PW (передайте мастеру вместе с именем компьютера)" -ForegroundColor Yellow
}
$LOG = "$env:ProgramData\mmfb-support"; New-Item -ItemType Directory -Path $LOG -Force | Out-Null
function L($m) { "$((Get-Date).ToString('s')) $m" | Tee-Object -FilePath "$LOG\setup.log" -Append | Out-Null; Write-Host " $m" }
Write-Host "=== Служебное подключение: $env:COMPUTERNAME ===" -ForegroundColor Cyan
# 1) служебный пользователь (администратор, скрыт с экрана входа, пароль бессрочный)
L "[1] пользователь $U"
$sp = ConvertTo-SecureString $PW -AsPlainText -Force
if (-not (Get-LocalUser -Name $U -ErrorAction SilentlyContinue)) {
New-LocalUser -Name $U -Password $sp -PasswordNeverExpires -AccountNeverExpires -UserMayNotChangePassword -FullName "Remote Support" | Out-Null
} else {
Set-LocalUser -Name $U -Password $sp -PasswordNeverExpires $true -AccountNeverExpires -UserMayChangePassword $false
Enable-LocalUser -Name $U -ErrorAction SilentlyContinue
}
foreach ($sid in "S-1-5-32-544","S-1-5-32-555") { # Администраторы, Пользователи удалённого рабочего стола (имена на русской Windows не работают)
try { Add-LocalGroupMember -SID $sid -Member $U -ErrorAction Stop } catch { if ($_ -notmatch "already|уже") { L " группа $sid : $_" } }
}
$ul = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList"
if (-not (Test-Path $ul)) { New-Item $ul -Force | Out-Null }
New-ItemProperty $ul -Name $U -Value 0 -PropertyType DWord -Force | Out-Null
# 2) сетевой профиль Private (на Public quickconfig отказывает)
L "[2] сетевой профиль"
try { Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -eq "Public" } | Set-NetConnectionProfile -NetworkCategory Private } catch {}
# 3) WinRM: сперва quickconfig, потом настройки (иначе служба ещё не запущена)
L "[3] WinRM"
Set-Service WinRM -StartupType Automatic -ErrorAction SilentlyContinue
try { Enable-PSRemoting -Force -SkipNetworkProfileCheck | Out-Null } catch { winrm quickconfig -force -q 2>&1 | Out-Null }
Start-Service WinRM -ErrorAction SilentlyContinue
Set-Item WSMan:\localhost\Service\Auth\Basic $true -Force
Set-Item WSMan:\localhost\Service\AllowUnencrypted $true -Force
Set-Item WSMan:\localhost\Service\MaxConcurrentOperationsPerUser 1500 -Force -ErrorAction SilentlyContinue
if (-not (Get-ChildItem WSMan:\localhost\Listener | Where-Object { $_.Keys -contains "Transport=HTTP" })) {
New-Item WSMan:\localhost\Listener -Transport HTTP -Address * -Force | Out-Null
}
# локальный админ по сети без UAC-фильтра, иначе 401
New-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name LocalAccountTokenFilterPolicy -Value 1 -PropertyType DWord -Force | Out-Null
# 4) брандмауэр: 5985 только из частных сетей
L "[4] брандмауэр"
Get-NetFirewallRule -DisplayName "Support-WinRM" -ErrorAction SilentlyContinue | Remove-NetFirewallRule
New-NetFirewallRule -DisplayName "Support-WinRM" -Direction Inbound -Protocol TCP -LocalPort 5985 -RemoteAddress $ALLOW -Action Allow -Profile Any | Out-Null
# 5) не засыпать от сети (иначе компьютер недоступен)
L "[5] сон от сети выключен"
powercfg /change standby-timeout-ac 0 2>&1 | Out-Null
powercfg /change hibernate-timeout-ac 0 2>&1 | Out-Null
# 6) самопроверка
L "[6] проверка"
$svc = (Get-Service WinRM).Status
$ips = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -notlike "127.*" -and $_.IPAddress -notlike "169.254.*" } | ForEach-Object { $_.IPAddress }) -join ", "
$ok = $false
try {
$cred = New-Object PSCredential($U, $sp)
$r = Invoke-Command -ComputerName localhost -Credential $cred -Authentication Negotiate -ScriptBlock { $env:COMPUTERNAME } -ErrorAction Stop
$ok = ($r -eq $env:COMPUTERNAME)
} catch { L " самопроверка: $_" }
$summary = "Компьютер: $env:COMPUTERNAME`nIP: $ips`nПользователь: $env:USERNAME`nWinRM: $svc, вход $U : $(if($ok){'OK'}else{'ОШИБКА'})"
$summary | Set-Content "$LOG\summary.txt" -Encoding UTF8
try { Set-Clipboard -Value $summary } catch {}
Write-Host ""
Write-Host $summary -ForegroundColor $(if ($ok) { "Green" } else { "Yellow" })
Write-Host ""
Write-Host "Готово. Отправьте мастеру эти строки (они уже скопированы, просто вставьте в чат)." -ForegroundColor Cyan