diff --git a/ssh_setup.ps1 b/ssh_setup.ps1 index 2d3b584..25ba5de 100644 --- a/ssh_setup.ps1 +++ b/ssh_setup.ps1 @@ -1,5 +1,5 @@ # ============================================================ -# SSH INSTALLER +# SSH INSTALLER (FIXED) # ============================================================ $repo = "https://git.help-d.ru/helmut/auto-turning/raw/branch/main" @@ -7,121 +7,172 @@ $temp = "$env:TEMP\ssh_setup" Write-Host "`n========== SSH УСТАНОВКА ==========`n" -ForegroundColor Cyan -# Проверка наличия SSH -$sshInstalled = Get-WindowsCapability -Online | Where-Object Name -like "OpenSSH.Server*" | Select-Object -ExpandProperty State +# ПРОВЕРКА SSH - более надёжный способ +$sshService = Get-Service -Name sshd -ErrorAction SilentlyContinue +$sshInstalled = $false -if ($sshInstalled -eq "Installed") { +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" - $currentPort = (Get-Content $cfg | Select-String "^Port" | Select-Object -Last 1).ToString().Split()[1] - - if ($currentPort -eq "2222" -and (Get-Content $cfg | Select-String "^#Match Group administrators")) { - Write-Host "✓ SSH уже настроен согласно скрипту" -ForegroundColor Green - Write-Host " Пропускаем настройку..." -ForegroundColor Yellow - } else { - Write-Host "! SSH установлен, но настроен не по шаблону" -ForegroundColor Yellow - Write-Host " Выполняю настройку..." -ForegroundColor Yellow + 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... + # Настройка sshd_config Write-Host "`n4. Настраиваю sshd_config..." -ForegroundColor Yellow $c = Get-Content $cfg - $c = $c -replace '^#Port 22', 'Port 2222' -replace '^Port 22', 'Port 2222' -replace '^Match Group administrators', '#Match Group administrators' -replace '^ AuthorizedKeysFile', '# AuthorizedKeysFile' + $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 - # 1. Скачиваю установщик... 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 - # 2. Устанавливаю SSH... Write-Host "`n2. Устанавливаю SSH..." -ForegroundColor Yellow msiexec /i "$temp\OpenSSH.msi" /quiet /norestart + Start-Sleep -Seconds 3 Write-Host " ✓ Готово" -ForegroundColor Green - # 3. Настраиваю авторизацию... 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 - # 4. Настраиваю sshd_config... 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 '^ AuthorizedKeysFile', '# AuthorizedKeysFile' + $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 - # 5. Перезапускаю службу... Write-Host "`n5. Перезапускаю службу..." -ForegroundColor Yellow + Start-Service sshd -ErrorAction SilentlyContinue Restart-Service sshd -Force Write-Host " ✓ Готово" -ForegroundColor Green } -# 6. Чистка мусора... +# 6. Чистка мусора Write-Host "`n6. Чистка мусора..." -ForegroundColor Yellow if (Test-Path $temp) { Remove-Item $temp -Recurse -Force Write-Host " ✓ Временные файлы удалены" -ForegroundColor Green } -# Очистка кэша Windows -CleanMgr /sagerun:1 | Out-Null -Write-Host " ✓ Системный мусор очищен" -ForegroundColor Green -# 7. Запуск антивирусной проверки... +# Очистка временных файлов Windows +try { + CleanMgr /sagerun:1 2>$null + Write-Host " ✓ Системный мусор очищен" -ForegroundColor Green +} catch { + Write-Host " ! Очистка мусора пропущена (требуется утилита CleanMgr)" -ForegroundColor Yellow +} + +# 7. Антивирусная проверка (исправленная) Write-Host "`n7. Запуск антивирусной проверки..." -ForegroundColor Yellow -# Проверяем наличие Windows Defender -$defenderStatus = Get-MpComputerStatus -if ($defenderStatus) { - Write-Host " Запуск быстрой проверки Windows Defender..." -ForegroundColor Yellow - Start-MpScan -ScanType QuickScan - Write-Host " ✓ Антивирусная проверка запущена" -ForegroundColor Green -} else { - Write-Host " ! Windows Defender не обнаружен" -ForegroundColor Red - # Попытка запуска стороннего антивируса (пример для Kaspersky) - $antivirusPaths = @( - "C:\Program Files\Windows Defender\MpCmdRun.exe", - "C:\Program Files\Kaspersky Lab\Kaspersky*\avp.exe", - "C:\Program Files\ESET\ESET Security\ecls.exe" - ) +try { + # Проверяем статус Windows Defender + $defenderStatus = Get-Service -Name WinDefend -ErrorAction SilentlyContinue - foreach ($av in $antivirusPaths) { - if (Test-Path $av) { - Write-Host " Запуск проверки: $av" -ForegroundColor Yellow - Start-Process $av -ArgumentList "/scan" -NoNewWindow - Write-Host " ✓ Антивирусная проверка запущена" -ForegroundColor Green - break + 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 } # Результат -$ip = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike "*Loopback*" -and $_.InterfaceAlias -notlike "*vEthernet*"}).IPAddress +$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@$ip" -ForegroundColor Cyan +Write-Host "Подключайтесь: ssh -p 2222 $env:USERNAME@$ipList" -ForegroundColor Cyan Write-Host "============================`n" -ForegroundColor Green -# Уведомление о завершении Write-Host "✓ Установка завершена" -ForegroundColor Green Write-Host "✓ Мусор очищен" -ForegroundColor Green -Write-Host "✓ Антивирусная проверка запущена в фоновом режиме" -ForegroundColor Green \ No newline at end of file + +if ($defenderStatus.Status -eq 'Running') { + Write-Host "✓ Антивирусная проверка выполнена" -ForegroundColor Green +} else { + Write-Host "⚠ Антивирусная проверка пропущена (служба не активна)" -ForegroundColor Yellow +} \ No newline at end of file