VSCode免密打开远程目录(一键脚本)

限制条件

远程用户根目录(/home/xxx)的权限必须是700

使用方法 

将如下内容存为.ps1文件-->将ps1文件修改为UTF-8 with BOM格式--->修改ssh用户名,密码,ip--->右键--->使用PowerShell运行。

$ip = "xxx"
$username = "xxx" 
$password = "xxx"
 
 
 
 
# Install-Module命令需要以管理员身份运行
 
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
 
{   
 
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
 
    Start-Process powershell -Verb runAs -ArgumentList $arguments
 
    Break
 
}
 
 
 
 
# 生成rsa key
 
Write-Output "===================[step 1] check and generate rsa key==================="
 
if ((Test-Path $home/.ssh) -and (Test-Path $home/.ssh/id_rsa.pub))
 
{
 
    Write-Output "rsa key is existed!"
 
}
 
else
 
{
 
    if (!(Test-Path $home/.ssh))
 
    {
 
        Write-Output "create .ssh directory"
 
        $null = New-Item  -Path $home/ -Name .ssh -ItemType Directory
 
    }
 
 
 
    Write-Output "generate rsa key"
 
    $null = ssh-keygen.exe -t rsa -f $home/.ssh/id_rsa -C 'myRsa' -N '""' # $null表示此命令的结果不输出到控制台
 
}
 
 
 
 
 
# 将rsa pub上传到服务器中
 
Write-Output "===================[step 2] upload rsa pub to ssh server==================="
 
if(!(Get-Module -ListAvailable Posh-SSH))
 
{
 
    Write-Output "insall Posh-SSH"
 
    $null = Install-Module -Name Posh-SSH -Force
 
}
 
 
 
$secure = $password | ConvertTo-SecureString -AsPlainText -Force 
$cred = New-Object System.Management.Automation.PSCredential($username,$secure) 
$session = New-SSHSession -ComputerName $ip -Credential $cred -AcceptKey
 
Write-Output "get rsa pub from $home/.ssh/id_rsa.pub"
$pubText = Get-Content $home/.ssh/id_rsa.pub #获取windows的公钥
 
$cmd = "mkdir -p ~/.ssh" 
Invoke-SSHCommand -Command $cmd -SSHSession $session  #如果.ssh目录不存在,则创建.ssh目录

$cmd = "chmod 700 ~/.ssh -R" 
Invoke-SSHCommand -Command $cmd -SSHSession $session  #修改.ssh目录权限
 
$cmd = "echo $pubText >> ~/.ssh/authorized_keys"
Invoke-SSHCommand -Command $cmd -SSHSession $session  #将公钥写入服务器的authorized_keys中
 
$cmd = "chmod 600 ~/.ssh/authorized_keys" 
Invoke-SSHCommand -Command $cmd -SSHSession $session  #修改authorized_keys权限
 
Remove-SSHSession -SSHSession $session
 
 
 
cmd /c "pause"

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值