提问人:AngelOfChaos 提问时间:10/20/2023 更新时间:10/25/2023 访问量:48
通过 SSHShellStream 发送 linux 命令,只返回结果
Send linux Commands through SSHShellStream and return only the results
问:
我正在编写向 powershell 脚本添加函数,该脚本需要向远程 Linux VM 发送命令并获取各种软件的版本。我很接近 - 我有命令,但无法仅返回结果。我正在使用 Posh-ssh 来做到这一点。 为了清楚起见并避免浪费任何人的时间,我不能使用 sshPass 或腻子。它必须是一个 powershell 脚本,我必须使用 sshSession 和 SSHShellStream。
我当前的脚本从 linux 终端返回所有行,但我只想要命令的结果。这是我的功能脚本,删除了敏感信息。
$linuxCreds = #function to retrieve admin credentials to ssh to linux box
$waitOnSSH = 5
$theSession = New-SSHSession -ComputerName <IP Address> -Credential $linuxCreds -AcceptKey:$true
if($theSession) {
Start-Sleep -Seconds $waitOnSSH
$theShellStream = New-SSHShellStream -sshsession $theSession
if($theShellStream){
Start-Sleep -Seconds $waitOnSSH
$results = ""
#Checking McAfee Version
$theShellStream.WriteLine("rpm -qa --queryformat '%{version}-%{release}\n' MFEcma")
Start-Sleep -Seconds $waitOnSSH
$results += $theShellStream.read()
Write-Host "Results: " + $results
}
#End SSH Session
Remove-SSHSession -SSHSession $theSession > $null
}else{
Write-Host "Could not establish session"
}
我当前返回的结果是:
Results:
Last login: Fri Oct 20 03:52:46 CDT 2023 from <IP Address> on pts/0
Last login: Fri Oct 20 03:53:19 2023 from <IP Address>
<m -qa --queryformat '%{version}-%{release}\n' MFEcma
<VersionNumber>
[UserName@ComputerName ~]$
我只想要 VersionNumber,不想要任何其他行 有没有办法只得到它?我正在多台计算机上检查多个软件版本,但如果我能得到第一个,我想我可以得到其余的。感谢您的任何帮助
答:
1赞
AngelOfChaos
10/25/2023
#1
我设法使用 Invoke-SSHCommand 来做到这一点,命令是从 xml 文件中提取的变量。它并不完全“完整”。我的下一步也是提取软件名称并将其链接到版本。到目前为止的代码(将进入上面的 if($theShellStream){ 循环:
$versionCmd = $operatingSystem.Section.Software.VersionCmd
Foreach($command in $versionCmd){
$results = Invoke-SSHCommand -Command $command -SSHSession $theSession
Write-Host $results.Output
}
评论
1.2.3
regex