auto-turning/ssh_setup.ps1

178 lines
9.3 KiB
PowerShell
Raw 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.

# ============================================================
# SSH INSTALLER (FIXED)
# ============================================================
$repo = "https://git.help-d.ru/helmut/auto-turning/raw/branch/main"
$temp = "$env:TEMP\ssh_setup"
Write-Host "`n========== SSH УСТАНОВКА ==========`n" -ForegroundColor Cyan
# ПРОВЕРКА SSH - более надёжный способ
$sshService = Get-Service -Name sshd -ErrorAction SilentlyContinue
$sshInstalled = $false
if ($sshService) {
$sshInstalled = $true
Write-Host "✓ SSH служба обнаружена" -ForegroundColor Green
} else {
# Альтернативная проверка
$sshCapability = Get-WindowsCapability -Online | Where-Object { $_.Name -like "OpenSSH.Server*" -and $_.State -eq "Installed" }
if ($sshCapability) {
$sshInstalled = $true
Write-Host "✓ SSH компонент обнаружен" -ForegroundColor Green
} else {
Write-Host "! SSH не обнаружен" -ForegroundColor Yellow
}
}
if ($sshInstalled) {
Write-Host "✓ SSH уже установлен" -ForegroundColor Green
# Проверка настройки sshd_config
$cfg = "C:\ProgramData\ssh\sshd_config"
if (Test-Path $cfg) {
$configContent = Get-Content $cfg -Raw
$portConfigured = $configContent -match "Port 2222"
$adminMatchCommented = $configContent -match "#Match Group administrators"
if ($portConfigured -and $adminMatchCommented) {
Write-Host "✓ SSH уже настроен согласно скрипту" -ForegroundColor Green
Write-Host " Пропускаем настройку..." -ForegroundColor Yellow
$skipConfig = $true
} else {
Write-Host "! SSH установлен, но настроен не по шаблону" -ForegroundColor Yellow
Write-Host " Выполняю настройку..." -ForegroundColor Yellow
$skipConfig = $false
}
} else {
Write-Host "! Файл конфигурации не найден" -ForegroundColor Yellow
$skipConfig = $false
}
if (-not $skipConfig) {
# Настройка авторизации
Write-Host "`n3. Настраиваю авторизацию..." -ForegroundColor Yellow
New-Item -ItemType Directory -Path "$env:USERPROFILE\.ssh" -Force | Out-Null
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHceolzaC/nnN14/lVqeXzcXcIANtQgJcIaFczLIchVo efgufk/admin@ISERVER" | Out-File "$env:USERPROFILE\.ssh\authorized_keys" -Force
Write-Host " ✓ Готово" -ForegroundColor Green
# Настройка sshd_config
Write-Host "`n4. Настраиваю sshd_config..." -ForegroundColor Yellow
$c = Get-Content $cfg
$c = $c -replace '^Port \d+', 'Port 2222' -replace '^#Port 22', 'Port 2222' -replace '^Match Group administrators', '#Match Group administrators' -replace '^\s+AuthorizedKeysFile', '# AuthorizedKeysFile'
$c | Set-Content $cfg
Write-Host " ✓ Готово" -ForegroundColor Green
# Перезапуск службы
Write-Host "`n5. Перезапускаю службу..." -ForegroundColor Yellow
Restart-Service sshd -Force
Write-Host " ✓ Готово" -ForegroundColor Green
}
} else {
# Установка SSH (как в оригинале)
Write-Host "! SSH не установлен, выполняю установку..." -ForegroundColor Yellow
Write-Host "`n1. Скачиваю установщик..." -ForegroundColor Yellow
New-Item -ItemType Directory -Path $temp -Force | Out-Null
Invoke-WebRequest -Uri "$repo/installers/OpenSSH.msi" -OutFile "$temp\OpenSSH.msi" -ErrorAction Stop
Write-Host " ✓ Готово" -ForegroundColor Green
Write-Host "`n2. Устанавливаю SSH..." -ForegroundColor Yellow
msiexec /i "$temp\OpenSSH.msi" /quiet /norestart
Start-Sleep -Seconds 3
Write-Host " ✓ Готово" -ForegroundColor Green
Write-Host "`n3. Настраиваю авторизацию..." -ForegroundColor Yellow
New-Item -ItemType Directory -Path "$env:USERPROFILE\.ssh" -Force | Out-Null
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHceolzaC/nnN14/lVqeXzcXcIANtQgJcIaFczLIchVo efgufk/admin@ISERVER" | Out-File "$env:USERPROFILE\.ssh\authorized_keys" -Force
Write-Host " ✓ Готово" -ForegroundColor Green
Write-Host "`n4. Настраиваю sshd_config..." -ForegroundColor Yellow
$cfg = "C:\ProgramData\ssh\sshd_config"
$c = Get-Content $cfg
$c = $c -replace '^#Port 22', 'Port 2222' -replace '^Match Group administrators', '#Match Group administrators' -replace '^\s+AuthorizedKeysFile', '# AuthorizedKeysFile'
$c | Set-Content $cfg
Write-Host " ✓ Готово" -ForegroundColor Green
Write-Host "`n5. Перезапускаю службу..." -ForegroundColor Yellow
Start-Service sshd -ErrorAction SilentlyContinue
Restart-Service sshd -Force
Write-Host " ✓ Готово" -ForegroundColor Green
}
# 6. Чистка мусора
Write-Host "`n6. Чистка мусора..." -ForegroundColor Yellow
if (Test-Path $temp) {
Remove-Item $temp -Recurse -Force
Write-Host " ✓ Временные файлы удалены" -ForegroundColor Green
}
# Очистка временных файлов Windows
try {
CleanMgr /sagerun:1 2>$null
Write-Host " ✓ Системный мусор очищен" -ForegroundColor Green
} catch {
Write-Host " ! Очистка мусора пропущена (требуется утилита CleanMgr)" -ForegroundColor Yellow
}
# 7. Антивирусная проверка (исправленная)
Write-Host "`n7. Запуск антивирусной проверки..." -ForegroundColor Yellow
try {
# Проверяем статус Windows Defender
$defenderStatus = Get-Service -Name WinDefend -ErrorAction SilentlyContinue
if ($defenderStatus.Status -eq 'Running') {
Write-Host " Запуск быстрой проверки Windows Defender..." -ForegroundColor Yellow
Start-Process -FilePath "C:\Program Files\Windows Defender\MpCmdRun.exe" -ArgumentList "-Scan -ScanType 1" -NoNewWindow -Wait
Write-Host " ✓ Антивирусная проверка завершена" -ForegroundColor Green
} else {
Write-Host " ! Служба Windows Defender не запущена" -ForegroundColor Yellow
Write-Host " Возможно, используется сторонний антивирус" -ForegroundColor Yellow
# Проверка наличия сторонних антивирусов
$thirdPartyAV = @(
@{Name="Kaspersky"; Path="C:\Program Files\Kaspersky Lab\*"; Exe="avp.com"; Args="scan"},
@{Name="ESET"; Path="C:\Program Files\ESET\*"; Exe="ecls.exe"; Args="--adware --unsafe --sfx /scan"},
@{Name="Dr.Web"; Path="C:\Program Files\DrWeb\*"; Exe="dwscancl.exe"; Args="/scan"},
@{Name="Avast"; Path="C:\Program Files\Avast Software\*"; Exe="ashCmd.exe"; Args="/quick"}
)
$avFound = $false
foreach ($av in $thirdPartyAV) {
$avPath = Get-ChildItem -Path $av.Path -Filter $av.Exe -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
if ($avPath) {
Write-Host " Обнаружен $($av.Name), запуск проверки..." -ForegroundColor Yellow
Start-Process -FilePath $avPath.FullName -ArgumentList $av.Args -NoNewWindow
Write-Host " ✓ Проверка $($av.Name) запущена" -ForegroundColor Green
$avFound = $true
break
}
}
if (-not $avFound) {
Write-Host " ! Сторонний антивирус не обнаружен" -ForegroundColor Red
Write-Host " Рекомендуется выполнить проверку вручную" -ForegroundColor Yellow
}
}
} catch {
Write-Host " ! Ошибка при запуске антивируса: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " Рекомендуется выполнить проверку вручную" -ForegroundColor Yellow
}
# Результат
$ips = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike "*Loopback*" -and $_.InterfaceAlias -notlike "*vEthernet*"}).IPAddress
$ipList = $ips -join " "
Write-Host "`n========== ГОТОВО ==========" -ForegroundColor Green
Write-Host "Подключайтесь: ssh -p 2222 $env:USERNAME@$ipList" -ForegroundColor Cyan
Write-Host "============================`n" -ForegroundColor Green
Write-Host "✓ Установка завершена" -ForegroundColor Green
Write-Host "Мусор очищен" -ForegroundColor Green
if ($defenderStatus.Status -eq 'Running') {
Write-Host "✓ Антивирусная проверка выполнена" -ForegroundColor Green
} else {
Write-Host "⚠ Антивирусная проверка пропущена (служба не активна)" -ForegroundColor Yellow
}