用PowerShell通过Posh-SSH免密码自动登录Linux并执行命令

Synology NAS用key做免密码认证SSH访问,尝试了设定,不得其门而入,因此尝试其他方法,找到这个PowerShell插件Posh-SSH可以实现https://github.com/darkoperator/Posh-SSH,具体安装步骤如下。

查看Powell版本命令:Get-Host | Select-Object Versionimage.png


Posh-SSH要求5.1或7.x以上版本,需要升级powershell,

机器是server2012 R2版本,下载地址:

https://download.microsoft.com/download/6/F/5/6F5FF66C-6775-42B0-86C4-47D41F2DA187/Win8.1AndW2K12R2-KB3191564-x64.msu

安装完后会要求重启系统,完成后检查版本

image.png

尝试按照GIT上面提示的命令安装:Install-Module -Name Posh-SSH

弹出错误提示:PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories.

image.png

扫描二维码关注公众号,回复: 13001380 查看本文章

用如下2个命令解决这个问题

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet

image.png

再次运行命令:Install-Module -Name Posh-SSH

image.png

安装完成,接着便可编写PowerShell脚本操作

$Password = "abcd1234562"
$User = "admin"
$ComputerName = "192.168.1.1"
$Command = "ls"

$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)

$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH

Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command # Invoke Command Over SSH

###如果ssh不是用标准22端口,可以在这里指定

$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials -Port 1234

###或者执行sh脚本,在Command处指定:此处发现无法执行sh shellscript的方式, 例如"sh /tmp/test.sh"




猜你喜欢

转载自blog.51cto.com/helpdesk/2676433
今日推荐