溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PowerShell 多線程測(cè)試IP端口

發(fā)布時(shí)間:2020-10-12 21:45:18 來(lái)源:網(wǎng)絡(luò) 閱讀:6447 作者:beanxyz 欄目:開(kāi)發(fā)技術(shù)

最近在學(xué)Python的爬蟲(chóng),昨天試著用多線程去使用不同的代理IP,基本原理是把所有的IP地址都放入一個(gè)隊(duì)列,然后使用多線程地去讀取隊(duì)列里面的值。

今天突然想到,類(lèi)似的方式在PowerShell里面能不能實(shí)現(xiàn)呢?PowerShell自己沒(méi)有直接可以使用的隊(duì)列模塊,不過(guò)可以調(diào)用.Net里面的類(lèi)來(lái)實(shí)現(xiàn)。

下面是一個(gè)簡(jiǎn)單的例子


$queue = [System.Collections.Queue]::Synchronized( (New-Object System.Collections.Queue) )

$lines=gc C:\temp\thebigproxylist-17-12-20.txt

foreach($line in $lines){
    $queue.enqueue($line)
}

write-host $queue.count

$Throttle = 5 #threads

#腳本塊,對(duì)指定的IP測(cè)試端口,結(jié)果保存在一個(gè)對(duì)象里面

$ScriptBlock = {
   Param (
      [string]$value
   )

   $ip=$value.Split(":")[0]
   $port=$value.Split(":")[1]
   $a=test-netconnection -ComputerName $ip -Port $port

   $RunResult = New-Object PSObject -Property @{

      ComputerName=$ip
      Port=$port
      TCP=$a.TCPTestSucceeded

   }
   Return $RunResult
}

#創(chuàng)建一個(gè)資源池,指定多少個(gè)runspace可以同時(shí)執(zhí)行

$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, $Throttle)
$RunspacePool.Open()
$Jobs = @()

for($i=1;$i -lt 20;$i++){
    $currentvalue=$queue.Dequeue()
    Write-Host $currentvalue
    $Job = [powershell]::Create().AddScript($ScriptBlock).addargument($currentvalue)
    $Job.RunspacePool = $RunspacePool
    $Jobs += New-Object PSObject -Property @{
      Server = $currentvalue
      Pipe = $Job
      Result = $Job.BeginInvoke()
   }

}

 #循環(huán)輸出等待的信息.... 直到所有的job都完成 

Write-Host "Waiting.." -NoNewline
Do {
   Write-Host "." -NoNewline
   Start-Sleep -Seconds 1
} While ( $Jobs.Result.IsCompleted -contains $false)
Write-Host "All jobs completed!"

#輸出結(jié)果 
$Results = @()
ForEach ($Job in $Jobs)
{   $Results += $Job.Pipe.EndInvoke($Job.Result)
}

$Results

結(jié)果如下

Waiting................................................................................All jobs completed!

Port ComputerName TCP


80 137.74.168.174 True
8080 103.28.161.68 True
53281 91.151.106.127 False
3128 177.136.252.7 True
80 47.89.22.200 True
8888 118.69.61.57 True
8080 192.241.190.167 True
80 185.124.112.130 True
3128 83.65.246.181 True
3128 79.137.42.124 True
8080 95.0.217.32 False
8080 104.131.94.221 True
65301 177.234.7.66 True
8080 37.57.179.2 False
8080 197.211.27.234 True
8080 139.59.117.11 True
8080 168.0.158.53 False
8080 154.48.196.1 True
8080 139.59.125.53 True

成功!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI