Need an advise on how to create an automate script to check connectivity from multiple servers to one server (DB) within Windows server environment either with telnet/portqry and also the script will create a .txt file for unsuccessful connection
Thanks in advance for your help
Claudia
Take a look at IPSentry. We've been using it for a number of years in a mixed Windows/UNIX/Linux environment and found it works well.
Why don't you just ping it?
if ping -q -c 1 yourserver; then
echo 'server is online'
else
echo 'server is offline'
fi
I think this question is similar.
This is bash because you have used bash tag
If you need to check specific port, then you can use this code:
timeout 10 "telnet server port"
if [[ $? == 124 ]]; then # timeout is going to exit with 124 code if it timeouts because of the telnet
echo 'server is online'
else
echo 'server is offline'
fi
Since you claim in the comments that you are really trying to test connectivity into a Sql Server, why not use .Net SqlConnection class? Like so,
$server = "server\instance"
$conStr = "Data Source=$server;Integrated Security=true;Initial Catalog=master;Connect Timeout=3;"
$sqlConn = new-object ("Data.SqlClient.SqlConnection") $conStr
try {
$sqlConn.Open()
if ($sqlConn.State -eq 'Open') {
$sqlConn.Close();
write-host "$server is alive."
} else {
write-host "$server connection problem: $($sqlConn.State.ToString())"
}
} catch {
write-host "$server is unavailable:"
}
Related
Percona MongoDB with LDAP is not working for more than 2 concurrent threads even if the connection pool configured for more than 2.
MongoDB Configuration,
setParameter:
saslauthdPath: /app/mongo/mongoldap/var/run/saslauthd/mux
authenticationMechanisms: PLAIN,SCRAM-SHA-1
ldapConnectionPoolSizePerHost: 10
ldapUseConnectionPool: true
ldapDebug: true
SASL Configuration,
ldap_servers: ldap://ldap.forumsys.com
ldap_mech: PLAIN
ldap_search_base: dc=example,dc=com
ldap_filter: (cn=%u)
ldap_bind_dn: cn=read-only-admin,dc=example,dc=com
ldap_password: password
Test Script (PHP),
<?php
use MongoDB\Driver\Manager as MongoDB;
use MongoDB\Driver\Query as Query;
use MongoDB\Driver\BulkWrite as BulkWrite;
try{
for($i=0;$i<3;$i++){
$handlerName = "handle".$i;
$$handlerName = new MongoDB("mongodb://xx.xx.xx.xx",array("authSource"=>"$external","authMechanism"=>"PLAIN","username"=>"cn=read-only-admin,dc=example,dc=com","password"=>"password","tls"=>true,"tlsCertificateKeyFile"=>"/xyzabc/dbs/mongoclient.pem","tlsCAFile"=>"/xyzabc/dbs/mongoca.pem","tlsAllowInvalidCertificates"=>true));
$filters=array();
$options=array();
$command = new Query($filters,$options);
$query="xyzabc.customerdetails";
$result = $$handlerName->executeQuery($query,$command);
$resultAsJson = $result->toArray();
$resultAsArray = json_decode(json_encode($resultAsJson), True);
print_r(count($resultAsArray));
echo "\n";
sleep(5);
}
for($i=0;$i<3;$i++){
$handlerName = "handle".$i;
$query="xyzabc.client";
$result = $$handlerName->executeQuery($query,$command);
$resultAsJson = $result->toArray();
$resultAsArray = json_decode(json_encode($resultAsJson), True);
print_r(count($resultAsArray));
echo "\n";
}
echo "Success";
}catch(Exception $e){
print_r($e);
echo "Failed";
}
?>
Test Script (Shell script for nohup),
nohup php test.php > output1.log 2>&1 &
nohup php test.php > output2.log 2>&1 &
nohup php test.php > output3.log 2>&1 &
nohup php test.php > output4.log 2>&1 &
nohup php test.php > output5.log 2>&1 &
Test Results,
Script executed in a single thread (same process ID) - there is no error it works for any number of connections
If the same script is executed on nohup (multi-thread or multiple process IDs) - only works for the first two threads, fails for 3rd and above
Error Message (MongoDB log),
LDAPLibraryError: Failed to authenticate 'cn=read-only-admin,dc=example,dc=com' using simple bind; LDAP error: Can't contact LDAP server
Percona MongoDB Version: 4.4.2-4
When the test PHP script is executed synchronously there is no error with the number of connections. I assume this is because the process ID is the same for all the DB connections so it uses the same connection pool.
On the other hand, if it is executed concurrently (with nohup), only the first 2 connections are working, by this, I assume only the first 2 connection pools are working and from 3rd connection pool, the requests are failing.
Since I have ldapConnectionPoolSizePerHost is set to 10, I don't understand why this is not working as expected.
Thanks in advance!
I was executing an nslookup command on powershell and got the output as below:
Server: *****.******.***
Address: ..*.
* *****.******.pvt can't find ..*.**: Server failed
The log capturing this output seems to be empty. is there any way i could capture the server failed error displayed on the host on to a variable?
You'll have to parse the results yourself, but this is how it works:
$variable = & nslookup args 2>&1
$variable
If you are redirecting the output from nslookup, there's no need when you can use the [Net.Dns] class in PowerShell. It returns a [Net.IPHostEntry] if the host exists. example:
try {
if ( [Net.Dns]::GetHostEntry("remoteserver") ) {
"Host exists"
}
}
catch [Management.Automation.MethodInvocationException] {
"Host does not exist"
}
The GetHostEntry method can resolve using a host name or an IP address.
I'm going to be traveling for the next month, and I'd like to automate the VPN connection process so that on X event, the script fires and automatically connects me. I've already configured the [L2TP/IPSec] VPN connection in ms-settings:network-vpn & verified it works, but it's automation step that's proving problematic.
Windows GUI: The credentials have been saved.
PowerShell: The RememberCredential property is set to True
VBScript: Curiously, the VPN connection is hidden:
Dim oShell : Set oShell = CreateObject("Shell.Application")
Dim NetConn : Set NetConn = oShell.Namespace(49)
Dim Connections : Set Connections = NetConn.Items
wscript.echo "Connection Count [" & Connections.Count & "]"
For i = 0 to Connections.Count - 1
wscript.echo "Connections.Item(" & i & ").Name: [" & Connections.Item(i).Name & "]"
next
rasdial <entry>: Expectedly returns error 691.
rasphone -d <entry>: Displays the Connection dialog whereas I'd prefer it to just connect automatically and hidden.
Is this even possible in Windows 10? Or am I just overlooking some small yet key detail?
I ended up leveraging Add-VpnConnectionTriggerApplication to trigger an automatic connection of the VPN on the launch of specific executables/UWP applications. The downside is that when doing this, PoSh warns that SplitTunneling must be enabled which is less than ideal.
However after playing around with it for a while (just 2 or so hours now) to ensure the VPN keys off specific executables/UWP's, I ended up disabling SplitTunneling and, paradoxically, it appears to continue working as I would hope/expect. I rebooted a few times, logged on and sure enough by the time the desktop loaded the VPN had been established.
I need to do more testing to confirm, but this is sufficient to help save me from myself.
I do this by checking the Remember my sign-in info checkbox when I created the VPN connection.
You can check this in your PowerShell script by ensuring that Get-VpnConnection returns RememberCredential : True.
If this is the case, then rasdial should automatically connect it.
I do it with this:
<#
.SYNOPSIS
Ensures vpn connection (assumed to have saved credentials) is connected.
#>
function Connect-Vpn
{
[CmdletBinding()]
param (
[object]
$Settings
)
$rr1 = Get-VpnConnection -Verbose:$false | where {$_.ServerAddress -imatch $Settings.VpnConnectionPattern -and $_.RememberCredential} | Select -First 1
if ($rr1.ConnectionStatus -ne 'Connected')
{
rasdial.exe $rr1.Name
If (-not $LASTEXITCODE)
{
throw "Cannot connect to '$($rr1.Name)'."
}
}
else
{
Write-Verbose "Already connected to '$($rr1.Name)'."
}
}
You will have to massage this code to your needs as this uses some fields from my settings file...
I'm using the AWS CodeDeploy platform for automatic deployment of my REST services. The deployment script got a lot of steps that copy/configure/do other staff. If any of the steps fails - the entire deployment fails for this server and I got a clear notification about it. So, the last step I need is a health check - a validation that configuration was appropriate and all is up and running.
Of cause, I can make a couple curl POSTs, parse their results and use some extracted values within more curl POSTs to get some sanity coverage, but all this parsing sounds like a wheel invention.
Is there any convinient testing framework/tool that can be easily "packed" and invoked in scripts without installing a huge testing siutes on each of my production servers?
Given that you're doing REST you probably can rely on the status codes instead of parsing the body. If you get a code that's not in 2xx, then something is wrong.
If you want a more elaborate check you could add a special endpoint that does some DB queries and maybe sends some harmless queries to its integrations.
And the most complicated option would be to implement a smart post-deployment steps that follow some workflow procedure. You'd need either to use an elaborate bash-scripting, or use more advanced programming languages and frameworks (like RestAssured in Java or RestClient in Groovy).
Don't forget to introduce a loop with some timeout that does a health check since your first request may be sent too early while the app is still being deployed.
Here is an example of simple bash-script that checks the status and the version of the app:
#!/usr/bin/env bash
# Helps to define whether application deployment was successful by checking
# connection to HTTP resource. If the page is loaded and the response is 200
# or 201, then the script finishes successfully. In case connection refused
# is or Gateway Timeout (503) the script is trying to connect again within
# timeout period. Otherwise script finishes with fail.
# Needs required parameter url to application and optional parameters timeout
# (by default equals to 180) and artifact version. If artifact version
# parameter is given and the response is 200 or 201, then script also checks
# that # deployed version (gets from $url/version) equals to the passed
# version. If not, the script finishes with fail. Example of usage in bash
# script:
# sh post_deployment_test.sh http://blah.com/version 100 1.0.102-20160404.101644-5
# result=$?
#
# If $result value equals to 0, then connection is successfully established,
# otherwise, it is not established.
url=$1
timeout=$2
version=$3
if [ -z "$timeout" ]; then
timeout=180
fi
counter=0
delay=3
while [ $counter -le $timeout ]; do
command="curl -L -s -o /dev/null -w %{http_code} $url"
echo "Executing: $command"
status_code=$($command)
curl_code=$?
# Curl error code CURLE_COULDNT_CONNECT (7) means fail to connect to host or proxy.
# It occurs, in particular, in case when connection refused.
if [ $curl_code -ne 0 ] && [ $curl_code -ne 7 ]; then
echo "Connection is not established"
exit 1
fi
if [ $curl_code = 7 ] || [ $status_code = 503 ]; then
echo "Connection has not been established yet, because connection refused or service unavailable. Trying to connect again"
sleep $delay
let counter=$counter+$delay
continue
elif [ $status_code = 200 ] || [ $status_code = 201 ]; then
if [ -z "$version" ]; then
echo "Connection is successfully established"
exit 0
else
grep_result=`curl -L -s $url | grep $version`
if [ -z "$grep_result" ]; then
echo `curl -L -s $url`
echo "Deployed version doesn't equal to expected"
exit 1
else
echo "Connection is successfully established"
exit 0
fi
fi
else
echo "Connection is not established"
exit 1
fi
done
echo "Connection is not established"
exit 1
I've found something nice I was looking for: jasmine-node as a test runtime + frisby.js as a validation script tool.
It's both really portable (I just run npm install during the deployment) and really convenient in terms of scripting, e.g.(official example from frisby):
var frisby = require('frisby');
.get('https://api.twitter.com/1/statuses/user_timeline.json?screen_name=brightbit')
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.expectJSON('0', {
place: function(val) { expect(val).toMatchOrBeNull("Oklahoma City, OK"); }, // Custom matcher callback
user: {
verified: false,
location: "Oklahoma City, OK",
url: "http://brightb.it"
}
})
.expectJSONTypes('0', {
id_str: String,
retweeted: Boolean,
in_reply_to_screen_name: function(val) { expect(val).toBeTypeOrNull(String); }, // Custom matcher callback
user: {
verified: Boolean,
location: String,
url: String
}
})
.toss();
I am trying to start my service with powershell but currently it fails. I don't know why it fails but that is not the point here. When trying to start the host all I don't get the correct exit code so my automatic deploy fails silently.
What I'm trying to do is:
$cmd = "$folder" + "\MyService.exe"
try
{
& $cmd stop
& $cmd uninstall
& $cmd install
& $cmd start
}
catch
{
Write-Host "Error: Update of service failed"
exit 1
}
The start command fails with the following messge:
Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.InvalidOperationException: Cannot start service MyService on computer '.'. ---> System.ComponentModel.Win32Exception: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it
--- End of inner exception stack trace ---
at System.ServiceProcess.ServiceController.Start(String[] args)
at System.ServiceProcess.ServiceController.Start()
at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName)
at Topshelf.Hosts.StartHost.Run()
and I never get into the catch statement of my powershell script.
UPDATE:
Note that I am asking for how to get the method to the catch statement and not the solution to the actual exception. I have solved the actual exception but I want better feedback in the future if it fails, and that is want the catch statement to be executed which it isn't in case of error.
try/catch in PowerShell doesn't work with exe.
After myservice.exe calls you need to check the automatic variable $LastExitCode.
Try something like this:
$out = & $cmd start
if ($LastExitCode -ne 0) # if exe returns 0 on success, if not change the condition accordingly
{
"ERROR: $out"
return # to exit script or do something else.
}