练习编写简易端口扫描(增加支持tcp与udp协议切换,增加先探测主机是否存活再进行端口开放探测,可写入文件,可从文件中读取ip,可指定范围端口,可指定特定端口)
【本来想搞个多线程的,但是没搞出来,总是有问题】
param (
[parameter(mandatory=$false)]
[alias('i')]
$ip= "127.0.0.1",
[parameter(mandatory=$false)]
[alias('p')]
$ports,
[parameter(mandatory=$false)]
[alias('f')]
$filename,
[parameter(mandatory=$false)]
[alias('o')]
$result,
[parameter(mandatory=$false)]
[alias('u')]
[switch]$udp,
[parameter(mandatory=$false)]
[alias('t')]
[switch]$tcp
)
if ($tcp -eq $true){
Write-Host "正在使用tcp协议"
}elseif ($udp -eq $true){
Write-Host "正在使用udp协议"
}else {
Write-Host "正在使用tcp协议"
}
function Check-PortStatus($ip, $ports,$udp,$tcp, $result) {
foreach ($port in $ports) {
if ($tcp -eq $true -or ($tcp -eq $false -and $udp -eq $false)){
$socket = New-Object System.Net.Sockets.TcpClient
try {
$socket.Connect($ip, $port)
Write-Host "$ip : $port is open" -ForegroundColor Green
Add-result $result $port $ip
}
catch {
Write-Host "$ip : $port is closed" -ForegroundColor Red
}
finally {
$socket.Dispose()
}
}else {
Check-UdpPortStatus $ip $port
}
}
}
function Check-UdpPortStatus($ip, $port) {
$udpClient = New-Object System.Net.Sockets.UdpClient
try {
$udpClient.Connect($ip, $port)
$udpClient.Send([byte[]](1..255), 255)
$response = $udpClient.Receive([ref]$null)
if($response -ne $null){
Write-Host "$ip : $port is open" -ForegroundColor Green
}else {
Write-Host "$ip : $port is closed" -ForegroundColor Red
}
}
catch {
Write-Host "$ip : $port is closed" -ForegroundColor Red
}
finally {
$udpClient.Close()
}
}
function Add-result($result,$port,$ip,$tcp,$udp){
if ($result.length -ge 0){
if ($tcp -eq $true){
Write-Output "tcp:${ip}:${port}" >> $result
}elseif ($udp -eq $true){
Write-Output "udp:${ip}:${port}" >> $result
}else {
Write-Output "tcp:${ip}:${port}" >> $result
}
}
}
if ($ports -eq $null){
$ports = (21,22,80,443,445,3389)
}
if ($ports -match '-'){
$range = $ports -split '-'
$start = [int]$range[0]
$end = [int]$range[1]
$ports = $start..$end
}
try {
$test = Test-Connection -ComputerName $ip -Count 1 -ErrorAction SilentlyContinue
if ($test -ne $null){
$test1 = $true
}else {
$test1 = $false
}
}catch {
Write-Host " $ip 连接超时"
}
if ($filename -eq $null){
if ($test1 -eq $true){
Check-PortStatus $ip $portS $udp $tcp $result
}else {
Write-Host "$ip 未存活"
}
}else {
$file = Get-Content $filename
foreach ($ip in $file){
try {
$test = Test-Connection -ComputerName $ip -Count 1 -ErrorAction SilentlyContinue
if ($test -ne $null){
$test1 = $true
}else {
$test1 = $false
}
}catch {
Write-Host " $ip 连接超时"
}
if ($test1 -eq $true){
Check-PortStatus $ip $ports $udp $tcp $result
}else {
Write-Host "$ip 未存活"
}
}
}