用PowerShell通过Posh-SSH免密码自动登录Linux并执行命令
作者:互联网
Synology NAS用key做免密码认证SSH访问,尝试了设定,不得其门而入,因此尝试其他方法,找到这个PowerShell插件Posh-SSH可以实现https://github.com/darkoperator/Posh-SSH,具体安装步骤如下。
查看Powell版本命令:Get-Host | Select-Object Version
Posh-SSH要求5.1或7.x以上版本,需要升级powershell,
机器是server2012 R2版本,下载地址:
安装完后会要求重启系统,完成后检查版本
尝试按照GIT上面提示的命令安装:Install-Module -Name Posh-SSH
弹出错误提示:PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories.
用如下2个命令解决这个问题
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet
再次运行命令:Install-Module -Name Posh-SSH
安装完成,接着便可编写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"
标签:ComputerName,Posh,sh,Command,SSH,Linux,New 来源: https://blog.51cto.com/helpdesk/2676433