Syed Jahanzaib Personal Blog to Share Knowledge !

January 28, 2017

Acquiring Cisco Switch Customized Report via Sms/Email

Filed under: Cisco Related — Syed Jahanzaib / Pinochio~:) @ 10:02 AM

img_20170127_163525339


Scenario:

We have few Cisco switches installed in our network. the OP wants to receive specific switch report via email, by sending SMS to the system (on demand or scheduled), and the system should return the detailed report by email with following details ….

The Task is quite simple, and surely it can be done with more better approach or professional coding, but this is just mine exploration which is working fine for my static requirements. We can add about any other information in the script, as per required.


Requirements for report:

  • The report should be customized according to the OP taste. For this purpose we made an script which does the following
  • Check if IP is missing, exit with error, and return error by email to Admin, otherwise Continue to Next Step…
  • Check if IP is invalid, exit with error, and return error by email to Admin, otherwise Continue to Next Step…
  • Check if IP is not accessible by ping, exit with error, and return error by email to Admin, otherwise Continue to Next Step…
  • Check if SNMP UDP port 161 is not accessible by nmap, exit with error, and return error by email to Admin, otherwise Continue to Next Step…
  • Check if remote device is not a Cisco switch, exit with error, and return error by email to Admin, otherwise Continue to Next Step…
  • Automatically check for all available ports like 24/28/48/52 etc,
  • Check Switch Mode/Type/Firmware/CPU Usage/Switch Uptime/Vlan Count etc
  • Check all Ports Up/Down Status / Port Speed / Last Status Change etc
  • Script start/end Time stamp.

Tools Used in this post … [Extra]

  • Kannel/playsms for receiving SMS and execute the script which will in return sends response by email (or sms) [ I have covered kannel and playSMS in my previous guides at my blog]
  • nmap to query remote device SNMP UDP 161 port [you can use some other methods as well]
  • sendEmail tool to send email [you can use some other methods as well]
    • [ I have covered sendEmail tool usage in my previous guide at my blog]

zaiB!


the Script!


#!/bin/sh
# Script to detect Cisco switch Port status / speed / Description with various checks
# Useful for admins who want to query there switch information by SMS ,
# like we can configure this script to be executed from incoming SMS (using playSMS) and send result by email
# Syed Jahanziab
# http:// aacable . wordpress . com / aacable @ hotmail . com

# to debug script , remove # from following line
#set -x

# Color Codes, we can use these codes to color our black world output
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"

# Hostname and other Variables
# Take ip from command line variable
IP="$1"
# Switch SNMP community string
SNMP_STRING="PUBLIC"
HOSTNAME=`hostname`
COMPANY="zaib (Pvt) Ltd."
FOOTER="Powered By Syed.Jahanzaib"
DATE=`date`

# EMAIL RELATED and KANNEL INFO
# for down status, we have to use GMAIL to send email
KANNELURL="127.0.0.1:13013"
KANNELID="kannel"
KANNELPASS="KANNEL_PASS"
CELL1="03333021909"
CELL2="0333XXXXXX"
# GMAIL Section
GMAILID="YOUR_GMAIL_ID@gmail.com"
GMAILPASS="PASS"
ADMINMAIL1="aacableAThotmailDOTcom"
ADMINMAIL2="XXX_XXX@hotmail.com"

#Email Subject Body etc
EMAIL_SUB="INFO: Switch IP $IP - Report @ $DATE"
EMAIL_BODY="/tmp/$ip.email.txt"
echo "
$IP SWITCH QUERY Starts @ $DATE

"

echo "
$IP SWITCH QUERY Starts @ $DATE

" > $EMAIL_BODY
############ DIFFERENT ERROR's VARIABLES ###########
ERR_NOIP="ERROR: Please provide IP of switch

Eaxmple:
portquery 192.168.155.255"

ERR_INVALID_IP="ERROR: Invalid IP address detected. Please provide valid IP of switch

Eaxmple:
portquery 192.168.155.255"

ERR_PING_FAILED="ERROR: Switch IP $IP PING is DOWN ... cannot proceed further... Wziring"
ERR_SNMP="ERROR: Switch IP $IP SNMP not responding. Cannot continue without it... Exiting"
ERR_NO_CISCO="ERROR: $IP - Remote device type doesn't look like CISCO switch... Exiting"

PORTS_TMP_HOLDER="/tmp/$IP.port.numbers"
PORTS_TMP_HOLDER_FINAL="$IP.port.numbers.final"

# If IP is not provided with variable , give error
if [ -z "$IP" ]; then
echo "$ERR_NOIP"
# Send Email reply to Admin for IP not provided error
echo "$ERR_NOIP" >> $EMAIL_BODY
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL2 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
exit 1
fi

# Check for IP addrrss validity, IP must be in format like `port query10.0.0.1`
if expr "$IP" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
echo "IP OK" > /dev/null
else
echo "$ERR_INVALID_IP"
# Send Email reply to Admin for invalid IP
echo "$ERR_INVALID_IP" >> $EMAIL_BODY
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL2 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
exit 1
fi

# Check if REMOTE DEVICE is accessibel or not, if not then EXIT immediately with error / zaib
#if [[ $(ping -q -c 3 P) == @(*100% packet loss*) ]]; then
PING_LOSS=`ping -c 1 -q $IP | grep -oP '\d+(?=% packet loss)'`
if [ "$PING_LOSS" = "100" ]; then
echo "$ERR_PING_FAILED"
# Send Email reply to Admin for IP not responding
echo "$ERR_PING_FAILED" >> $EMAIL_BODY
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL2 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
exit 1
fi

# Check if SNMP port is responding or not, because we require SNMP to query all results
SNMP_PORT_QUERY=`nmap -sU -p 161 $IP | grep open`
if [ -z "$SNMP_PORT_QUERY" ]; then
echo "$ERR_SNMP"
# Send Email reply to Admin for SNMP not responding
echo "$ERR_SNMP" >> $EMAIL_BODY
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL2 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
exit 1
fi

# Determine device OS type, if it doesnt contains 'Cisco IOS' word, then exit
DETECT_SW_OS=`snmpwalk -v1 -c $SNMP_STRING $IP 1.3.6.1.2.1.1.1 | grep -R "Cisco IOS"`
if [ -z "$DETECT_SW_OS" ]; then
echo "$ERR_NO_CISCO"
echo "$ERR_NO_CISCO" >> $EMAIL_BODY
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL2 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
exit 1
fi

# Switch name variable / mib etc
MIB="/cfg/mibs/HOST-RESOURCES-MIB"
SW_NAME=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP iso.3.6.1.2.1.1.5.0`
SW_MODEL=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP .1.3.6.1.2.1.47.1.1.1.1.13.1001`
SW_FW=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP .1.3.6.1.2.1.1.1.0 | sed -n '1p'`
SW_CPU_USAGE=`snmpwalk -Oqvn -v1 -c $SNMP_STRING $IP 1.3.6.1.4.1.9.2.1.56.0`
SW_UPTIME=`snmpwalk -v1 -c $SNMP_STRING $IP .1.3.6.1.2.1.1.3.0 | sed 's:.*)::'`
SW_VLAN_COUNT=`snmpwalk -v1 -c $SNMP_STRING $IP iso.3.6.1.2.1.47.1.2.1.1.2 | wc -l`
# Query Port number after trimming and store in file, it will be used for port counting and switch media type as well / zaib
snmpwalk -v1 -c gt $IP .1.3.6.1.2.1.2.2.1.2 | sed '/Stack\|Vlan\|Null/d' > $PORTS_TMP_HOLDER

# Count total ports in switch
PORT_COUNT=`cat $PORTS_TMP_HOLDER | wc -l`

# Query Switch type like if its megabit or gigabit, we will do it using FAST word, pretty lame but its working good for me / zaib
SW_TYPE_Q=`cat $PORTS_TMP_HOLDER | grep Fast`
if [ -z "$SW_TYPE_Q" ]; then

###########################################################
# Consider Switch as GIGAbit and do actions based upon it #
###########################################################

# Print
INFO_HEADER="Switch Model: $SW_MODEL
Switch Name: $SW_NAME
Switch type: GIGABIT Model
Switch Fw : $SW_FW
Switch Uptime: $SW_UPTIME
Switch CPU Usage: $SW_CPU_USAGE
Switch VLAN Numbers: $SW_VLAN_COUNT

Ports Status :
"
echo "$INFO_HEADER"

# Add text for Email Body
echo "$INFO_HEADER" >> $EMAIL_BODY

# Some junk maths
cat $PORTS_TMP_HOLDER | grep -o -P '.{0,0}101.{0,2}' | sed 's/101//' > $PORTS_TMP_HOLDER_FINAL
cat $PORTS_TMP_HOLDER_FINAL | while read ports
do
num=$[$num+1]
PORT_N=`echo $ports`
PORT_DESC_Q=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP 1.3.6.1.2.1.31.1.1.1.18.101$PORT_N | tr -d '"' | grep -E "[[:alnum:]]"`
SW_PORT_LAST_ST_CHANGE=`snmpwalk -On -v1 -c $SNMP_STRING $IP .1.3.6.1.2.1.2.2.1.9.101$PORT_N | sed 's:.*)::'`
if [ "$PORT_DESC_Q" = "" ]; then
PORT_DESC="n/a"
else
PORT_DESC="$PORT_DESC_Q"
fi
PORT_Q=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP 1.3.6.1.2.1.2.2.1.8.101$PORT_N`
if [ "$PORT_Q" -eq 1 ]; then
PORT_STATUS="UP"
else
PORT_STATUS="DOWN"
fi
if [ "$PORT_STATUS" = "DOWN" ]; then
PORT_SPEED="n/a"
else
PORT_SPEED_Q=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP iso.3.6.1.2.1.2.2.1.5.101$PORT_N`
PORT_SPEED=`echo $(($PORT_SPEED_Q/1000/1000)) mbps`
fi
PORT_NAME=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP 1.3.6.1.2.1.31.1.1.1.18.101$PORT_N`

# Finally Spit out all the info gaterhed by above junk code 😀 / zaib
echo "PORT_Number: $PORT_N / Status: $PORT_STATUS / Name: $PORT_DESC / Speed: $PORT_SPEED / Port_Last_Status_Change = $SW_PORT_LAST_ST_CHANGE"
#echo "PORT_Number: $PORT_N / Status: $PORT_STATUS / Name: $PORT_DESC / Speed: $PORT_SPEED / Port_Last_Status_Change = $SW_PORT_LAST_ST_CHANGE" >> $EMAIL_BODY
done

###########################################################
# Consider Switch as Megabit and do actions based upon it #
###########################################################
else
#Print
INFO_HEADER="Switch Model: $SW_MODEL
Switch Name: $SW_NAME
Switch type: MEGABIT Model
Switch Fw : $SW_FW
Switch Uptime: $SW_UPTIME
Switch CPU Usage: $SW_CPU_USAGE
Switch VLAN Numbers: $SW_VLAN_COUNT

Ports Status :
"
echo "$INFO_HEADER"
# Add text for Email Body
echo "$INFO_HEADER" >> $EMAIL_BODY

cat $PORTS_TMP_HOLDER | grep -o -P '.{0,0}100.{0,2}' | sed 's/100//' > $PORTS_TMP_HOLDER_FINAL
cat $PORTS_TMP_HOLDER_FINAL | while read ports
do
num=$[$num+1]
PORT_N=`echo $ports`
PORT_DESC_Q=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP 1.3.6.1.2.1.31.1.1.1.18.100$PORT_N | tr -d '"' | grep -E "[[:alnum:]]"`
SW_PORT_LAST_ST_CHANGE=`snmpwalk -On -v1 -c $SNMP_STRING $IP .1.3.6.1.2.1.2.2.1.9.100$PORT_N | sed 's:.*)::'`
if [ "$PORT_DESC_Q" = "" ]; then
PORT_DESC="n/a"
else
PORT_DESC="$PORT_DESC_Q"
fi
PORT_Q=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP 1.3.6.1.2.1.2.2.1.8.100$PORT_N`
if [ "$PORT_Q" -eq 1 ]; then
PORT_STATUS="UP"
PORT_SPEED_Q=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP iso.3.6.1.2.1.2.2.1.5.100$PORT_N`
PORT_SPEED=`echo $(($PORT_SPEED_Q/1000/1000)) mbps`
else
PORT_STATUS="DOWN"
PORT_SPEED="n/a"
PORT_NAME=`snmpwalk -Oqv -v1 -c $SNMP_STRING $IP 1.3.6.1.2.1.31.1.1.1.18.100$PORT_N`
fi
# Finally Spit out all the info gaterhed by above junk code 😀 / zaib
echo "PORT_Number: $PORT_N / Status: $PORT_STATUS / Name: $PORT_DESC / Speed: $PORT_SPEED / Port_Last_Status_Change = $SW_PORT_LAST_ST_CHANGE"
echo "PORT_Number: $PORT_N / Status: $PORT_STATUS / Name: $PORT_DESC / Speed: $PORT_SPEED / Port_Last_Status_Change = $SW_PORT_LAST_ST_CHANGE" >> $EMAIL_BODY
done
fi
# Send the result via EMAIL to admin emails as mentioned in start.
# Add footer
DATE=`date`
echo "
Switch Query Ends Here at $DATE

$COMPANY
$FOOTER"
echo "
Switch Query Ends Here at $DATE

$COMPANY
$FOOTER" >> $EMAIL_BODY
/temp/sendEmail-v1.56/sendEmail -u "$EMAIL_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAIL_BODY -o message-content-type=text
#cat $MSGDOWNHOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-

# Script Ends here #

 


Result/Report Sample:

Result via Email:

1- sw-report.PNG


Result in CMD:


#### root@ubuntu:/temp# ./portquery.sh 192.168.255.254

192.168.255.254 SWITCH QUERY Starts @ Sat Jan 28 00:49:07 PKT 2017
Switch Model: "WS-C3750G-24PS-S"
Switch Name: "X-switch"
Switch type: GIGABIT Model
Switch Fw : "Cisco IOS Software, C3750 Software (C3750-IPBASE-M), Version 12.2(35)SE5, RELEASE SOFTWARE (fc1)
Switch Uptime: 13 days, 17:24:37.14
Switch CPU Usage: 6
Switch VLAN Numbers: 57

Ports Status :

PORT_Number: 01 / Status: UP / Name: n/a / Speed: 1000 mbps / Port_Last_Status_Change = 0:01:19.59
PORT_Number: 02 / Status: DOWN / Name: ServerX / Speed: n/a / Port_Last_Status_Change = 0:01:13.07
PORT_Number: 03 / Status: UP / Name: Server4 / Speed: 1000 mbps / Port_Last_Status_Change = 7 days, 23:46:45.26
PORT_Number: 04 / Status: UP / Name: n/a / Speed: 1000 mbps / Port_Last_Status_Change = 7 days, 23:46:44.53
PORT_Number: 05 / Status: UP / Name: n/a / Speed: 1000 mbps / Port_Last_Status_Change = 0:01:16.08
PORT_Number: 06 / Status: UP / Name: n/a / Speed: 1000 mbps / Port_Last_Status_Change = 7 days, 23:46:42.48
PORT_Number: 07 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.07
PORT_Number: 08 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.07
PORT_Number: 09 / Status: DOWN / Name: vlanX / Speed: n/a / Port_Last_Status_Change = 0:01:13.07
PORT_Number: 10 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 13 days, 1:53:58.05
PORT_Number: 11 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 12 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 13 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 14 / Status: DOWN / Name: test-trunk-XX-new / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 15 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 16 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 17 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 18 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 19 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 20 / Status: UP / Name: XXX_gb_media_test / Speed: 1000 mbps / Port_Last_Status_Change = 0:01:16.09
PORT_Number: 21 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 22 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 23 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:13.08
PORT_Number: 24 / Status: DOWN / Name: up_2_jr_sw / Speed: n/a / Port_Last_Status_Change = 0:01:11.68
PORT_Number: 25 / Status: UP / Name: up-2-XXX / Speed: 1000 mbps / Port_Last_Status_Change = 0:01:18.92
PORT_Number: 26 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:11.71
PORT_Number: 27 / Status: DOWN / Name: n/a / Speed: n/a / Port_Last_Status_Change = 0:01:11.72
PORT_Number: 28 / Status: UP / Name: XXX-SWX by FC / Speed: 1000 mbps / Port_Last_Status_Change = 12 days, 10:12:00.62

Switch Query Ends Here at Sat Jan 28 00:49:22 PKT 2017

zaib (Pvt) Ltd.
Powered By Syed.Jahanzaib
Jan 28 00:49:26 ubuntu sendEmail[16553]: Email was sent successfully!


playSMS COMMAND sample config [for incoming sms action]

playsms command.PNG

playSMS log when incoming message with specific keyword ‘switch x.x.x.x’ is received

127.0.0.1 localhost 2017-01-28 01:11:32 PID588ba9743d5c2 - L2 kannel__call # start load:/var/www/playsms/plugin/gateway/kannel/geturl.php
127.0.0.1 localhost 2017-01-28 01:11:32 PID588ba9743d5c2 - L3 kannel__incoming # remote_addr:127.0.0.1 remote_host:localhost t:[2017-01-28 03:11:27] q:[+923333021909] a:[switch X.X.X.X] Q:[13013] smsc:[] smsc:[]
127.0.0.1 localhost 2017-01-28 01:11:32 PID588ba9743d5c2 - L3 recvsms # isrecvsmsd:1 dt:2017-01-28 03:11:27 sender:+923333021909 m:switch X.X.X.X receiver:13013 smsc:
127.0.0.1 localhost 2017-01-28 01:11:32 PID588ba9743d5c2 - L2 kannel__call # end load geturl
- - 2017-01-28 01:11:32 PID58798d2cbeb7d - L3 recvsmsd # id:261 dt:2017-01-28 03:11:27 sender:+923333021909 m:switch X.X.X.X receiver:13013 smsc:
- - 2017-01-28 01:11:32 PID58798d2cbeb7d - L3 recvsms_process # dt:2017-01-28 03:11:27 sender:+923333021909 m:switch X.X.X.X receiver:13013 smsc:
- - 2017-01-28 01:11:32 PID58798d2cbeb7d - L3 gateway_decide_smsc # SMSC supplied:[] configured:[] decided smsc:[]
- - 2017-01-28 01:11:32 PID58798d2cbeb7d - L3 sms__command # command_exec:/var/lib/playsms/sms_command/1/portquery.sh 'X.X.X.X'
- - 2017-01-28 01:11:58 PID58798d2cbeb7d - L3 recvsms_process # feature:sms_command datetime:2017-01-28 03:11:27 sender:+923333021909 receiver:13013 keyword:SWITCH message:X.X.X.X raw:switch X.X.X.X smsc:

once the sms is received the playsms will execute the script, and will reply back by email or sms OR according to the configuration set in the script.


Regard’s

Syed Jahanzaib

January 26, 2017

Check remote windows logged-in user/lock status via BASH

Filed under: Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 10:42 AM

locked

Scenario:

We have Active Directory environment in our office. Clients OS are mixed starting from windows 2000/2003/2008 and Win7.
For some specific reasons/policy, our helpdesk staff is often required to inquire if the employee is working on his workstation or if his/her windows status is locked.

Solution:

Since I am using my Ubuntu box to manage most of the Active Directory functions using Webmin/BASH scripts, therefore I made a small bash script which queries for remote windows logged in user session and windows locked/unlocked status.

The bash script does the following …

  • Check for remote PC PING Status, if ping fails, exit with error
  • Get remote windows IP via NSLOOKUP using local DNS
  • Current Logged-in user and their status
  • Current status of windows either its locked/unlocked.
  • TRIM the results and display according to our taste

the Script!

> root@linux:/temp# cat winuserstatus.sh

#!/bin/bash
# Script to check remote windwos status, like Loggedin + Windows Lock/Unlock status
# More functions can be added/removed as required.
# I attached this script to webmin for our Support dept.
# Syed Jahanzaib / aacable.wordpress.com / aacable @ hotmail . com
# Created: 25-JAN-2017

# set -x
QUSER_HOLDER="/tmp/$1.quser"
LOCK_HOLDER="/tmp/$1.lockstatus"
REMOTE_PC="$1"
PING_ATEMPTS="1"
PING_STATUS="/tmp/$1.ping.status"
LOCAL_DNS_IP="10.0.0.1"

# Domain credentials details so that winexe can execute commands on all domain clients
DOMAIN="domain.local"
DOMAIN_ADMIN="admin"
ADMIN_PASS="password"

# Empty All Holders
> $QUSER_HOLDER
> $LOCK_HOLDER
> $PING_STATUS

# Check if remote PC is accessibel or not,
## IF PING FAILS then inform accordingly and EXIT
ping -q -c $PING_ATEMPTS $REMOTE_PC &>/dev/null > $PING_STATUS
PING_RESULT=`cat $PING_STATUS`
if [ "$PING_RESULT" = "" ]; then
echo "ERROR: Unknown HOST. Exiting"
exit 1
fi

# Print PC NAME (from $1 variable)
echo "
Remote PC = $1"

# Print IP of remote PC via nslookp using local DNS
echo "IP Details =
`nslookup $1 | grep Address | sed /$LOCAL_DNS_IP/d`"

# If ping failed, then print Error and EXIT
if [[ $(ping -q -c $PING_ATEMPTS $REMOTE_PC) == @(*100% packet loss*) ]]; then
echo "$1 not responding to ping request, probably system is not UP"
exit 1
fi

# Query remote windows Logged in user using Linux WINEXE tool
winexe -U $DOMAIN/$DOMAIN_ADMIN%"$ADMIN_PASS" //$1 "quser" > $QUSER_HOLDER
QUSER_RESULT=`cat $QUSER_HOLDER |grep Active`
if [ "$QUSER_RESULT" = "" ]; then
echo "
User Status = No user is active"
else
echo "
User Status = Logged in User found ... details as below ...
$QUSER_RESULT
"
fi

# Query remote windows TASK list to find if windows is locked/unlocked
winexe -U $DOMAIN/$DOMAIN_ADMIN%"$ADMIN_PASS" //$1 "tasklist" > $LOCK_HOLDER
LOCK_RESULT=`cat $LOCK_HOLDER |grep -E "LogonUI.exe|logon.scr"`
if [ "$LOCK_RESULT" = "" ]; then
echo "
Windows Status = Windows is UN-LOCKED!"
else
echo "
Windows Status = Windows is LOCKED"
fi

# Script function ends here
# Thank you


Result:

When User is logged in and windows is LOCKED!

root@linux:/temp# /temp/winuserstatus.sh WORKSTAION-1

Remote PC = WORKSTAION-1
IP Details =
Address: 10.0.0.20
Address: 10.0.0.21

User Status = Logged in User found ... details as below ...
jahan.zaib console 13 Active 1+00:53 1/23/2017 1:57 PM
Windows Status = Windows is LOCKED

When User is logged in and windows is UN-LOCKED!

root@linux:/temp# /temp/winuserstatus.sh WORKSTAION-1

Remote PC = WORKSTAION-1
IP Details =
Address: 10.0.0.21
Address: 10.0.0.20

User Status = Logged in User found ... details as below ...
jahan.zaib console 13 Active 1+00:53 1/23/2017 1:57 PM
Windows Status = Windows is UN-LOCKED!

When User is NOT logged in and windows is LOCKED as well !


root@linux:/temp# /temp/winuserstatus.sh SERVER-2

Remote PC = SERVER-2
IP Details =
Address: 101.11.11.2
No User exists for *

User Status = No user is active

Windows Status = Windows is LOCKED

Regard’s
Syed Jahanzaib

January 19, 2017

Windows Users Centralized Logging with AD & GPO

Filed under: Microsoft Related — Tags: — Syed Jahanzaib / Pinochio~:) @ 7:12 PM

Disclaimer:
This is a reference post for myself, to recall it later when i need it.
There are tons of tools/apps that can automate such tasks, But being lazy/blockhead or fond of fetching result using out of the box approach, I usually try to select method that works for me and which seems easy to me plus with some learning. You may follow the internet to get more elegant / less complicated solution. Read it just to add ideas on how dumb-heads like me doing there work in other dimension approach , lean so that you may enhance it or at least not follow it for many reasons ;). This was a drafted version, later I modified this task for more presentable formatting. Windows batch file is far behind in advance coding as compare to bash, but we understand the limitation dueo to Microsoft platform.

I used WINTAIL to view real time logging of the specific system. we can modify the scripting to any level we want it to be. example we can log this info at our linux based mysql server, email the event, etc etc 😀

Sky is the only limit !

Zaib!


Scenario#1:

We have a domain environment in our office. At one windows 7 workstation, we have some important application installed which is access by specific users Remote (RDP and Dameware remote app) session & dueto some specific issues, the management wanted to store its full logs for following events only …

  1. When user login to the workstation
  2. When user logoff from the workstation
  3. When workstation gets LOCK dueto inactive session (after 5 minutes)
  4. When user connect to any previous session, either local or by remote
  5. When user re-login to the system (unlock)

Following information should be recorded in simple log file at remote server. there must be 2 log file for each user, one for the USER ID , and second for the COMPUTER NAME, so that we can view which users logged in to the PC, or which ID is used to loggedin to the PC. i am unable to explain right now, but later.

  1. Event Type: LOGIN OR LOGOFF
  2. RDP Client IP: If the user is logged in via RDP, his ip should be logged
  3. DAMEWARE IP: If the user is logged in using DAMEWARE remote app, his IP should be logged, it will be triggered by Event ID 1102
  4. Remote Client PC DNS Name: Remote client windows DNS name should be logged
  5. Username: Domain User ID which is being used to logging to the workstation
  6. Computername: name of workstation on which user is logging to
  7. Date / Time

 


Solution:

Since we are using Active Directory, We can use Login/Logoff script using DOMAIN Group Policy. What we will do is to create a new TASK scheduler entry via GPO to trigger task on specific actions like login/logoff/lock/unlock etc.

Requirements:

  • grep
    [Linux tool for windows version, copy its files in shared folder like \\DC1\TOOLS]
  • sed
    [Linux tool for windows version, copy its files in shared folder like \\DC1\TOOLS]
  • login-log.cmd
    This file will add login entry in user/computer log file [Copy it to DC SYSVOL Folder]
  • logoff.cmd
    This file will add logoff entry in user/computer log file [Copy it to DC SYSVOL Folder]
  • lock-log.cmd
    This will log unlock log in user/computer log file [Copy it to DC SYSVOL Folder]
  • Some addition in group policy to add task triggering via GPO

Download grep/sed and place all contents  to some shared location which all user can access example DC1\tools

Create another folder name DC1\userlogs which users can only write in it, but they should not able to browse in it.

Now create files for different tasks


login-log.cmd

@echo off
rem Script to add LOGIN log to our log server
rem *** by Syed Jahanzaib aacable@hotmail.com ***
cls
rem Create Backup folder if not exists already
set TEMPLOC="C:\BACKUP"
if not exist "%TEMPLOC%" mkdir %TEMPLOC%
set LOGLOCAL="%TEMPLOC%\LOCAL.LOG"
set LOGSERVER="\\DC1\userlog\%USERNAME%.log"
set LOGSERVER2="\\DC1\userlog\%COMPUTERNAME%.log"
set IPFILE="%TEMPLOC%\IP.TXT"
set COMPFILE="%TEMPLOC%\COMPNAME.TXT"
set IPADD=
set DAMWIP=
set DAMWIPFILE="%TEMPLOC%\damwipfile.txt"
set COMPNAME=
del %IPFILE% 2> nul
del %COMPFILE% 2> nul
taskkill /F /IM nslookup.exe 2> nul


::# Get IP Address
for /f "skip=1 tokens=2 delims=[]" %%* in (
'ping.exe -n 1 %Computername%') Do (set "LOCALIP=%%*" & goto:exitFor1)
:exitFor1

netstat -na | find "3389" | find "ESTABLISHED" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %IPFILE%
set /p IPADD=<%IPFILE%
IF "%IPADD%"=="" (
set IPADD=x
)


set "filter=c:\backup/ip.txt"
for %%A in (%filter%) do if %%~zA==0 goto :skipname

nslookup %IPADD% | \\DC1\tools\sed -n "4p" | \\DC1\tools\awk "{print $2}" > %COMPFILE%
set /p COMPNAME=<%COMPFILE%

:skipname
netstat -na | find "6129" | find "ESTABLISHED" | \\DC1\tools\sed -n "2p" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %DAMWIPFILE%
set /p DAMWIP=<%DAMWIPFILE%
rem echo %DAMWIP%
set "filter=%DAMWIPFILE%"
rem for %%A in (%filter%) do if %%~zA==0 echo no damw
REM goto :skipdamw

IF "%DAMWIP%"=="127.0.0.1" (
set DAMWIP=x
)

IF "%DAMWIP%"=="" (
goto :nodamw
)

:skipdamw
if "%DAMWIP%"=="x" goto :1
nslookup %DAMWIP% | \\DC1\tools\sed -n "4p" | \\DC1\tools\awk "{print $2}" > c:\backup\damwip.txt
set /p COMPNAME=<c:\backup\damwip.txt
goto :skip
:1
if "%IPADD%"=="x" goto :cond
goto :skip
:cond
set IPADD=LOCAL-LOGIN


:nodamw
set DAMWIP=x
:skip

if "%COMPNAME%"=="" set COMPNAME=LOCAL-LOGIN
echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGSERVER2%
ECHO LOGIN >> %LOGSERVER%
ECHO LOGIN >> %LOGSERVER2%
echo RDP Client IP: %IPADD% - / DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% 
echo Login User: %USERNAME% / To: %COMPUTERNAME% / Local IP: %LOCALIP% / %DATE% %TIME% 

echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER%

echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER2%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER2%

echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGSERVER2%
echo --------------------------------- >> %LOGLOCAL%
ECHO LOGIN >> %LOGLOCAL%
echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGLOCAL%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGLOCAL%

echo --------------------------------- >> %LOGLOCAL%

lock-login.cmd


@echo off
cls
rem *** Script to add workstation is locked entry in log file ***
rem *** Syed Jahanzaib aacable@hotmail.com ***
rem Create Backup folder if not exists already
set TEMPLOC="C:\BACKUP"
if not exist "%TEMPLOC%" mkdir %TEMPLOC%
set LOGLOCAL="%TEMPLOC%\LOCAL.LOG"
set LOGSERVER="\\DC1\userlog\%USERNAME%.log"
set LOGSERVER2="\\DC1\userlog\%COMPUTERNAME%.log"
set IPFILE="%TEMPLOC%\IP.TXT"
set COMPFILE="%TEMPLOC%\COMPNAME.TXT"
set IPADD=
set DAMWIP=
set DAMWIPFILE="%TEMPLOC%\damwipfile.txt"
set COMPNAME=
del %IPFILE% 2> nul
del %COMPFILE% 2> nul
taskkill /F /IM nslookup.exe 2> nul
::# Get IP Address
for /f "skip=1 tokens=2 delims=[]" %%* in (
'ping.exe -n 1 %Computername%') Do (set "LOCALIP=%%*" & goto:exitFor1)
:exitFor1

netstat -na | find "3389" | find "ESTABLISHED" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %IPFILE%
set /p IPADD=<%IPFILE%
IF "%IPADD%"=="" (
set IPADD=x
)
set "filter=c:\backup/ip.txt"
for %%A in (%filter%) do if %%~zA==0 goto :skipname

nslookup %IPADD% | \\DC1\tools\sed -n "4p" | \\DC1\tools\awk "{print $2}" > %COMPFILE%
set /p COMPNAME=<%COMPFILE%

:skipname
netstat -na | find "6129" | find "ESTABLISHED" | \\DC1\tools\sed -n "2p" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %DAMWIPFILE%
set /p DAMWIP=<%DAMWIPFILE%
rem echo %DAMWIP%
set "filter=%DAMWIPFILE%"
rem for %%A in (%filter%) do if %%~zA==0 echo no damw
REM goto :skipdamw

IF "%DAMWIP%"=="127.0.0.1" (
set DAMWIP=x
)

IF "%DAMWIP%"=="" (
goto :nodamw
)

:skipdamw
if "%DAMWIP%"=="x" goto :1
nslookup %DAMWIP% | \\DC1\tools\sed -n "4p" | \\DC1\tools\awk "{print $2}" > c:\backup\damwip.txt
set /p COMPNAME=<c:\backup\damwip.txt
goto :skip
:1
if "%IPADD%"=="x" goto :cond
goto :skip
:cond
set IPADD=LOCAL-LOGIN
:nodamw
set DAMWIP=x
:skip

if "%COMPNAME%"=="" set COMPNAME=LOCAL-LOGIN
echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGSERVER2%
ECHO LOCKED >> %LOGSERVER%
ECHO LOCKED >> %LOGSERVER2%
echo RDP Client IP: %IPADD% - / DW IP: %DAMWIP% / Remote Client PC: %COMPNAME%
echo Login User: %USERNAME% / To: %COMPUTERNAME% / Local IP: %LOCALIP% / %DATE% %TIME%

echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER%

echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER2%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER2%

echo --------------------------------- >> %LOGSERVER%

REM --- LOCAL LOG FILE
echo --------------------------------- >> %LOGLOCAL%
ECHO LOCK >> %LOGLOCAL%
echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGLOCAL%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGLOCAL%

echo --------------------------------- >> %LOGLOCAL%


LOGOFF.CMD

@echo off
echo LOGOFF -- Username: %USERNAME% / PC_name: %COMPUTERNAME% / Local_ip: %LOCALIP% / Rdp_client: %CLIENTNAME% / %DATE% %TIME% >> \\DC1\userlog\%USERNAME%.log
echo LOGOFF -- Username: %USERNAME% / PC_name: %COMPUTERNAME% / Local_ip: %LOCALIP% / Rdp_client: %CLIENTNAME% / %DATE% %TIME% >> \\DC1\userlog\%COMPUTERNAME%.log

 


RELOGIN-LOG.CMD

@echo off
rem *** Script to add log of session continue / relogin ***
rem *** Syed Jahanzaib aacable@hotmail.com ***
rem schtasks /delete /tn "Update LOGIN - LOG to Server" /f
cls
rem test file for computer name
rem Create Backup folder if not exists already
set TEMPLOC="C:\BACKUP"
if not exist "%TEMPLOC%" mkdir %TEMPLOC%
set LOGSERVER=
set LOGTOSERVERBYCOMPNAME=
set LOGSERVER="\\DC1\userlog\%USERNAME%.log"
set LOGTOSERVERBYCOMPNAME="\\DC1\userlog\%COMPUTERNAME%.log"
set LOGLOCAL="%TEMPLOC%\LOCAL.LOG"
set IPFILE="%TEMPLOC%\IP.TXT"
set COMPFILE="%TEMPLOC%\COMPNAME.TXT"
set IPADD=
set DAMWIP=
set DAMWIPFILE="%TEMPLOC%\damwipfile.txt"
set COMPNAME=
del %IPFILE% 2> nul
del %COMPFILE% 2> nul
taskkill /F /IM nslookup.exe 2> nul
::# Get IP Address
for /f "skip=1 tokens=2 delims=[]" %%* in (
'ping.exe -n 1 %Computername%') Do (set "LOCALIP=%%*" & goto:exitFor1)
:exitFor1

netstat -na | find "3389" | find "ESTABLISHED" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %IPFILE%
set /p IPADD= %COMPFILE%
set /p COMPNAME= %DAMWIPFILE%
set /p DAMWIP= c:\backup\damwip.txt
set /p COMPNAME=> %LOGSERVER%
echo --------------------------------- >> %LOGTOSERVERBYCOMPNAME%
ECHO SESSION-CONTINUED >> %LOGSERVER%
ECHO SESSION-CONTINUED >> %LOGTOSERVERBYCOMPNAME%
echo RDP Client IP: %IPADD% - / DW IP: %DAMWIP% / Remote Client PC: %COMPNAME%
echo Login User: %USERNAME% / To: %COMPUTERNAME% / Local IP: %LOCALIP% / %DATE% %TIME%
echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER%
echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGTOSERVERBYCOMPNAME%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGTOSERVERBYCOMPNAME%
echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGTOSERVERBYCOMPNAME%

REM --- LOCAL LOG FILE
echo --------------------------------- >> %LOGLOCAL%
ECHO S-RELOGIN >> %LOGLOCAL%
echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGLOCAL%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGLOCAL%

echo --------------------------------- >> %LOGLOCAL%


Windows Task Scheduler Configuration via GPO

 

1-task-scheudler

2-update-re-login

3-trigger

4-action

for login entries, I used startup script like welcome.vbs

welcome.vbs


' Domain Users Welcome Logon script / syed jahanzaib
dim objShell, objNetwork
set objShell = WScript.CreateObject("WScript.Shell")
set objNetwork = WScript.CreateObject("WScript.Network")
' let's display a welcome message
dim strDomain, strUser
strDomain = objNetwork.UserDomain
strUser = objNetwork.UserName
msgbox "Welcome to AGP (Pvt) Ltd. " & strUser & "!"
' msgbox "Welcome to the " & strDomain & ", " & strUser & "!"
' Syed jahanzaib


Result:

Now you can open the log file at log server, or local pc as well.

---------------------------------
---------------------------------
LOGOFF -- user1.id USER1_PC Mon 01/23/2017 17:03:34.68
---------------------------------
---------------------------------
LOGIN
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 8:31:15.80
---------------------------------
---------------------------------
LOCKED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:33:30.06
---------------------------------
---------------------------------
SESSION-CONTINUED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:36:22.70
---------------------------------
---------------------------------
LOCKED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:36:30.19
---------------------------------
---------------------------------
SESSION-CONTINUED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:49:58.99
---------------------------------

Uuserlog Folder Permission

At remote log server, you can set permission of userlog folder so that user can only write in it, but not explore it.

permission


blah blah blah

Syed.Jahanzaib

January 6, 2017

Gathering Stats from remote Windows via Linux Shell

Filed under: Linux Related, Uncategorized — Tags: , , , , , , , — Syed Jahanzaib / Pinochio~:) @ 2:43 PM

Reference Post:

Following are few simple methods to query information for various instances like remote windows service status , performance monitor instance result with trimming , , execute commands on remote windows box , all being done from our beloved Linux boX 😉

I must admit that even after spending years in this field, I still feel myself very doodle, blockhead & light brain in almost every topic or subject I get confronted with ! STML plays an important role in my Deficiency  ‘_’    – 😉

ots1087__97717-1410905363-1280-1280


Executing command on remote windows server, and get its result in output

$WINEXE --user=$DOMAIN/$ADMINID%$ADMINPASS //$SERVERIP "C:\TEMP\COMMAND.EXE -syntax-if-any"

Note: above command requires WINEXE tool (Linux tools to execute command on remote windows)

Querying Remote Windows Performance Monitor Instances

Example, we have Forefront TMG 2010 and we want to see its Cache Hit % from our linux box shell, so we can use following command (It was real hard to escape nested double quotes :O )

This is very very useful command and it took few hours for me to trim the required result for plotting graph.

winexe -U domain/admin%"password" //MYSERVER 'typeperf -sc 1 -si 1 "\\MYSERVER\Forefront TMG Web Proxy\Cache Hit Ratio (%)"'

and with bash script I used it like

root@linux:/temp# cat tmg-cachehit.sh

#!/bin/bash
# Script to query TMG cache HIT after trimming
#set -x
IP="10.0.0.1"
DOMAIN="MYDOMIN"
ID="ADMIN"
PASS="PASSWORD"
TMP_HOLDER="/tmp/$IP.cache.hit.txt"
winexe -U $DOMAIN/$ID%"$PASS" //$IP 'typeperf -sc 1 -si 1 "\\101.11.11.6\Forefront TMG Web Proxy\Cache Hit Ratio (%)"' > $TMP_HOLDER
RESULT=`cat $TMP_HOLDER | sed -n 3p | awk '{print $2}' | cut -d "," -f 2 | tr -d '"' | cut -f1 -d"."`
echo $RESULT
echo $RESULT

Result:

tmg-cache-hit


Check remote windows service status

Example if we want to query service status result of Lotus domino mail server  from our linux box …

root@linux:/temp# net rpc service status "Lotus Domino Server (DLotusDominodata)" -I 10.0.0.1 --user=DOMAIN/ADMINID%PASSWORD

RESULT:

Lotus Domino Server (DLotusDominodata) service is running.
Configuration details:
Controls Accepted = 0x5
Service Type = 0x110
Start Type = 0x2
Error Control = 0x0
Tag ID = 0x0
Executable Path = "X:\Lotus\nservice.exe" "=X:\Lotus\notes.ini" "-jc" "-c"
Load Order Group =
Dependencies = /
Start Name = LocalSystem
Display Name = Lotus Domino Server (DLotusDominodata)

Allah Shuker


I used all above commands in various script for alerts and mrtg graphing. you can use it to fulfill any customized requirements.

Regard’s
Syed Jahanzaib

January 3, 2017

Ubiquiti Unifi Notes & Odd methods of acquiring Info

Filed under: Ubiquiti — Syed Jahanzaib / Pinochio~:) @ 9:49 AM

ubiquity


1- Odd method to acquire total number of active WiFi Clients

Bash script to acquire some info via UniFi controller like active number of WiFi clients connected with different UniFi AP LR in the company.


#!/bin/bash
# Script to query active clients by curl from unifi controller
# Syed jahanzaib / aacable . wordpress . com / aacable at hotmail dot com
# 2nd-January-2017
#set -x
# UniFi Controller IP and Port
IP="10.0.0.1"
PORT="8443"
COOKIE="/tmp/cookies.txt"
TMP_HOLDER="/tmp/$IP.active.wifi.clients.txt"
# pattern to match to count active clients using string matching
PATTERN="hostname"

# First Login to controller via CURL
curl -s "https://$IP:$PORT/api/login" --data-binary '{"username":"admin","password":"CONTROLLERPASSWORD","strict":true}' --compressed --insecure -c $COOKIE > /dev/null

# Download Statistics from controller using CURL
curl -s --insecure -b $COOKIE -c $COOKIE "https://$IP:$PORT/api/s/default/stat/sta" > $TMP_HOLDER

# Count active users by pattern match,  what an odd method, may not work correctly, but so far working for me
ACTIVE=`cat $TMP_HOLDER | grep -o $PATTERN | wc -l`
echo $ACTIVE
echo $ACTIVE


Result in command …

unifi-active

 

CFG file for MRTG …

# Unifi Controller - WiFi Active WiFi Clients - syed.jahanzaib
Target[unifi_wifi_active_users]: `/temp/unifi-client.sh`
Title[unifi_wifi_active_users]: Active Wifi Clients via Unifi Controller
PageTop[unifi_wifi_active_users]: <H1>Active Wifi Clients via Unifi Controller</H1>
MaxBytes[unifi_wifi_active_users]: 50000
Colours[unifi_wifi_active_users]: B#8888ff,B#0813B7,B#5398ff,B#0813B7
Options[unifi_wifi_active_users]: growright,nopercent,gauge,integer,nobanner,printrouter,pngdate,noo
LegendI[unifi_wifi_active_users]: Active Wifi Users
LegendO[unifi_wifi_active_users]:
YLegend[unifi_wifi_active_users]: Active Wifi Users
Legend1[unifi_wifi_active_users]: Active Wifi Users
Legend2[unifi_wifi_active_users]:
ShortLegend[unifi_wifi_active_users]:
#Unscaled[unifi_wifi_active_users]: dwmy

MRTG Graph for Active WiFi Clients via UniFi Controller …

1-wifi

  •  – – – – – – – – –
  •  – – – – – – – – –
  •  – – – – – – – – –
  •  – – – – – – – – –

Following are some snapshots from the UniFi Controller for some comparison that script is working accurate so far …
(However it is still under observation to monitor its accuracy result / zaib)

1

2


2- Odd method to acquire total number of Active Access Points Vs Down [Registered in UniFi Controller]

Bash script to acquire total number of registered access points (unifi AP-LR) and there status as well to compare Active vs down.


#!/bin/bash
# Script to query active clients by curl from unifi controller
#set -x
IP="10.0.0.1"
PORT="8443"
COOKIE="/tmp/cookies.txt"
TMP_HOLDER="/tmp/$IP.total.ap.txt"
PATTERN="adopted"
curl -s "https://$IP:$PORT/api/login" --data-binary '{"username":"admin","password":"CONTROLLERPASSWORD","strict":true}' --compressed --insecure -c $COOKIE > /dev/null
curl -s --insecure -b $COOKIE -c $COOKIE "https://$IP:$PORT/api/s/default/stat/device" > $TMP_HOLDER
ACTIVE=`cat $TMP_HOLDER | grep -o $PATTERN | wc -l`
DOWN=`grep -oP '\"state\" : \K[^ ]*' $TMP_HOLDER | grep 0 | wc -l`
echo $DOWN
echo $ACTIVE

Result in command …

[Total access points  vs DOWN]

ap-up-vs-down

CFG file for MRTG …


# Unifi Controller - UniFi AP-LR - Active Access Points vs DOWN
Target[unifi_ap_total_vs_down]: `/temp/unifi-devices.sh`
Title[unifi_ap_total_vs_down]: UniFi AP-LR - Active Access Points vs DOWN
PageTop[unifi_ap_total_vs_down]: <H1>UniFi AP-LR - Active Access Points vs DOWN</H1>
MaxBytes[unifi_ap_total_vs_down]: 5000
Colours[unifi_ap_total_vs_down]: B#0000FF,R#FF0000,B#0000FF,R#FF0000
Options[unifi_ap_total_vs_down]: growright,nopercent,gauge,integer,nobanner,printrouter,pngdate
LegendI[unifi_ap_total_vs_down]: Active AP -->
LegendO[unifi_ap_total_vs_down]: Down AP -->
YLegend[unifi_ap_total_vs_down]: Active vs Down
Legend1[unifi_ap_total_vs_down]: Active Access Points
Legend2[unifi_ap_total_vs_down]: Down Access Points
ShortLegend[unifi_ap_total_vs_down]:
#Unscaled[unifi_ap_total_vs_down]: dwmy

MRTG Graph for Active WiFi AP DEVICES via UniFi Controller …

3-active-vs-down-ap


3# Upgrade UniFi AP LR Access Point via SSH/CLI

We have few unifi AP-LR  Wireless Access Points in our company which are connected with the Unifi Controller ver 5.2.9.0 on windows 2008 r2 / x64 server. For some unknown reasons I was unable to upgrade the access point’s firmware from the controller. Therefore I upgraded all AP’s via SSH method which is posted below …

First download the appropriate firmware and upload it to some web server. (at the time of upgrading the latest firmware version was  3.7.21.5389 , you make sure to download latest one available)
Select your model / download from following link …

https://www.ubnt.com/download/unifi/

[Luckily I had local web server available so I simply put this file into my /var/www folder (for ubuntu)]

 

Now login in the access point via SSH , and issue this command

upgrade http://101.0.0.1/BZ.ar7240.v3.7.21.5389.161017.0923.bin

Make sure to change the path or ip according to your network. Once its upgraded it rebooted and new Firmware was 3.7.21.5389


I will post more info later … 3.7.21.5389

Regard’s
Syed Jahanzaib

Blog at WordPress.com.

%d bloggers like this: