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

}

}

}

相关推荐
Trouvaille ~8 小时前
【Linux】应用层协议设计实战(一):自定义协议与网络计算器
linux·运维·服务器·网络·c++·http·应用层协议
雯0609~8 小时前
hiprint:实现项目部署与打印3-vue版本-独立出模板设计与模板打印页面
前端·vue.js·arcgis
allway28 小时前
基于华为taishan200服务器、arm架构kunpeng920 cpu的虚拟化实战
linux·运维·服务器
Junlan278 小时前
Cursor使用入门及连接服务器方法(更新中)
服务器·人工智能·笔记
CSCN新手听安8 小时前
【linux】高级IO,I/O多路转接之poll,接口和原理讲解,poll版本的TCP服务器
linux·运维·服务器·c++·计算机网络·高级io·poll
熊文豪8 小时前
服务器炸了才知道?Ward+cpolar让异常无处藏
运维·服务器·cpolar
杜子不疼.8 小时前
【Linux】教你在 Linux 上搭建 Web 服务器,步骤清晰无门槛
linux·服务器·前端
荔枝吻8 小时前
忘记服务器密码,在Xshell7中查看已保存密码
运维·服务器·github
码农阿豪8 小时前
多服务器批量指令管理:从Xshell到自动化运维
运维·服务器·自动化
Pocker_Spades_A8 小时前
在家也能连公司服务器写代码?GoLand+CPolar 远程开发实测
运维·服务器