我在文本文件中有一个 ips 列表。该脚本读取 ips 列表并尝试连接到每个 ips。这部分正在工作。
当脚本找到对用户无权访问的 IP 时,会返回一些消息。我想捕获字符串“拒绝访问”以创建一个无权访问我的用户的 ips 列表。
PS X:\PATH\USER> .\script.ps1
XXX.XXX.XXX.XXX
Access denied
Access denied
Access denied
Access denied
Access denied
FATAL ERROR: Server sent disconnect message
type 2 (protocol error):
"Too many authentication failures for XXXX"
Using username "XXXX".
Access denied
文件(ips.txt)内部包含:
xxx.xxx.xxx.xx1
xxx.xxx.xxx.xx2
xxx.xxx.xxx.xx3
xxx.xxx.xxx.xx4
.
.
.
xxx.xxx.xxx.xxn
脚本.ps1
$ipsarray=(get-content ips.txt)
$size=(get-content ips.txt).Length
Function Invoke-SSHCommands {
Param($Hostname,$Username,$Password, $CommandArray, $PlinkAndPath, $ConnectOnceToAcceptHostKey = $true)
$Target = $Username + '@' + $Hostname
$plinkoptions = "-ssh $Target -pw $Password"
$CommandArray += "exit"
$remoteCommand = ""
if($ConnectOnceToAcceptHostKey)
{
$PlinkCommand = [string]::Format('echo y | & "{0}" {1} exit', $PlinkAndPath, $plinkoptions )
$msg = Invoke-Expression $PlinkCommand
}
$PlinkCommand = [string]::Format('& "{0}" {1} "{2}"', $PlinkAndPath, $plinkoptions , $remoteCommand)
$msg = Invoke-Expression $PlinkCommand
}
$PlinkAndPath = "XXXX\plink.exe"
$Username = "XXX"
$Password = "XXX"
for ($i=0; $i -lt $size; $i++) {
$Hostname=$ipsarray[$i]
Write-Host $Hostname
Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands
}
嗨大卫。我将重复结构中的代码更改为
for ($i=0; $i -lt $tamanho; $i++) {
$Hostname=$vetor[$i]
Write-Host $Hostname
$response = Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands
if ($null -ieq $response) {
write-host "EMPTY"
}
else {
write-host $response
}
}
该行正在与操作系统交互。我看不到如何捕捉它返回的内容。响应被发送到终端,换句话说,不返回到脚本。
$response = Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands
以下条件始终为 EMPTY
if ($null -ieq $response) {
write-host "EMPTY"
}
else {
write-host $response
}
我更改了 if 语句以检查变量的类型
if ($null -ieq $response) {
$response.GetType().Name
write-host "EMPTY"
}
变量 $response 的结果始终为空
You can not call a method on a null expression.
X:\PATH\USER\script.ps1:xx caractere:xx
+ $response.GetType <<<< ().Name
+ CategoryInfo : InvalidOperation: (GetType:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
现在我决定测试变量 $msg 返回的结果是什么,并将代码行更改为:
$msg = Invoke-Expression $PlinkCommand
return $msg
循环(for)的示例更改为测试变量 $msg 的返回。
for ($i=0; $i -lt $tamanho; $i++) {
$Hostname=$vetor[$i]
Write-Host $Hostname
$response = Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands
if ($null -eq $response) {
write-host "NULL"
}
else {
write-host $response
}
}
函数调用后 if 中显示的示例。永远不要返回“拒绝访问”
user@xxx.xxx.xxx.xxx's password: user@xxx.xxx.xxx.xxx's password: user@xxx.xxx.xxx.xxx's password: user@xxx.xxx.xxx.xxx's password: root@xxx.xxx.xxx.xxx's password: