如果我们需要在Windows系统下,远程访问Linux服务器,需要借助第三方模块Posh-SSH来完成访问和执行远程命令。
首先需要在本地计算机安装Posh-SSH模块
Install-Module-Name Posh-SSH
通过New-SSHSession建立本地计算机和远程Linux服务器之间的会话session
$session=New-SSHSession-ComputerName$server-Port$port-Credential$cred
通过Invoke-SSHCommand在远程Linux服务器上执行shell命令
Invoke-SSHCommand-Command$cmd-SSHSession$session
执行完任务后,记得关系会话session
Remove-SSHSession-SSHSession$session
完整的代码示例
function getCred($username,$password){
$pass=ConvertTo-SecureString$password-AsPlainText-Force
$cred=New-Object System.Management.Automation.PSCredential-ArgumentList$username,$pass
return$cred
}
$server='47.100.1.234'
$port='22'
$username='abc'
$password='123456'
$cred=getCred-username$username-password$password
$session=New-SSHSession-ComputerName$server-Port$port-Credential$cred
$cmd='uname-a'
Invoke-SSHCommand-Command$cmd-SSHSession$session
Remove-SSHSession-SSHSession$session
上一篇:putty连接linux,使用 PuTTY访问远程Linux 服务器
下一篇:没有了