VScode SSH 免密连接 一键脚本

发布时间:2026/7/4 3:05:20
VScode SSH 免密连接 一键脚本 前言使用VScode的SSH插件连接一个新的服务器时由于VScode不支持保存密码所以一般的免密操作步骤如下1生成一对密钥2把公钥拷贝到服务器(Linux)的authorized_keys3在主机Windows的.ssh/config 中设置 IdentityFile 后面接私钥绝对路径上述步骤每次全部来一遍也是很繁琐的完全可以整合一个脚本然后一键式傻瓜操作。一键配置VScode SSH免密连接脚本echo off setlocalsetSELF%~f0powershell.exe-NoProfile-ExecutionPolicyBypass-EncodedCommandJABwAD0AJABlAG4AdgA6AFMARQBMAEYAOwAgACQAbABpAG4AZQBzAD0ARwBlAHQALQBDAG8AbgB0AGUAbgB0ACAALQBMAGkAdABlAHIAYQBsAFAAYQB0AGgAIAAkAHAAIAAtAEUAbgBjAG8AZABpAG4AZwAgAEQAZQBmAGEAdQBsAHQAOwAgACQAbQBhAHIAawA9AFsAQQByAHIAYQB5AF0AOgA6AEkAbgBkAGUAeABPAGYAKAAkAGwAaQBuAGUAcwAsACcAIwAgAFAATwBXAEUAUgBTAEgARQBMAEwAJwApADsAIABpAGYAKAAkAG0AYQByAGsAIAAtAGwAdAAgADAAKQB7AHQAaAByAG8AdwAgACcAQgBBAFQAIABmAGkAbABlACAAaQBzACAAYgByAG8AawBlAG4ALgAnAH0AOwAgACQAYwBvAGQAZQA9ACQAbABpAG4AZQBzAFsAKAAkAG0AYQByAGsAKwAxACkALgAuACgAJABsAGkAbgBlAHMALgBMAGUAbgBnAHQAaAAtADEAKQBdACAALQBqAG8AaQBuACAAWwBFAG4AdgBpAHIAbwBuAG0AZQBuAHQAXQA6ADoATgBlAHcATABpAG4AZQA7ACAASQBuAHYAbwBrAGUALQBFAHgAcAByAGUAcwBzAGkAbwBuACAAJABjAG8AZABlAAecho. pauseexit/b# POWERSHELL$ErrorActionPreferenceStopfunctionAsk($text,$default){if($default){$vRead-Host$text[$default]if([string]::IsNullOrWhiteSpace($v)){return$default}return$v.Trim()}do{$vRead-Host$text}while([string]::IsNullOrWhiteSpace($v))return$v.Trim()}functionHas-HostConfig($configText,$hostValue){if([string]::IsNullOrWhiteSpace($configText)){return$false}$pattern(?m)^\s*Host\s$([regex]::Escape($hostValue))\s*$return[regex]::IsMatch($configText,$pattern)}functionTest-HostValue($hostValue){if($hostValue-match^\d$){throwInvalid IP or host:$hostValue}if($hostValue-match^[\d.]$){$addr$nullif(-not[Net.IPAddress]::TryParse($hostValue,[ref]$addr)){throwInvalid IP:$hostValue}}}functionSet-HostConfigBlock($configPath,$hostValue,$configBlock){$lines(Get-Content-LiteralPath$configPath-ErrorActionSilentlyContinue)$hostPattern^\s*Host\s$([regex]::Escape($hostValue))\s*$$start-1for($i0;$i-lt$lines.Count;$i){if($lines[$i]-match$hostPattern){$start$ibreak}}if($start-lt0){Add-Content-LiteralPath$configPath-Value$configBlock-EncodingASCIIreturn}$end$lines.Countfor($i$start1;$i-lt$lines.Count;$i){if($lines[$i]-match^\s*Host\s\S){$end$ibreak}}$newLines()if($start-gt0){$newLines$lines[0..($start-1)]}$newLines($configBlock-split\r?\n)if($end-lt$lines.Count){$newLines$lines[$end..($lines.Count -1)]}Set-Content-LiteralPath$configPath-Value$newLines-EncodingASCII}try{$ipAskIPTest-HostValue$ip$userAskUser$port[int](AskPort22)$keyNameAskKey nameid_rsaif($keyName-match[\\/]-or$keyName-in.,..){throwKey name must be a file name, not a path.}$hostAliasAskHost aliasmy-server$sshDirJoin-Path$HOME.ssh$keyJoin-Path$sshDir$keyName$pub$key.pubif(!(Test-Path$sshDir)){New-Item-ItemTypeDirectory-Path$sshDir|Out-Null}$configJoin-Path$sshDirconfig$identityFile($key-replace\\,/)$configBlock Host$hostAliasHostName$ipUser$userPort$portIdentityFile$identityFileIdentitiesOnly yes HostKeyAlgorithms ssh-rsa,ssh-dss PubkeyAcceptedKeyTypes ssh-rsa,ssh-dss PubkeyAcceptedAlgorithms ssh-rsa,ssh-dss if(!(Test-Path$config)){New-Item-ItemTypeFile-Path$config|Out-Null}$configTextGet-Content-LiteralPath$config-Raw-ErrorActionSilentlyContinue$originalConfigText$configTextif(-not(Has-HostConfig$configText$hostAlias)){if([string]::IsNullOrWhiteSpace($configText)){Set-Content-LiteralPath$config-Value$configBlock-EncodingASCII}else{Add-Content-LiteralPath$config-Value$configBlock-EncodingASCII}Write-HostSSH config added: Host$hostAlias-ForegroundColorGreen}else{Set-HostConfigBlock$config$hostAlias$configBlockWrite-HostSSH config updated: Host$hostAlias-ForegroundColorGreen}$configTextGet-Content-LiteralPath$config-Raw-ErrorActionSilentlyContinueif(-not(Has-HostConfig$configText$hostAlias)){throwSSH config was not written correctly: Host$hostAliasnot found in$config}$parsedConfigssh.exe-G-F$config$hostAlias21if($LASTEXITCODE-ne0){throwssh cannot read config:$parsedConfig}if(-not($parsedConfig-match(?m)^hostname\s$([regex]::Escape($ip))\s*$)){throwssh config is not applied correctly: Host$hostAliasdid not resolve to$ip}$keyGenerated$falseif(!(Test-Path$pub)){Write-HostCreating SSH key:$key-ForegroundColorCyan ssh-keygen.exe-trsa-b4096-N-f$key|Out-Null$keyGenerated$true}$cmdumask 077; mkdir -p ~/.ssh; touch ~/.ssh/authorized_keys; TMP~/ssh_pubkey_$$; cat $TMP; grep -qxFf $TMP ~/.ssh/authorized_keys || { echo ~/.ssh/authorized_keys; cat $TMP ~/.ssh/authorized_keys; }; chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys; grep -qxFf $TMP ~/.ssh/authorized_keys echo PUBLIC_KEY_INSTALLED; rm -f $TMPWrite-HostWrite-HostNow enter the server password if ssh asks for it.-ForegroundColorYellow Write-HostConnecting with SSH config:$hostAlias...-ForegroundColorCyan$knownHostsJoin-Path$HOME.ssh\known_hosts$hadKnownHostsTest-Path$knownHostsif($hadKnownHosts){$originalKnownHostsGet-Content-LiteralPath$knownHosts-Raw-ErrorActionSilentlyContinue}cmd.exe /ctype$pub|ssh.exe-F$config-oConnectTimeout5-oPubkeyAuthenticationno-oPreferredAuthenticationspassword,keyboard-interactive$hostAlias$cmdif($LASTEXITCODE-ne0){# Cleanup: restore config to original state if password auth failsif([string]::IsNullOrWhiteSpace($originalConfigText)){Remove-Item-LiteralPath$config-Force-ErrorActionSilentlyContinue Write-HostConfig file removed (was empty before this run).-ForegroundColorYellow}else{Set-Content-LiteralPath$config-Value$originalConfigText-EncodingASCII Write-HostConfig restored to original state.-ForegroundColorYellow}if($keyGenerated){Remove-Item-LiteralPath$key,$pub-Force-ErrorActionSilentlyContinue Write-HostGenerated key files removed.-ForegroundColorYellow}if($hadKnownHosts){Set-Content-LiteralPath$knownHosts-Value$originalKnownHosts-EncodingASCII Write-Hostknown_hosts restored to original state.-ForegroundColorYellow}else{Remove-Item-LiteralPath$knownHosts-Force-ErrorActionSilentlyContinue Write-Hostknown_hosts file removed.-ForegroundColorYellow}throwssh password authentication failed with exit code$LASTEXITCODE}Write-HostWrite-HostTesting key login ...-ForegroundColorCyanssh.exe-F$config-oBatchModeyes-oConnectTimeout5$hostAliasecho KEY_LOGIN_OKif($LASTEXITCODE-ne0){throwpublic key was installed, but key login still failed}Write-HostWrite-HostDone. Use this command next time:-ForegroundColorGreen Write-Hostssh$hostAliasWrite-Hostor:Write-Hostssh -i$key-p$port$user$ip } catch { Write-Host Write-Host Failed:$($_.Exception.Message)-ForegroundColorRed}把上述代码保存为.bat文件双击启动依次键入IP用户名密钥名主机别名密码出现PUBLIC_KEY_INSTALLED和 KEY_LOGIN_OK即代表成功。最后可以使用ssh [主机别名]测试免密配置是否成功。