PowerShell - 远程访问 Linux 服务器

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

参考资料

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容