Create Self-Signed Certificate for Windows (Server 2012 R2) PowerShell 4.0

Scenario & Environment

Windows 2012 R2 Servers Environment with Powershell 4.0. For some reason servers remain outdated.

Problem Description

Self Signed Certificate is expired or about to be expired, and new one has to be created.

Solution

Open elevated Powershell CLI and create Self Signed Certificate with the following command-let:

New-SelfSignedCertificate -DnsName *.maaz.local, localhost -CertStoreLocation Cert:\LocalMachine\My

New-SelfSignedCertificate cmdlet is restricted for few options for Powershell 4.0 therefore you won’t be able to modify Certificate Expiry which will remain valid for a year from date of generation.

To export the generated certificate as file, go to Start Menu > Manager Computer Certificates > Certificates – Local Computer > Personal > Certificates. Find the certificate you just created (can check it by expiry date easily). Right Click > All Tasks > Export. You will see Certificate Export Wizard, click Next. On Export Private Key options, select “Yes, export the private key”. In Export File Format options just add a check to “Export all extended properties” in addition to the default ones. In Security section select your security settings for Group/Usernames or by opting for Password (or both). Browse to a location and specify the filename. Click Finish.

You can use the same certificate on any server on same domain.

More Resources

https://4sysops.com/archives/create-a-self-signed-certificate-with-powershell/

https://www.petri.com/create-self-signed-certificate-using-powershell

https://docs.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps

https://blogs.technet.microsoft.com/scotts-it-blog/2014/12/30/working-with-certificates-in-powershell/

Advertisements

PRTG Custom Notifications: Outbound Calls on “Down” Alarm

The last blog I wrote about custom file sensor to track an abnormally large file and raise alarm based on that helped me gaining more confidence in PRTG. I am now of opinion that good folks at Paessler AG have tried their level best to make it as open as they could when it comes to customization and integration with other systems. It worked great with Powershell to figure out a problem that could collapse one of my applications, and also, it gave me another idea.

Problem Statement

We use SMS and Email as primary notification channels for any warning or down state alarm. I use Nova Launcher on Note 5 having bug of not showing Email Count on my Nine (for MS Exchange) email client. For SMS, we previously had a product that somehow didn’t turn out to be totally compatible as per our requirement, so we’re developing our own at the moment. Further to this, even if both of them work, they’re not ample enough to wake anyone of us in case something serious happens in night (P.S: We don’t entertain night duties). The best communication medium therefore in such duration of entire day is nothing but the GSM or PSTN calls and we decided to use Robot Calls for “Down” state cases.

Pre-Requisites

  • PRTG (Free or Commercial)
  • CTI Integration Knowledge with your Voice System
  • PRTG Admin Access

PRTG Custom Notification Settings

Login with PRTGAdmin Account or any other account with same permission level and go to Setup > Notifications.

2016-03-12 22_15_07-Windows 7 - Dev [Running] - Oracle VM VirtualBox
PRTG Setup Page
Now click on “Add New Notification” button at the bottom of this page.

2016-03-12 22_23_06-Program Manager
Click on “Add New Notification”

Give this Custom Notification a name and trigger action as per your accord. I wanted to have only Down State therefore I selected as per screenshot:

2016-03-12 22_25_10-Windows 7 - Dev [Running] - Oracle VM VirtualBox
Name & Summarization
Set Access Rights as per your environment:

2016-03-12 22_36_50-Windows 7 - Dev [Running] - Oracle VM VirtualBox
Access Rights
Here starts the real part. In notification actions you have to check on Execute Program option. Provide the credential set which is capable of executing this program. In my case, I wrote a Powershell Script that required admin privileges. Notice the Program File name “Notify.ps1” which is our script – the medium of communication between PRTG and External Application. As per Paessler, here you can Select the program that PRTG executes. You can choose from *.exe, *.bat, *.cmd, *.com or *.ps1 files located in the Notifications/exe subfolder of your PRTG installation. If this list is empty, please copy all files you want to appear to the executables directory.

2016-03-12 22_38_44-Windows 7 - Dev [Running] - Oracle VM VirtualBox
Execute Program Setup

PRTG Host Machine Settings

 

Go to C:\Program Files (x86)\PRTG Network Monitor\Notifications\EXE OR C:\Program Files\PRTG Network Monitor\Notifications\EXE depending upon your 32 or 64 bit machine. This is the folder where you have to save your script. Just an idea about how I am doing it, we have a dialer with an option to keep on looking for a new number in DB table and dial it out the moment it finds one. So what I’m doing with this script is to execute a stored procedure in my MS SQL Server to update the records and once dialer finds it updated, there’s an outbound calls on all numbers inserted via stored procedure. The dialer with robot call option uses particular wav file (I generated one from here). You can use any other as per your requirement.

So here’s the Notify.ps1 making the execution of stored procedure possible:

===========================START===========================
$con = new-object "System.data.sqlclient.SQLconnection"
#Set Connection String
$con.ConnectionString =(“Data Source=mssqlserver.mydomain.local;Initial Catalog=HN_MSSQLDB;Integrated Security=SSPI;User ID=username;Password=mypassword”)
$con.open()
$sqlcmd = new-object "System.data.sqlclient.sqlcommand"
$sqlcmd.connection = $con
$sqlcmd.CommandTimeout = 600000
#Let's Call Remote Procedure
$sqlcmd.CommandText = “EXEC [HN_MSSQLDB].[dbo].[UpdatePRTG]”
$rowsAffected = $sqlcmd.ExecuteNonQuery()

#This section you can use for time stamping with little improvement.
$text = "Alarm Raised Again"
$text | Out-File "C:\Program Files (x86)\PRTG Network Monitor\Notifications\EXE\test.txt"
#Exit 0 is important or the custom notification won't work.
exit 0;
============================END============================

To be honest, the script isn’t doing any extraordinarily intelligent stuff. It’s just communicating with SQL Server which further interacts with dialer. But the good thing is that we can do it pretty easily using PRTG.

Bringing it to Action

For some reason, I couldn’t get this part directly from Paessler’s stock documentation, so I have to use their forum from where I got a response pretty quickly within a day. It was simple enough. Simply navigate to the group/device/sensor for which you want to configure this notification, go to Notification Setting and create new notification as per your requirement. In my case, I wanted to do it for all of my machines and all sensors, so I went to the Root level and did my things as under which were then inherited across all the sensors:

2016-03-12 23_46_43-Windows 7 - Dev [Running] - Oracle VM VirtualBox
Select Root Level
And then create Alarm as under:

2016-03-12 23_52_47-Windows 7 - Dev [Running] - Oracle VM VirtualBox
Add Alarm with Custom Notification Created Earlier

Further Ideas

 

PROVIDED that I find some time, I will try to formulate more general standard setting to use minimal Asterisk based VM with SIP Trunk Setup to open the dialer part for organizations that may require it. Luckily, I didn’t have to work hard at this part in my scenario since we’re having Call Center as our core services.

Another idea is to let this setting be part of default PRTG Notification type, i.e. Email, SMS and SIP Calling (where user can provide SIP Details for calling).

 

PRTG Custom Sensor: Alarm for Large File

Requirement

Need to check for any file larger then let’s say 60 Mb and save its name somewhere, and raise alarm on PRTG.

Tools/Environment

Powershell, PRTG, Windows Server 2012 R2.

Powershell Script

Following script will look for any file larger then 60 Mb, of file type wav, in F:\Dir\SubDir\SubDirL2\SubDirL3\ and will save it to F:\Dir\res.txt and keep it on appending it with the results.

##Mention the path to search the files
$path = “F:\Dir\SubDir\SubDirL2\SubDirL3\”
##Find out the files greater than equal to below mentioned size
$size = 60MB
##Limit the number of rows in text file mentioning file names
$limit = 5
##Find out the specific extension file
$Extension = “*.wav”
##script to find out the files based on the above input
$largeSizefiles = get-ChildItem -path $path -recurse -ErrorAction “SilentlyContinue” -include $Extension | ? { $_.GetType().Name -eq “FileInfo” } | where-Object {$_.Length -gt $size} | sort-Object -property length -Descending | Select-Object Name, @{Name=”SizeInMB”;Expression={$_.Length / 1MB}},@{Name=”Path”;Expression={$_.directory}} -first $limit
IF ($largeSizefiles -eq $NULL)

{
$res = “NORMAL”
$date = Get-Date
Out-File -FilePath F:\Dir\res.txt -InputObject $date -Encoding Default
Out-File -FilePath F:\Dir\res.txt -InputObject $res -Encoding Default -Append
}
ELSE
{
$res = “ERROR”
$date = Get-Date -UFormat “%Y%m%d%H%M%S”
Out-File -FilePath F:\Dir\res.txt -InputObject $date -Encoding Default
Out-File -FilePath F:\Dir\res.txt -InputObject $res -Encoding Default -Append
$largeSizefiles | Out-File -FilePath F:\Dir\res.txt -Encoding Default -Append
}

Run Script Periodically

Using Windows Task Scheduler, the script can be run periodically every 5 minutes. Create new task with following settings:

2016-01-28 16_41_52-10.150.10.160 - Remote Desktop Connection

2016-01-28 16_43_49-10.150.10.160 - Remote Desktop Connection

2016-01-28 16_44_25-10.150.10.160 - Remote Desktop Connection.png

 

PRTG Sensor Settings

  • Go to corresponding probe and the machine where you set up the previous Powershell Script.
  • Go to device list of that machine and add new sensor “File Sensor” with following settings:

2016-01-28 16_52_59-60MB+ Recorded File _ Sensor Details _ PRTG

2016-01-28 16_55_12-60MB+ Recorded File _ Sensor Details _ PRTG2016-01-28 16_56_33-60MB+ Recorded File _ Sensor Details _ PRTG.png

Change Scanning interval to your desired time.

Results:

2016-01-28 16_58_39-60MB+ Recorded File _ Sensor Details _ PRTG

The error will be displayed whenever there’s wav file larger then 60 Mb in the location mentioned earlier. You can also look for any word other then “Error” and raise the alarm.

Directory Replication Between Two Linux Servers

Replicate one directory between two servers without putting additional system or network resources.
1. First it checks the latest file in remote Server (source machine which is actually generating log files).
2. Checks if this files exist locally or not.
3. Creates the file with same name if doesn’t exists.

4. If file exists locally, it checks the number of lines in source.

5. Compares number of lines with local copy.
6. If Number of Lines in Source is greater then Number of Lines in local copy, it gets the new lines.
7. Appends the new lines from Source machine to local copy.
__________________________________________________________________________________________________
#!/bin/bash

file=`ssh root@192.168.1.99 “ls -t /usr/local/src/folder1” | head -1`
nsrc=`ssh root@192.168.1.99 “wc -l /usr/local/src/folder1/$file”  | awk ‘{print $1}’`
ndst=`touch folder1/$file`
ndst=`wc -l folder1/$file  | awk ‘{print $1}’`

declare -i start
start=$ndst+1

for i in $(seq $start $nsrc); do
update=`ssh root@192.168.1.99 “sed -n “${i}{p}” /usr/local/src/folder1/$file”`
echo $update >> /usr/local/src/folder1/$file
done

Checking Remote File for ‘ 404 ‘ Pattern, Send Email If Found (Not Optimized yet)

#!/bin/bash

for (( ; ; ))
do

result =””

echo “Resetting Variables”

sec_latest=”$(ls /home/max/Desktop/SSH\ Watchdog/ -Art | tail -n 1)”

echo “‘”$sec_latest”‘”” was last file modified”

lines_old=”$(grep -c “.*” /home/max/Desktop/SSH\ Watchdog/${sec_latest})”

echo $lines_old

# tocopy=”$(ssh root@192.168.2.200 ‘ls /home/max/Desktop -Art | tail -n 1’)”

# Edit: The previous command doesn’t work with Absolute Path so use this one instead

tocopy=”$(ssh root@192.168.2.200 ‘ls /home/max/Desktop/SSH\ Watchdog/’20130619’* -Art | tail -n 1 | sed ‘s/[^\/]*\///g”)”

echo $tocopy

scp root@192.168.2.200:/home/max/Desktop/${tocopy} /home/max/Desktop/SSH\ Watchdog/

echo “SCP Command Executed”

DATE=$(date +%Y%m%d%H%M%S)

cp /home/max/Desktop/SSH\ Watchdog/${tocopy} /home/max/Desktop/SSH\ Watchdog/$DATE.txt

echo “File Renamed”

lines_new=”$(grep -c “.*” /home/max/Desktop/SSH\ Watchdog/${tocopy})”

echo $lines_new

tocheck=”$(sed “$lines_old,$lines_new!d” /home/max/Desktop/SSH\ Watchdog/${tocopy})”

echo “Data to be checked retrieved”

datachunk=/home/max/Desktop/logs/chunk.txt

echo “$tocheck” > “$datachunk”

echo “datachunk saved”

result=”$(grep -A 0 ” 404 ” ${datachunk})”

echo “$result” > “/home/max/Desktop/logs/${DATE}.chunk”

if [[ “$result” =~ ” 404 ” ]]

then

echo $result

echo “$result” | mutt -s “ERROR” — pointed.out@gmail.com

else

echo “All Is Well”

fi

sleep 1s

done

Bash to check for 404 Errors (with records)

#Start infinite Loop

for (( ; ; ))
do

#Check the Newest File in same director as Script

NEWESTFILE=`ls -tr | tail -1`

#Start Wireshark on Port 80 & Port 443, check for Request & Response coming on these ports, select interface WLAN0 and do this for 15 seconds, print output to
#Text file with name as Date & Time Stamp

sudo tshark tcp port 80 or tcp port 443 -V -R “http.request || http.response” -i wlan0 -T ps -a duration:15 > $(date “+%b_%d_%Y_%H.%M.%S”).txt

#Display latest file name

echo $NEWESTFILE

#Check for 404 Not Found error in latest output file, if found send Email with body “Mail Sent”, Subject “Error” and to the recepient pointed.out@gmail.com
#

if grep -F “404 Not Found” $NEWESTFILE;
then
echo “Error Found”
#echo $NEWESTFILE | mail -s “Error” -a $NEWESTFILE pointed.out@gmail.com
echo $NEWESTFILE | mutt  -a $NEWESTFILE -s “Error” — pointed.out@gmail.com
else
echo “No Error”
 fi
sleep 1
done

Don’t You Be Evil – It’s My Turn Now!

Organize world’s information and make it universally accessible & useful – Google.

Google Evil vs St. Google
Google Evil vs St. Google

Google as a Trend Setter

Larry Page and Sergey Brin decided to set their unofficial slogan as ‘Don’t be Evil’ back in 1998, while they were laying the foundations of Google with merely 16% shares. Since then, Google has been proven itself repeatedly not being an evil when it comes to Information Access & Sharing.  It has been the trendsetters in so many versatile range of services including Online Advertisement (AdSense), Search Engine (Google Search), Smart Phone Operating Systems (Android), Web Browser (Chrome), Maps & Navigation (Google Earth). Google, for sure, has been a trend setter over the internet.

The Support for Openness

Google promotes and supports Open Source in many ways. The usual way of this is to adapt Open Source technologies in their products. The very obvious example of this is the support of WebRTC and its implementation in Chrome. The browser itself has over 750 Million active users as per Google (see here) which gives the organization enough data to analyze, realize and improve the quality of the Open technology being run behind the scenes. From Apache to Python, Google supports a vast number of Open Source projects and organizations. It helps Google a lot, but sometimes, bad things happen… like what happened with XMPP.

The Twist In The Story – XMPP (Jabber) Dilemma

“Google will be releasing a new communications product called Hangouts which users may choose to use instead of Google Talk. The new service does not support XMPP.” – Google I/O 2013.

And then they announced to stop their support for XMPP in their one of the most popular product when it comes to VoIP/Web Conferencing. Apparently, Google did so as Microsoft was taking negative advantage of that by integrating Lync with XMPP that would have enabled Outlook to Google Hangout sessions pretty easily.

Google’s stance seems strange. Dropping an Open Source support just because some closed source vendor is using it to benefit itself, is lame enough. Openness means to be very Open to everyone – even to your competitors. Dropping Jabber support from Hangout is more of the selfishness as there is a whole lot of open source projects that would not be able to go ahead with Hangout. This, for sure, is a real twist in the story of Google Open Source Support!

And The Opportunist Strikes!

And soon after Google decides this, Microsoft announces the connectivity between Skype and Lync enabled platforms… Interesting, isn’t it? Microsoft, that couldn’t capture the market using their epic (usually discouraged) Lync, not trying to penetrate in VoIP using the shield of Skype. This, I believe, is the right time to do so as Viber has recently announced to become next Skype using better tactic, capture the viral Smartphone market first and then extend your support to Desktops to compete Skype.

And The Award of Ultimate Victim Goes To…

The Open Source Community… As they are the ones who are going to be suffered the most. Time is the only factor to decide about how good or bad this move would be for Google but we, the Open Source Community, feel sad to witness this day, when Google, the most favorite of us all, disappointed everyone by dropping their support for XMPP giving Microsoft a chance to promote their closed source stuff.

Enhanced by Zemanta