PowerShell - to check multiple Port Status - powershell

I was trying to check whether the port is opened or not using powershell like follows.
My question is : I want to check multiple ports such as 389,53,135. how can we do that?
Here is my script :
$Ipaddress= "xx.xx.xx.xx"
$Port= "389"
$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)
if($t.Connected)
{
"Port $Port is operational"
}
else
{
"Port $Port is closed, You may need to contact your IT team to open it. "
}
My desired output :
Port 389 is operational;Port 53 is operational;Port 135 is operational

Use PowerShells Test-NetConnection and just put that inside a loop that iterates over an array of ports.
For syntax and usage see https://learn.microsoft.com/en-us/powershell/module/nettcpip/test-netconnection?view=windowsserver2022-ps

Related

Laravel ReactPHP Socket server need to restart on day of start

I've created the server in laravel command file & set in supervisor to run the socket server continuously to accept client msg
Laravel Command file code
Server.php
$loop = React\EventLoop\Factory::create();
$IP = getHostByName(getHostName()); // this will get current server IP address // 192.168.0.50
$socket = new React\Socket\Server($IP.':8080', $loop);
$socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
$connection->on('data', function ($data) use ($connection) {
// process data sent from client
});
});
$loop->run();
Client.php
$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);
$connector->connect('192.168.0.50:8080')->then(function (React\Socket\ConnectionInterface $connection) use ($loop,$data) {
$connection->write($data); // sent data to Server.php
});
$loop->run();
This is working fine but when I check on the next day it will be sent data from Client.php but not received at Server.php Then restart Supervisor of Server.php / php artisan server then it working fine for the whole day
I've found what exactly happen.
I've set IP with port 192.168.0.50:8080 to communicate with the server. but checked the next day the IP is changed to 127.0.0.1:8080.
Below is the solution to communicate with any IP address.
Server.php
$loop = React\EventLoop\Factory::create();
$IP = getHostByName(getHostName()); // this will get current server IP address // 192.168.0.50
$IP = '0.0.0.0'; -> set this to I/O to any IP address
$socket = new React\Socket\Server($IP.':8080', $loop);
$socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
$connection->on('data', function ($data) use ($connection) {
// process data sent from client
});
});
$loop->run();
sudo lsof -i -P -n | grep LISTEN -> run this cmd to check 8080 port
with updated code, It's showing now *:8080

I am Trying to connect to an existing BizTalk application and add Receive Ports and Send Ports and Parties etc

When run this I do not get a error, but when I create send ports and Receive locations I don't see anything
make sure the ExplorerOM assembly is loaded
[void] [System.reflection.Assembly]::LoadwithPartialName("Microsoft.BizTalk.ExplorerOM")
Connect to the BizTalk management database
$Catalog = New-Object Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer
$Catalog.ConnectionString = "SERVER=sql\instance; DATABASE=BizTalkMgmtDb; Integrated Security=SSPI"
Connect to an existing application in Biztalk
Create a message to let you know if powershell can't find the applicaiton on your server
If it can't find the application it gives a error and discard changes. If so it continues
$In837_2Cimor = $Catalog.Applications["In837_2Cimor"]
if ($In837_2Cimor -eq $null)
{
Write-Host "`r`nFailed to find `"In837_2Cimor`" deployed on this BizTalk server."
}
else
{
**Register a trap handler for any exceptions**
$ErrorActionPreference="silentlycontinue"
trap { "Exception encountered:`r`n"; $_; "`r`nDiscarding Changes.`r`n";$Catalog.DiscardChanges();exit; }
}
**Create a new receive port named For the new provider**
And A new receive location will also be created and associated
with the receive port.
$NewRP = $In837_2Cimor.AddNewRecievePort($false,$false)
$NewRP.Name = "RP_Pickup999_000"
Note if you don’t set the name property for the receive port,
it will create a new receive location and add it to the receive
port.
**Create a new receive location and add it to the receive port**
$NewRL = $In837_2Cimor.AddNewReceiveLocation($false,$false)
$NewRL.PrimaryTransport.TransportType = $Catalog.ProtocolTypes["FILE"]
$NewRL.PrimaryTransport.Address = "\\location\BizTalkd\"
$NewRL.SendPipeline = $Catalog.Pipelines["Microsoft.BizTalk.DefaultPipelines.PassThruTransmit"]
**Save the changes**
Write-Host "Adding $NewRP.Name..."
$catalog.SaveChanges();
Write-Host "`r`n $NewRP.Name has been created."
Create New In837 sendPorts for a new provider
$NewSP = $In837_2Cimor.AddNewSendPort($false,$false)
$NewSP.Name = "SP_999_TO_FTP_000"
$NewSP.PrimaryTransport.TransportType = $Catalog.ProtocolTypes["FILE"]
$NewSP.SendHandler = $Catalog.SendHandlers["BizTalkServerApplication"]
$NewSP.PrimaryTransport.Address = "\\location\"
$NewSP.SendPipeline = $Catalog.Pipelines["Microsoft.BizTalk.DefaultPipelines.PassThruTransmit"]
Add the filter to New send port
$NewSP.Filter = "<Filter><Group>" +
"<Statement Property='BTS.ReceivePortName' Operator='==' Value='RP_Pickup999_000'/>" +
"</Group></Filter>"
Write-Host Adding ($NewSP.Name) and ($NewRP.Name) and ($NewRL.Name) to catalog...
$Catalog.SaveChanges()

Make a dump of a session on fiddler without modification of Fiddler Rules

I want to do this things :
select a session
make a dump of this session (the issue is here)
Plus, I want to do that without modification of Fiddler Rules. I have done this with a modification of Fiddler Rules but the program will be used on several machines and it can be difficult to change Fiddler Rules in every machines.
I don't know if it is possible.
The code to do that with the modification of the fiddler Rules is :
PowerShell :
$filePath = "...\nameFile.txt" # file which contain the names of fiddler ZIP files
$file = Get-Content $filePath # content of nameFile
foreach ($line in $file) {
start $line # open the file
Write-Host "File : $line open"
Start-Sleep -s 1
}
& "...\Fiddler\ExecAction.exe" "failuresselection" # select all failures and make another file (see Fiddler Rules)
Fiddler Rules :
static function OnExecAction(sParams: String[]): Boolean {
[...]
// Select all failures and put them in a new ZIP file
case "failuresselection":
var path = "...\\Newlogs";
UI.actSelectSessionsWithResponseCode(449);
if (UI.GetFirstSelectedSession() != null){
UI.actSaveSessionsToZip(path+"\\Logs" + 449 + ".saz");
}
// Confirmation
FiddlerObject.StatusText = "Dumped all failures sessions to " + path;
UI.actExit();
return true;
[...]
}
I try this but it doesn't worked :
& "...\Fiddler\ExecAction.exe" "FiddlerApplication.UI.actSelectAll();"
It's to select all line but I think that ExecAction.exe replace QuickExec.
In summary, I am searching a way to do the same thing without modification of Fiddler Rules.

Powershell DSC client can't register with pull server

For the past few days, I have been trying to create a development/test environment where I can automate deployments with DSC.
I have been using WMF5.1.
The pullserver has been set up using the example: Sample_xDscWebServiceRegistrationWithSecurityBestPractices
From xPSDesiredStateConfiguration 5.1.0.0.
configuration Sample_xDscWebServiceRegistrationWithSecurityBestPractices
{
param
(
[string[]]$NodeName = 'CORE-O-DSCPull.CORE.local',
[ValidateNotNullOrEmpty()]
[string] $certificateThumbPrint,
[Parameter(HelpMessage='This should be a string with enough entropy (randomness) to protect the registration of clients to the pull server. We will use new GUID by default.')]
[ValidateNotNullOrEmpty()]
[string] $RegistrationKey # A guid that clients use to initiate conversation with pull server
)
Import-DSCResource -ModuleName xPSDesiredStateConfiguration -ModuleVersion '5.1.0.0'
Node $NodeName
{
WindowsFeature DSCServiceFeature
{
Ensure = "Present"
Name = "DSC-Service"
}
xDscWebService PSDSCPullServer
{
Ensure = "Present"
EndpointName = "PSDSCPullServer"
Port = 8080
PhysicalPath = "$env:SystemDrive\inetpub\wwwroot\PSDSCPullServer"
CertificateThumbPrint = $certificateThumbPrint
ModulePath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Modules"
ConfigurationPath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Configuration"
State = "Started"
DependsOn = "[WindowsFeature]DSCServiceFeature"
RegistrationKeyPath = "$env:PROGRAMFILES\WindowsPowerShell\DscService"
AcceptSelfSignedCertificates = $true
UseSecurityBestPractices = $true
}
File RegistrationKeyFile
{
Ensure = 'Present'
Type = 'File'
DestinationPath = "$env:ProgramFiles\WindowsPowerShell\DscService\RegistrationKeys.txt"
Contents = $RegistrationKey
}
}
}
I apply the MOF file to my pull server without issues. I create a meta MOF using the same example:
[DSCLocalConfigurationManager()]
configuration Sample_MetaConfigurationToRegisterWithSecurePullServer
{
param
(
[ValidateNotNullOrEmpty()]
[string] $NodeName = 'CORE-O-DSCPull.CORE.local',
[ValidateNotNullOrEmpty()]
[string] $RegistrationKey, #same as the one used to setup pull server in previous configuration
[ValidateNotNullOrEmpty()]
[string] $ServerName = 'CORE-O-DSCPull.CORE.local' #node name of the pull server, same as $NodeName used in previous configuration
)
Node $NodeName
{
Settings
{
RefreshMode = 'Pull'
}
ConfigurationRepositoryWeb CORE-O_PullSrv
{
ServerURL = "https://$ServerName`:8080/PSDSCPullServer.svc" # notice it is https
RegistrationKey = $RegistrationKey
ConfigurationNames = #('Basic')
}
}
}
I apply the LCM settings to my pull-server without a problem.
I can create a simple basic.mof and use DSC to apply it. All this works fine.
Next, I create another meta.mof file for another node to let it register to my pull-server. I use the same configuration as above except for the nodename, which I change to the name of the other node. I use the command:
Set-DscLocalConfigurationManager -ComputerName <nodename> -path <pathtonewmetamof>
This command works correctly. That machine can then use DSC to apply the same basic.mof without problems.
Here comes the problem:
I restart my pull server and node, create a new basic.mof and try to apply this to both my machines. This procedure works fine on the pull server itself, but my node can no longer apply the basic.mof, because it will no longer register with my pull-server. I have replicated this many times, where I would install both machines from scratch and configure them. Every time I restart my machines, registration stops working. See the error below:
Registration of the Dsc Agent with the server https://CORE-O-DSCPull.CORE.local:8080/PSDSCPullServer.svc failed. The underlying error is: Failed to register Dsc
Agent with AgentId 1FE837AA-C774-11E6-80B5-9830B2A0FAC0 with the server
https://core-o-dscpull.core.local:8080/PSDSCPullServer.svc/Nodes(AgentId='1FE837AA-C774-11E6- 80B5-9830B2A0FAC0'). .
+ CategoryInfo : InvalidResult: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : RegisterDscAgentCommandFailed,Microsoft.PowerShell.DesiredStateConfiguration.Commands.RegisterDscAgentCommand
+ PSComputerName : CORE-O-DC.CORE.local
So, my problem is that registration seems to work fine until I reboot the pull server. Does anyone have any idea what can cause this issue?
For those wondering if I managed to fix this, yes I did.
It appears to be a bug in WMF5.0 and I was only using WMF5.1 on the pullserver. Not on the node. So I had to update that and now it is working.
As explained in this blog entry the low-level problem is that WMF 5.0 uses TLS 1.0 to communicate with the server, while WFM 5.1 does no longer support TLS 1.0.
In the aforementioned entry you will find two solutions: one that implies upgrading WMF in every and each of the nodes, and another that allows less secure connections by modifying the register in the server.

How do I retrieve PR_RULE_ACTIONS via PowerShell and the EWS Managed API?

I have need of retrieving and inspecting the delegate forwarding rule (the built-in delegate commands in EWS being inadequate for my needs since they choke on groups being used as delegates).
I am able to successfully locate the rule created by "Schedule+ EMS Interface". However, I am unable to retrieve PR_RULE_ACTIONS. Turning on tracing.
I see that the PidTagRuleMsgProvider property is getting returned just fine, but PR_RULE_ACTIONS never does.
I suspect that I am using the wrong MAPI property type in the propertyset definition, but I've gone through everything listed at http://msdn.microsoft.com/en-us/library/exchangewebservices.mapipropertytypetype(v=exchg.140).aspx . Any clues?
Here is the relevant snippet of code:
# Setup Basic EWS Properties for Message Search - Used to locate Hidden Forwarding Rule
$searchFilterForwardRule = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Rule", [Microsoft.Exchange.WebServices.Data.ContainmentMode]::Prefixed, [Microsoft.Exchange.WebServices.Data.ComparisonMode]::Exact)
$itemViewForwardRule = New-Object Microsoft.Exchange.WebServices.Data.ItemView(30, 0, [Microsoft.Exchange.Webservices.Data.OffsetBasePoint]::Beginning)
$itemViewForwardRule.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, [Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
$itemViewForwardRule.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
# Properties for Hidden Delegate Forwarding Rule
$PID_TAG_RULE_MSG_PROVIDER = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65EB,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)
$PID_TAG_RULE_ACTIONS = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6680,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
# Property Set for Delegate Forward Rule
$propertySetForwardRule = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, $PID_TAG_RULE_MSG_PROVIDER)
$forwardRuleExists = $false
$findResults = $service.FindItems([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $searchFilterForwardRule, $itemViewForwardRule)
If ($findResults.TotalCount -lt 1) {
Write-Error "Failed to find rule" "Error"
} Else {
Foreach ($item in $findResults.Items) {
$item.Load($propertySetForwardRule)
If ($item.ExtendedProperties.Count -ge 1) {
If ($item.ExtendedProperties[0].Value -eq "Schedule+ EMS Interface") {
$forwardRuleExists = $true
write-host "Delegate forwarding rule found." -ForegroundColor Cyan
$propertySetForwardRule.Add($PID_TAG_RULE_ACTIONS)
$item.Load($propertySetForwardRule)
Write-Host "Attempting to retrieve x6680 PR_RULE_ACTIONS (PidTagRuleActions)" -ForegroundColor Cyan
$PR_RULE_ACTIONS = $null
if($Item.TryGetProperty($Pid_Tag_Rule_Actions,[ref]$PR_RULE_ACTIONS)){
return $PR_RULE_ACTIONS
} # endif
else {write-host "TryGetProperty for PR_RULE_ACTIONS failed!" -ForegroundColor Red
} # endelse
} # End If - Correct Message
} # End If - Has Extended Properties
} # End ForEach
} # End If - Message Count
Glen Scales was able to set me on the right path. It turns out that PR_RULE_ACTIONS is not exposed via EWS, but the same data exposed via an attribute called PR_EXTENDED_RULE_ACTIONS. Now I'm happily slinging code to parse the binary blob.
http://msdn.microsoft.com/en-us/library/ee218391(v=EXCHG.80).aspx
The property tag for PR_RULE_ACTIONS is 0x668000FE. You can see it (and the property data) in OutlookSpy (I am its author) - go to the Inbox folder, click IMAPIFolder button, go to the PR_RULES_TABLE tab, select the rule, double click on the PR_RULE_ACTIONS property.
Note that PT_ACTIONS MAPI type (0x000FE) is only accessing in Extended MAPI, I don't think EWS will be able to return it.