Skip to content

Commit

Permalink
Fix #4
Browse files Browse the repository at this point in the history
  • Loading branch information
BornToBeRoot committed Sep 13, 2022
1 parent fb6ff38 commit 97ee2fd
Showing 1 changed file with 97 additions and 116 deletions.
213 changes: 97 additions & 116 deletions Scripts/IPv4PortScan.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -30,67 +30,61 @@
[CmdletBinding()]
param(
[Parameter(
Position=0,
Mandatory=$true,
HelpMessage='ComputerName or IPv4-Address of the device which you want to scan')]
Position = 0,
Mandatory = $true,
HelpMessage = 'ComputerName or IPv4-Address of the device which you want to scan')]
[String]$ComputerName,

[Parameter(
Position=1,
HelpMessage='First port which should be scanned (Default=1)')]
[ValidateRange(1,65535)]
[Int32]$StartPort=1,
Position = 1,
HelpMessage = 'First port which should be scanned (Default=1)')]
[ValidateRange(1, 65535)]
[Int32]$StartPort = 1,

[Parameter(
Position=2,
HelpMessage='Last port which should be scanned (Default=65535)')]
[ValidateRange(1,65535)]
Position = 2,
HelpMessage = 'Last port which should be scanned (Default=65535)')]
[ValidateRange(1, 65535)]
[ValidateScript({
if($_ -lt $StartPort)
{
throw "Invalid Port-Range!"
}
else
{
return $true
}
})]
[Int32]$EndPort=65535,
if ($_ -lt $StartPort) {
throw "Invalid Port-Range!"
}
else {
return $true
}
})]
[Int32]$EndPort = 65535,

[Parameter(
Position=3,
HelpMessage='Maximum number of threads at the same time (Default=500)')]
[Int32]$Threads=500,
Position = 3,
HelpMessage = 'Maximum number of threads at the same time (Default=500)')]
[Int32]$Threads = 500,

[Parameter(
Position=4,
HelpMessage='Execute script without user interaction')]
Position = 4,
HelpMessage = 'Execute script without user interaction')]
[switch]$Force
)

Begin{
Begin {
Write-Verbose -Message "Script started at $(Get-Date)"

$PortList_Path = "$PSScriptRoot\Resources\ports.txt"
}

Process{
if(Test-Path -Path $PortList_Path -PathType Leaf)
{
Process {
if (Test-Path -Path $PortList_Path -PathType Leaf) {
$PortsHashTable = @{ }

Write-Verbose -Message "Read ports.txt and fill hash table..."

foreach($Line in Get-Content -Path $PortList_Path)
{
if(-not([String]::IsNullOrEmpty($Line)))
{
try{
foreach ($Line in Get-Content -Path $PortList_Path) {
if (-not([String]::IsNullOrEmpty($Line))) {
try {
$HashTableData = $Line.Split('|')

if($HashTableData[1] -eq "tcp")
{
$PortsHashTable.Add([int]$HashTableData[0], [String]::Format("{0}|{1}",$HashTableData[2],$HashTableData[3]))
if ($HashTableData[1] -eq "tcp") {
$PortsHashTable.Add([int]$HashTableData[0], [String]::Format("{0}|{1}", $HashTableData[2], $HashTableData[3]))
}
}
catch [System.ArgumentException] { } # Catch if port is already added to hash table
Expand All @@ -99,30 +93,26 @@ Process{

$AssignServiceWithPort = $true
}
else
{
else {
$AssignServiceWithPort = $false

Write-Warning -Message "No port-file to assign service with port found! Execute the script ""Create-PortListFromWeb.ps1"" to download the latest version.. This warning doesn`t affect the scanning procedure."
}

# Check if host is reachable
Write-Verbose -Message "Test if host is reachable..."
if(-not(Test-Connection -ComputerName $ComputerName -Count 2 -Quiet))
{
if (-not(Test-Connection -ComputerName $ComputerName -Count 2 -Quiet)) {
Write-Warning -Message "$ComputerName is not reachable!"

if($Force -eq $false)
{
if ($Force -eq $false) {
$Title = "Continue"
$Info = "Would you like to continue? (perhaps only ICMP is blocked)"

$Options = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes", "&No")
[int]$DefaultChoice = 0
$Opt = $host.UI.PromptForChoice($Title , $Info, $Options, $DefaultChoice)
$Opt = $host.UI.PromptForChoice($Title , $Info, $Options, $DefaultChoice)

switch($Opt)
{
switch ($Opt) {
1 {
return
}
Expand All @@ -138,63 +128,55 @@ Process{
# Check if ComputerName is already an IPv4-Address, if not... try to resolve it
$IPv4Address = [String]::Empty

if([bool]($ComputerName -as [IPAddress]))
{
$IPv4Address = $ComputerName
}
else
{
# Get IP from Hostname (IPv4 only)
try{
$AddressList = @(([System.Net.Dns]::GetHostEntry($ComputerName)).AddressList)
if ([bool]($ComputerName -as [IPAddress])) {
$IPv4Address = $ComputerName
}
else {
# Get IP from Hostname (IPv4 only)
try {
$AddressList = @(([System.Net.Dns]::GetHostEntry($ComputerName)).AddressList)

foreach($Address in $AddressList)
{
if($Address.AddressFamily -eq "InterNetwork")
{
$IPv4Address = $Address.IPAddressToString
break
}
}
}
catch{ } # Can't get IPAddressList

if([String]::IsNullOrEmpty($IPv4Address))
{
throw "Could not get IPv4-Address for $ComputerName. (Try to enter an IPv4-Address instead of the Hostname)"
}
}
foreach ($Address in $AddressList) {
if ($Address.AddressFamily -eq "InterNetwork") {
$IPv4Address = $Address.IPAddressToString
break
}
}
}
catch { } # Can't get IPAddressList

if ([String]::IsNullOrEmpty($IPv4Address)) {
throw "Could not get IPv4-Address for $ComputerName. (Try to enter an IPv4-Address instead of the Hostname)"
}
}

# Scriptblock --> will run in runspaces (threads)...
[System.Management.Automation.ScriptBlock]$ScriptBlock = {
Param(
$IPv4Address,
$Port
$IPv4Address,
$Port
)

try{
$Socket = New-Object System.Net.Sockets.TcpClient($IPv4Address,$Port)
try {
$Socket = New-Object System.Net.Sockets.TcpClient($IPv4Address, $Port)

if($Socket.Connected)
{
if ($Socket.Connected) {
$Status = "Open"
$Socket.Close()
}
else
{
else {
$Status = "Closed"
}
}
catch{
catch {
$Status = "Closed"
}

if($Status -eq "Open")
{
if ($Status -eq "Open") {
[pscustomobject] @{
Port = $Port
Port = $Port
Protocol = "tcp"
Status = $Status
Status = $Status
}
}
}
Expand All @@ -209,20 +191,19 @@ Process{
Write-Verbose -Message "Setting up Jobs..."

#Set up job for each port...
foreach($Port in $StartPort..$EndPort)
{
$ScriptParams =@{
IPv4Address = $IPv4Address
Port = $Port
}
foreach ($Port in $StartPort..$EndPort) {
$ScriptParams = @{
IPv4Address = $IPv4Address
Port = $Port
}

# Catch when trying to divide through zero
try {
$Progress_Percent = (($Port - $StartPort) / $PortsToScan) * 100
}
catch {
$Progress_Percent = 100
}
$Progress_Percent = (($Port - $StartPort) / $PortsToScan) * 100
}
catch {
$Progress_Percent = 100
}

Write-Progress -Activity "Setting up jobs..." -Id 1 -Status "Current Port: $Port" -PercentComplete ($Progress_Percent)

Expand All @@ -232,7 +213,7 @@ Process{

$JobObj = [pscustomobject] @{
RunNum = $Port - $StartPort
Pipe = $Job
Pipe = $Job
Result = $Job.BeginInvoke()
}

Expand All @@ -245,22 +226,21 @@ Process{
# Total jobs to calculate percent complete, because jobs are removed after they are processed
$Jobs_Total = $Jobs.Count

# Process results, while waiting for other jobs
# Process results, while waiting for other jobs
Do {
# Get all jobs, which are completed
$Jobs_ToProcess = $Jobs | Where-Object -FilterScript {$_.Result.IsCompleted}
$Jobs_ToProcess = $Jobs | Where-Object -FilterScript { $_.Result.IsCompleted }

# If no jobs finished yet, wait 500 ms and try again
if($null -eq $Jobs_ToProcess)
{
if ($null -eq $Jobs_ToProcess) {
Write-Verbose -Message "No jobs completed, wait 500ms..."

Start-Sleep -Milliseconds 500
continue
}

# Get jobs, which are not complete yet
$Jobs_Remaining = ($Jobs | Where-Object -FilterScript {$_.Result.IsCompleted -eq $false}).Count
$Jobs_Remaining = ($Jobs | Where-Object -FilterScript { $_.Result.IsCompleted -eq $false }).Count

# Catch when trying to divide through zero
try {
Expand All @@ -275,8 +255,7 @@ Process{
Write-Verbose -Message "Processing $(if($null -eq $Jobs_ToProcess.Count){"1"}else{$Jobs_ToProcess.Count}) job(s)..."

# Processing completed jobs
foreach($Job in $Jobs_ToProcess)
{
foreach ($Job in $Jobs_ToProcess) {
# Get the result...
$Job_Result = $Job.Pipe.EndInvoke($Job.Result)
$Job.Pipe.Dispose()
Expand All @@ -285,24 +264,26 @@ Process{
$Jobs.Remove($Job)

# Check if result is null --> if not, return it
if($Job_Result.Status)
{
if($AssignServiceWithPort)
{
if ($Job_Result.Status) {
if ($AssignServiceWithPort) {
$Service = [String]::Empty

$Service = $PortsHashTable.Get_Item($Job_Result.Port).Split('|')

if ($PortsHashTable.Get_Item($Job_Result.Port)) {
$Service = $PortsHashTable.Get_Item($Job_Result.Port).Split('|')
}
else {
$Service = @("Unknown", "Unknown")
}

[pscustomobject] @{
Port = $Job_Result.Port
Protocol = $Job_Result.Protocol
ServiceName = $Service[0]
Port = $Job_Result.Port
Protocol = $Job_Result.Protocol
ServiceName = $Service[0]
ServiceDescription = $Service[1]
Status = $Job_Result.Status
Status = $Job_Result.Status
}
}
else
{
else {
$Job_Result
}
}
Expand All @@ -319,6 +300,6 @@ Process{
Write-Verbose -Message "Script finished at $(Get-Date)"
}

End{
End {

}

0 comments on commit 97ee2fd

Please sign in to comment.