This commit is contained in:
Windneiro 2026-04-13 16:45:35 +05:00
parent f474701760
commit a6203ab3ed
1 changed files with 102 additions and 51 deletions

View File

@ -1,5 +1,5 @@
# ============================================================ # ============================================================
# SSH INSTALLER # SSH INSTALLER (FIXED)
# ============================================================ # ============================================================
$repo = "https://git.help-d.ru/helmut/auto-turning/raw/branch/main" $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 Write-Host "`n========== SSH УСТАНОВКА ==========`n" -ForegroundColor Cyan
# Проверка наличия SSH # ПРОВЕРКА SSH - более надёжный способ
$sshInstalled = Get-WindowsCapability -Online | Where-Object Name -like "OpenSSH.Server*" | Select-Object -ExpandProperty State $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 Write-Host "✓ SSH уже установлен" -ForegroundColor Green
# Проверка настройки sshd_config # Проверка настройки sshd_config
$cfg = "C:\ProgramData\ssh\sshd_config" $cfg = "C:\ProgramData\ssh\sshd_config"
$currentPort = (Get-Content $cfg | Select-String "^Port" | Select-Object -Last 1).ToString().Split()[1] if (Test-Path $cfg) {
$configContent = Get-Content $cfg -Raw
if ($currentPort -eq "2222" -and (Get-Content $cfg | Select-String "^#Match Group administrators")) { $portConfigured = $configContent -match "Port 2222"
Write-Host "✓ SSH уже настроен согласно скрипту" -ForegroundColor Green $adminMatchCommented = $configContent -match "#Match Group administrators"
Write-Host " Пропускаем настройку..." -ForegroundColor Yellow
} else {
Write-Host "! SSH установлен, но настроен не по шаблону" -ForegroundColor Yellow
Write-Host " Выполняю настройку..." -ForegroundColor Yellow
# Настраиваю авторизацию... 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 Write-Host "`n3. Настраиваю авторизацию..." -ForegroundColor Yellow
New-Item -ItemType Directory -Path "$env:USERPROFILE\.ssh" -Force | Out-Null 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 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHceolzaC/nnN14/lVqeXzcXcIANtQgJcIaFczLIchVo efgufk/admin@ISERVER" | Out-File "$env:USERPROFILE\.ssh\authorized_keys" -Force
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
# Настраиваю sshd_config... # Настройка sshd_config
Write-Host "`n4. Настраиваю sshd_config..." -ForegroundColor Yellow Write-Host "`n4. Настраиваю sshd_config..." -ForegroundColor Yellow
$c = Get-Content $cfg $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 $c | Set-Content $cfg
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
# Перезапускаю службу... # Перезапуск службы
Write-Host "`n5. Перезапускаю службу..." -ForegroundColor Yellow Write-Host "`n5. Перезапускаю службу..." -ForegroundColor Yellow
Restart-Service sshd -Force Restart-Service sshd -Force
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
} }
} else { } else {
# Установка SSH (как в оригинале)
Write-Host "! SSH не установлен, выполняю установку..." -ForegroundColor Yellow Write-Host "! SSH не установлен, выполняю установку..." -ForegroundColor Yellow
# 1. Скачиваю установщик...
Write-Host "`n1. Скачиваю установщик..." -ForegroundColor Yellow Write-Host "`n1. Скачиваю установщик..." -ForegroundColor Yellow
New-Item -ItemType Directory -Path $temp -Force | Out-Null New-Item -ItemType Directory -Path $temp -Force | Out-Null
Invoke-WebRequest -Uri "$repo/installers/OpenSSH.msi" -OutFile "$temp\OpenSSH.msi" -ErrorAction Stop Invoke-WebRequest -Uri "$repo/installers/OpenSSH.msi" -OutFile "$temp\OpenSSH.msi" -ErrorAction Stop
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
# 2. Устанавливаю SSH...
Write-Host "`n2. Устанавливаю SSH..." -ForegroundColor Yellow Write-Host "`n2. Устанавливаю SSH..." -ForegroundColor Yellow
msiexec /i "$temp\OpenSSH.msi" /quiet /norestart msiexec /i "$temp\OpenSSH.msi" /quiet /norestart
Start-Sleep -Seconds 3
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
# 3. Настраиваю авторизацию...
Write-Host "`n3. Настраиваю авторизацию..." -ForegroundColor Yellow Write-Host "`n3. Настраиваю авторизацию..." -ForegroundColor Yellow
New-Item -ItemType Directory -Path "$env:USERPROFILE\.ssh" -Force | Out-Null 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 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHceolzaC/nnN14/lVqeXzcXcIANtQgJcIaFczLIchVo efgufk/admin@ISERVER" | Out-File "$env:USERPROFILE\.ssh\authorized_keys" -Force
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
# 4. Настраиваю sshd_config...
Write-Host "`n4. Настраиваю sshd_config..." -ForegroundColor Yellow Write-Host "`n4. Настраиваю sshd_config..." -ForegroundColor Yellow
$cfg = "C:\ProgramData\ssh\sshd_config" $cfg = "C:\ProgramData\ssh\sshd_config"
$c = Get-Content $cfg $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 $c | Set-Content $cfg
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
# 5. Перезапускаю службу...
Write-Host "`n5. Перезапускаю службу..." -ForegroundColor Yellow Write-Host "`n5. Перезапускаю службу..." -ForegroundColor Yellow
Start-Service sshd -ErrorAction SilentlyContinue
Restart-Service sshd -Force Restart-Service sshd -Force
Write-Host " ✓ Готово" -ForegroundColor Green Write-Host " ✓ Готово" -ForegroundColor Green
} }
# 6. Чистка мусора... # 6. Чистка мусора
Write-Host "`n6. Чистка мусора..." -ForegroundColor Yellow Write-Host "`n6. Чистка мусора..." -ForegroundColor Yellow
if (Test-Path $temp) { if (Test-Path $temp) {
Remove-Item $temp -Recurse -Force Remove-Item $temp -Recurse -Force
Write-Host " ✓ Временные файлы удалены" -ForegroundColor Green 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 Write-Host "`n7. Запуск антивирусной проверки..." -ForegroundColor Yellow
# Проверяем наличие Windows Defender try {
$defenderStatus = Get-MpComputerStatus # Проверяем статус Windows Defender
if ($defenderStatus) { $defenderStatus = Get-Service -Name WinDefend -ErrorAction SilentlyContinue
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"
)
foreach ($av in $antivirusPaths) { if ($defenderStatus.Status -eq 'Running') {
if (Test-Path $av) { Write-Host " Запуск быстрой проверки Windows Defender..." -ForegroundColor Yellow
Write-Host " Запуск проверки: $av" -ForegroundColor Yellow Start-Process -FilePath "C:\Program Files\Windows Defender\MpCmdRun.exe" -ArgumentList "-Scan -ScanType 1" -NoNewWindow -Wait
Start-Process $av -ArgumentList "/scan" -NoNewWindow Write-Host " ✓ Антивирусная проверка завершена" -ForegroundColor Green
Write-Host " ✓ Антивирусная проверка запущена" -ForegroundColor Green } else {
break 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 "`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 "============================`n" -ForegroundColor Green
# Уведомление о завершении
Write-Host "✓ Установка завершена" -ForegroundColor Green Write-Host "✓ Установка завершена" -ForegroundColor Green
Write-Host "Мусор очищен" -ForegroundColor Green Write-Host "Мусор очищен" -ForegroundColor Green
Write-Host "✓ Антивирусная проверка запущена в фоновом режиме" -ForegroundColor Green
if ($defenderStatus.Status -eq 'Running') {
Write-Host "✓ Антивирусная проверка выполнена" -ForegroundColor Green
} else {
Write-Host "⚠ Антивирусная проверка пропущена (служба не активна)" -ForegroundColor Yellow
}