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

}

}

}

相关推荐
vx_BS813303 分钟前
【项目编号:project51629】Spring Boot 乡村自来水缴费系统:把抄表、水费生成与在线缴费做成一条数字化闭环
java·spring boot·eclipse·tomcat·maven
qq_2695067512 分钟前
第29课-Servlet基础
java
晚安日记wanna21 分钟前
Vue2 的 defineProperty 差在哪四层追问筛掉九成候选人
前端·vue.js·面试
毅炼24 分钟前
不写多语言 SDK,怎么让 Python、Go、Node 服务接入注册中心?
java·后端·系统架构·gateway
TiDi25 分钟前
吸顶导航交互实现
前端
kisshyshy28 分钟前
从Props透传到自定义Hook:系统梳理React跨层级通信与逻辑复用
前端·架构·代码规范
2501_9378609428 分钟前
上篇:网络编程基础与UDP套接字编程
java·网络·计算机网络
yume_sibai30 分钟前
05-Flutter实战项目
前端·flutter
Methy31 分钟前
IoTHub半个月崩了五次?都是裸rethrow惹的祸
服务器·c++·后端
泡海椒33 分钟前
jquick-pdf 表格行列尺寸控制实战:单元格合并的可行边界
java·开发语言·pdf