Skip to main content

开启OpenSSH访问

开启服务流程

  • 检查是否支持

    # 查询安装状态
    Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*'

    # 安装
    Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

    # 这两者应该都会返回以下输出:
    Path :
    Online : True
    RestartNeeded : False
  • 开启服务

    # Start the sshd service
    # 手动开启服务
    Start-Service sshd

    # OPTIONAL but recommended:
    # 将服务器设置为自动启动
    Set-Service -Name sshd -StartupType 'Automatic'

    #
    # Confirm the Firewall rule is configured.
    # It should be created automatically by setup.
    # Run the following to verify
    if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
    Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
    } else {
    Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
    }

    function test-sshd {
    if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
    Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
    } else {
    Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
    }
    }

    # 返回:Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists.
    # 表示成功开启防火墙对应规则