powershell 批量测试ip 端口 脚本

方案1

定义IP地址和端口列表

$ips = @(

"192.168.1.75",

"192.168.1.76",

)

$ports = @(1433,80)

$timeout = 500 # 毫秒

创建结果数组

$results = @()

foreach (ip in ips) {

foreach (port in ports) {

try {

$client = New-Object System.Net.Sockets.TcpClient

connect = client.BeginConnect(ip, port, null, null)

wait = connect.AsyncWaitHandle.WaitOne($timeout) # 等待连接,超时为500毫秒

if ($wait) {

client.EndConnect(connect) # 完成连接

$status = "Open"

} else {

$status = "Timeout" # 超时视为关闭或不可达

}

$client.Close() # 关闭客户端连接

$results += [PSCustomObject]@{

IP = $ip

Port = $port

Status = $status

}

} catch {

$results += [PSCustomObject]@{

IP = $ip

Port = $port

Status = "Error"

ErrorMessage = $_.Exception.Message

}

}

}

}

输出结果

$results | Format-Table -AutoSize

方案2

$computers = "192.168.1.75 # 要测试的计算机列表

$ports = "1433" # 要测试的端口列表

foreach (computer in computers) {

foreach (port in ports) {

result = Test-NetConnection -ComputerName computer -Port $port -InformationLevel Quiet

if (result -eq true) {

Write-Host "computer : Port port is open" -ForegroundColor Green

} else {

Write-Host "computer : Port port is closed" -ForegroundColor Red

}

}

}

相关推荐
华普微HOPERF2 小时前
Matter协议,如何塑造更宜居、流畅的智能家居网络?
服务器·网络·智能家居
万邦科技Lafite2 小时前
京东按图搜索京东商品(拍立淘) API (.jd.item_search_img)快速抓取数据
开发语言·前端·数据库·python·电商开放平台·京东开放平台
默 语3 小时前
MySQL中的数据去重,该用DISTINCT还是GROUP BY?
java·数据库·mysql·distinct·group by·1024程序员节·数据去重
小志biubiu3 小时前
【Linux】Ext系列文件系统
linux·服务器·c语言·经验分享·笔记·ubuntu·操作系统
DooTask官方号3 小时前
DooTask 1.3.38 版本更新:MCP 服务器与 AI 工具深度融合,开启任务管理新体验
运维·服务器·人工智能·开源软件·dootask
oDeviloo4 小时前
新版IntelliJ IDEA个性化设置兼容老版习惯
java·ide·intellij-idea
一只小透明啊啊啊啊4 小时前
Java Web 开发的核心组件:Servlet, JSP,Filter,Listener
java·前端·servlet
你的人类朋友5 小时前
设计模式有哪几类?
前端·后端·设计模式
wanhengidc5 小时前
云手机适配用户有哪些?
服务器·arm开发·安全·智能手机·玩游戏
Yeats_Liao5 小时前
Go Web 编程快速入门 10 - 数据库集成与ORM:连接池、查询优化与事务管理
前端·数据库·后端·golang