限制条件
远程用户根目录(/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"