美文网首页
PowerShell - 远程访问 Linux 服务器

PowerShell - 远程访问 Linux 服务器

作者: 娃哈哈喜之郎 | 来源:发表于2020-04-02 10:04 被阅读0次

如果我们需要在 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

参考资料

如果这篇文章对您有帮助,记得给作者点个赞,谢谢!

相关文章

网友评论

      本文标题:PowerShell - 远程访问 Linux 服务器

      本文链接:https://www.haomeiwen.com/subject/sbptphtx.html