Syed Jahanzaib – Personal Blog to Share Knowledge !

June 29, 2018

FREERADIUS WITH MIKROTIK – Part #15 – Dynamic NAS Clients

Filed under: freeradius — Tags: , — Syed Jahanzaib / Pinochio~:) @ 3:21 PM

fre

rapid change.jpg

FREERADIUS WITH MIKROTIK – Part #1 – General Tip’s Click here to read more on FR tutorials …


Disclaimer! This is important!

Every Network is different , so one solution cannot be applied to all. Therefore try to understand logic & create your own solution as per your network scenario. Just dont follow copy paste.

If anybody here thinks I am an expert on this stuff, I am NOT certified in anything Mikrotik/Cisco/Linux or Windows. However I have worked with some core networks and I read , research & try stuff all of the time. So I am not speaking/posting about stuff I am formerly trained in, I pretty much go with experience and what I have learned on my own. And , If I don’t know something then I read & learn all about it.

So , please don’t hold me/my-postings to be always 100 percent correct. I make mistakes just like everybody else. However – I do my best, learn from my mistakes and always try to help others.

Regard's
Syed Jahanzaib~

Scenario:

In freeradius , we have to add NAS client entries either in clients.conf or in nas table to allow communication from NAS  with freeradius services (for AAA requests). This is good from security perspective to allow only specific IP addresses, BUT what if your NASes are spreaded across different location (geographically different places) and have dynamic IP addresses like DSL , 3G/4G etc.

As a workaround we can setup a vpn server on our central location and connect all remote NAS (es) to this vpn server but this requires additional configuration at server end and all client end’s as well.

Another workaround is to ALLOW all ip addresses to communicate with FR service which is really a BAD idea from security perspective 🙂 As ALAN once said:

Are you willing to let anyone on the net send RADIUS packets to your RADIUS server?

Another workaround is to allow only specific IP subnet range , for this you have to inquire about the IP range that ISP is assigning to that particular NAS & allow this range in your clients.conf .


1# Howto enable freeradius to inquire about NAS clients using SQL NAS table

To enable freeradius to read clients details from NAS table in SQL, We need to modify in sql.conf file …

Edit following file /etc/freeradius/sql.conf

nano /etc/freeradius/sql.conf file

Uncomment the following

readclients = yes

So after modifications some portion of the file may look like following …

# Connection info:
server = "localhost"
#port = 3306
login = "radius"
password = "zaib1234"
readclients = yes

Now add one entry in this table & restart your Freeradius service.

mysql> select * from nas;
+---+---------------+------------+-------+------+------------+------+------+---------------+------+
| 1 | 101.11.11.255 | testmk | other | NULL | testing123 | NULL | NULL | RADIUS Client | 3799 |
+---+---------------+------------+-------+------+------------+------+------+---------------+------+
1 rows in set (0.00 sec)

This table contains data about your NASes (like mikrotik etc). It is more convenient to to maintain the NAS details in the database.

NOTE: Whenever you add / edit / remove any entry in clients.conf or NAS table, you must restart freeradius service by following cmd

service freeradius restart

 

You can use following NAS table also, adding just for reference purposes …

-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 29, 2018 at 03:25 PM
-- Server version: 5.7.21-0ubuntu0.16.04.1-log
-- PHP Version: 7.0.22-0ubuntu0.16.04.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `radius`
--

-- --------------------------------------------------------

--
-- Table structure for table `nas`
--

CREATE TABLE `nas` (
`id` int(10) NOT NULL,
`nasname` varchar(128) NOT NULL,
`shortname` varchar(32) DEFAULT NULL,
`type` varchar(30) DEFAULT 'other',
`ports` int(5) DEFAULT NULL,
`secret` varchar(60) NOT NULL DEFAULT 'secret',
`server` varchar(64) DEFAULT NULL,
`community` varchar(50) DEFAULT NULL,
`description` varchar(200) DEFAULT 'RADIUS Client',
`nas_coa_port` int(32) NOT NULL DEFAULT '3799'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `nas`
--

INSERT INTO `nas` (`id`, `nasname`, `shortname`, `type`, `ports`, `secret`, `server`, `community`, `description`, `nas_coa_port`) VALUES
(1, '10.0.0.3', 'ZAIB_CCR_GW', 'other', NULL, 'testing123', NULL, NULL, 'RADIUS Client', 3799);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `nas`
--
ALTER TABLE `nas`
ADD PRIMARY KEY (`id`),
ADD KEY `nasname` (`nasname`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `nas`
--
ALTER TABLE `nas`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


2# Adding NAS Clients entries in CLIENTS.CONF file

 

In /etc/freeradius/clients.conf use below format to allow either single ip, subnet, or Allow ANY IP (all all ip’s is is not recommended*)

# To allow specific NAS single IP only

# To allow ONLY specific NAS via clients.conf
client 92.168.10.1 {
secret = testing123
shortname = Mikrotik
}

# To allow specific SUBNET ip (example if remote NAS have dynamic public ip but the ip remains from specific subnet range)

client test_subnet_nas {
ipaddr = 192.168.10.0
secret = testing123
netmask = 24
}

To allow ANY ip to send request to freeradius server (not recommended)

# To allow ANY NAS client which is not recommended*
client 0.0.0.0/0 {
secret = testing123
shortname = Mikrotik
}

3# Allow NAS AAA Requests based on NAS-IDENTIFIER

In Some situations we would like to authenticate user only if its coming from SPECIFIC NAS only (not by ip, but by NAS-Identifier attribute).

Example if client request coming from NAS which have system identifiaction of ZAIB_CCR_GW , then process authentication request further ELSE REJECT !

First you need to allow NAS requests from ALL or Subnet range IP.

# To allow ANY NAS client which is not recommended*
client 0.0.0.0/0 {
secret = testing123
shortname = Mikrotik
}

Users Table Sample !

We have a user table which contains a column nas_id. We will add a SQL IF statement which will check the the connecting user NAS-Identifier & match it with users allowed nas_id in the user’s table.

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
`id` int(10) NOT NULL,
`username` varchar(128) NOT NULL,
`password` varchar(32) NOT NULL,
`firstname` text NOT NULL,
`lastname` text NOT NULL,
`email` text NOT NULL,
`mobile` text NOT NULL,
`cnic` text NOT NULL,
`srvname` text NOT NULL,
`srvid` int(3) NOT NULL,
`expiration` date DEFAULT NULL,
`mac` varchar(30) NOT NULL,
`macvendor` varchar(128) NOT NULL,
`bwpkg` varchar(256) NOT NULL,
`pool` varchar(128) DEFAULT 'other',
`is_enabled` int(1) NOT NULL,
`is_days_expired` int(1) NOT NULL,
`is_qt_expired` int(1) NOT NULL,
`is_uptime_expired` int(1) NOT NULL,
`qt_total` varchar(32) NOT NULL,
`qt_used` varchar(20) NOT NULL,
`uptime_limit` varchar(20) NOT NULL,
`uptime_used` varchar(32) NOT NULL,
`owner` text NOT NULL,
`vlanid` varchar(32) NOT NULL,
`nas_id` varchar(32) DEFAULT NULL,
`createdon` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

Now we will add a USERS entry as sample …

INSERT INTO `users` (`id`, `username`, `password`, `firstname`, `lastname`, `email`, `mobile`, `cnic`, `srvname`, `srvid`, `expiration`, `mac`, `macvendor`, `bwpkg`, `pool`, `is_enabled`, `is_days_expired`, `is_qt_expired`, `is_uptime_expired`, `qt_total`, `qt_used`, `uptime_limit`, `uptime_used`, `owner`, `vlanid`, `nas_id`, `createdon`) VALUES
(1, 'zaib', 'zaib', 'OK', 'jahanzaib', 'aacableAThotmailDOTcom', '03333021909', '1234567890-1-1', '1mb', 9, '2018-01-04', '00:0C:29:B9:D8:A0', '', '1024k/1024k', 'public-pool', 1, 0, 0, 0, '0', '2933559', '0', '', 'xxxxxx', 'ether1-LAN-DUMMY', 'someinvalid_CCR_GW', '2018-06-29 11:06:52');

Now we will add the SQL IF statement that will actually check every incoming Authentication request for matching NAS-IDENTIFIER with nas_id column in users table.

Edit Default Sites-Enabled file,

nano /etc/freeradius/sites-enabled/default

& paste following in `Authorize` Section

if ("%{sql: select nas_id from users where username = '%{User-Name}'}" != "%{NAS-Identifier}") {
update reply {
Reply-Message = 'Error: You are not allowed to connect form this NAS ! Bingo - zaib'
}
update control {
Auth-Type := "Reject"
}
}

Save & Exit.

Now reload Freeradius in Debug Mode (by freeradius -X) & monitor the debugging.

If user will connect from another NAS (which is not matched in with nas_id column in the USERS table , he will get denied with the message.

Note: For testing purposes . I have added dummy entry in user’s nas_id column.

###############################################
# Showing relevant data only for demo purposes - Syed Jahanzaib - 29-JUN-2018
###############################################
rad_recv: Access-Request packet from host 10.0.0.1 port 49453, id=150, length=124
Service-Type = Framed-User
Framed-Protocol = PPP
NAS-Port = 15729249
NAS-Port-Type = Ethernet
User-Name = "zaib"
Calling-Station-Id = "24:26:42:D4:BC:43"
Called-Station-Id = "service1"
NAS-Port-Id = "ether10"
User-Password = "zaib"
NAS-Identifier = "ZAIB_CCR_GW"
NAS-IP-Address = 10.0.0.1

# Executing section authorize from file /etc/freeradius/sites-enabled/default

++? if ("%{sql: select nas_id from users where username = '%{User-Name}'}" != "%{NAS-Identifier}")
sql_xlat
expand: %{User-Name} -> zaib
sql_set_user escaped user --> 'zaib'
expand: select nas_id from users where username = '%{User-Name}' -> select nas_id from users where username = 'zaib'
rlm_sql (sql): Reserving sql socket id: 25
sql_xlat finished
rlm_sql (sql): Released sql socket id: 25
expand: %{sql: select nas_id from users where username = '%{User-Name}'} -> ZAIB_CCR_GW1
expand: %{NAS-Identifier} -> ZAIB_CCR_GW
? Evaluating ("%{sql: select nas_id from users where username = '%{User-Name}'}" != "%{NAS-Identifier}") -> TRUE
++? if ("%{sql: select nas_id from users where username = '%{User-Name}'}" != "%{NAS-Identifier}") -> TRUE
++if ("%{sql: select nas_id from users where username = '%{User-Name}'}" != "%{NAS-Identifier}") {
+++update reply {
+++} # update reply = noop
+++update control {
+++} # update control = noop
++} # if ("%{sql: select nas_id from users where username = '%{User-Name}'}" != "%{NAS-Identifier}") = noop

Found Auth-Type = Reject
Auth-Type = Reject, rejecting user
Failed to authenticate the user.
Using Post-Auth-Type Reject

# Executing group from file /etc/freeradius/sites-enabled/default
+group REJECT {
++update reply {
++} # update reply = noop
[sql] expand: %{User-Name} -> zaib
[sql] sql_set_user escaped user --> 'zaib'

[sql] expand: INSERT into radpostauth (username, pass, mac, nasipaddress, reply, authdate, reason) values ('%{User-Name}', '%{User-Password:-Pap-Password}', '%{Calling-Station-Id}', '%{NAS-IP-Address}', '%{reply:Packet-Type}', NOW(), '%{reply:Reply-Message}') -> INSERT into radpostauth (username, pass, mac, nasipaddress, reply, authdate, reason) values ('zaib', 'zaib', '24:26:42:D4:BC:43', '10.0.0.1', 'Access-Reject', NOW(), 'Error: You are not allowed to connect form this NAS =21')
rlm_sql (sql) in sql_postauth: query is INSERT into radpostauth (username, pass, mac, nasipaddress, reply, authdate, reason) values ('zaib', 'zaib', '24:26:42:D4:BC:43', '10.0.0.1', 'Access-Reject', NOW(), 'Error: You are not allowed to connect form this NAS =21')
rlm_sql (sql): Reserving sql socket id: 24
rlm_sql (sql): Released sql socket id: 24
++[sql] = ok
[attr_filter.access_reject] expand: %{User-Name} -> zaib
attr_filter: Matched entry DEFAULT at line 11
++[attr_filter.access_reject] = updated
+} # group REJECT = updated
Delaying reject of request 3 for 1 seconds
Going to the next request
Waking up in 0.9 seconds.
Sending delayed reject for request 3
Sending Access-Reject of id 150 to 10.0.0.1 port 49453
Reply-Message = "Error: You are not allowed to connect form this NAS !"
Waking up in 4.9 seconds.
Cleaning up request 3 ID 150 with timestamp +104
Ready to process requests.

.

& if the users request matches , he will be granted access (off course after all other checks) 🙂


Regard’s
Syed Jahanzaib

 

June 27, 2018

FREERADIUS WITH MIKROTIK – Part #14 – Dynamic Bandwidth Change on the FLY using COA with radclient

Filed under: freeradius — Tags: , , , , , , — Syed Jahanzaib / Pinochio~:) @ 1:33 PM

fre

bandwidth

FREERADIUS WITH MIKROTIK – Part #1 – General Tip’s Click here to read more on FR tutorials …

word-press blog is not saving the code properly, so some syntax is missing in the script after every update, so if requires this script then email me.


Disclaimer! This is important!

Every Network is different , so one solution cannot be applied to all. Therefore try to understand logic & create your own solution as per your network scenario. Just dont follow copy paste.

If anybody here thinks I am an expert on this stuff, I am NOT certified in anything Mikrotik/Cisco/Linux or Windows. However I have worked with some core networks and I read , research & try stuff all of the time. So I am not speaking/posting about stuff I am formerly trained in, I pretty much go with experience and what I have learned on my own. And , If I don’t know something then I read & learn all about it.

So , please don’t hold me/my-postings to be always 100 percent correct. I make mistakes just like everybody else. However – I do my best, learn from my mistakes and always try to help others.

This particular script was tested in Virtual environment only, therefore consider this posting as an reference only, donot use it in production environment.

Regard's
Syed Jahanzaib~

Scenario:

We have a generic FreeRADIUS Version 2.2.8 based billing system in Ubuntu 16.04.3 LTS Server. Users are authenticating to NAS (Mikrotik) which is using Freeradius as its AAA Server.


Requirement:

Currently users packages are 1mb,  2mb and so on. We would like to introduce different bandwidth for day and night for specific services. Upgrade/Downgrade of user package should be done by dynamically with COA, so that package changing should be done on the fly without disconnecting user.

Its a bit complicated piece of BASH scripting , but so far doing its job.


Software / Hardware Components Used:

  • NAS: Mikrotik CCR1036 / Firmware: 6.42.1
  • OS: Ubuntu 16.04.3 LTS Server Edition / 64bit
  • FreeRADIUS Version: 2.2.8 (using apt-get default repository)

(more…)

June 26, 2018

BASH Script with time & single execution per day checks

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

 

repeat

Scenario:

We have a bash script that performs various functions related to Freeradius, including expiration checkup & various groups updates functions.

Problem:

We have schedules this script to run daily at 1700 hours, What will happen if server was powered off  at 1700 hours? Script will missed its schedule resulting in expired users account will not be disabled for that day and incorrect display of users status in front gui. Alternatively we can schedule it to run hourly but it will increase the server load because of repeated task , which is supposed to be executed only once per day

Requirements:

We need to make some checks and balances so that if script must have some intelligent IF ELSE criteria in order to check following steps …

  • Script is scheduled to run hourly, so that if it misses the 1700 hour it will be relaunched next hour,
  • If time is 1700 hours or above then execute the script,
  • If the script executes successfully , then save this result, and on next run (within current date) it should detect last run status and dont repeat the code to avid recurrence,
  • If the last run was not executed for any reason, & the time is 1700 or above then execute the script and save its run status in file,
  • Once the data changes, it should re-run the script only if the time is 1700 or above.

Solution:

the SCRIPT ! Sample Purpose only

#!/bin/bash
# Bash Script to make sure script runs at specific time, and should not run again for the same date
# record date in local file, to avoic repeating running the code in todays date, once the date is changed,
# then re-run the code and match time again and so on
# Syed Jahanzaib / 26-Jun-2018
# set -x

# Setting variables
DATE=$(date +%d-%m-%Y)
FULL_DATE=`date`
FILE=/temp/1.txt
touch $FILE
CURR_HOUR=$(date +%H)

# Set time for script execution
SCR_SCHEDULED_TIME="11"
H=$(date +'%-H')

CHK_GREP=`grep -c $DATE $FILE`
echo "Current Date time is $FULL_DATE"

# If script is executed successfully then dont re-run and exit now
if grep -q $DATE $FILE >/dev/null 2>&1
then
echo "It seems the script was executed successfully today $DATE, It will run on next date change.... Exiting now."
exit 1
fi

# Check if time is matched that is greater or equals to $SCR_SCHEDULED_TIME and also check if script hae ran successfully or not previously
echo "
Stage-1: Checking if current time is equals or greater then '$SCR_SCHEDULED_TIME hours' ..."
if [ "$CURR_HOUR" -ge "$SCR_SCHEDULED_TIME" ] && [ "$CHK_GREP" == "0" ]; then
echo "
Stage-2: Time matched that is equals or greater then $SCR_SCHEDULED_TIME"
# If all matches, then run the code ! and add time stamp in file to avoid repeatingo/re-running the following script code on next RUN
echo "Finally: All conditions time + this day first execution matched, Now running the script code ...."
date +%d-%m-%Y >> $FILE
exit 1
fi

# If time have not come like its before the $SCR_SCHEDULED_TIME, then give error and exit now
echo "
Warning !
Scheudled time is equals or greater then $SCR_SCHEDULED_TIME hours : Current hour is $CURR_HOUR
Time have not came yet ! wait for your turn ..."

This way I was able to achieve the task I was thiking of.


# Actual Script which performs various functions with time checkups etc

Just for personnel reference …

#!/usr/bin/env bash
####!/bin/sh
#set -x
#trap "set +x; set -x" DEBUG
# BASH base script to discopnnect users whose expiry is today & update there GROUPS as well and update log table.
# the simple logic can be applied for about any other task as well. I tried to make it as simple as it can be
# also check if the scrpit ran successfully then dont re-run today,
# By Syed Jahanzaib
# CREATED on : 16th July, 2015
# Modified on 25h June 2018

# Local Variables
# Mysql credentials
SQLID="root"
SQLPASS="ROOTPASS"
export MYSQL_PWD=$SQLPASS
CMD="mysql -u$SQLID --skip-column-names -s -e"
DB="radius"
#Table which contain main users information
TBL="users"
#Rad user group in which we will update user profile like from 1mb to expired or likewise
GROUP="radusergroup"
NEXTSRV="expired"
TBL_LOG="log"

# Date Time Variables
DATE=$(date +%d-%m-%Y)
FULL_DATE=`date`
CURR_HOUR=$(date +%H)
TODAY=$(date +"%Y-%m-%d")
WEEK=`date -d "-1000 days" '+%Y-%m-%d'`
BEGIN="1970-01-01"
H=$(date +'%-H')
################################
## Set time for script execution
## IMPORTANT, donot use 0 in it
SCR_SCHEDULED_TIME="12"
################################

#Network Related
hostname=`hostname`
IP=`ip route get 8.8.8.8 | awk '{print $NF; exit}'`

# Gmail Data
GMAILID="MYGMAIL@gmail.com"
GMAILPASS="MYGMAILPASS"
SMTP="64.233.184.108:587"
ADMINMAIL1="aacableAThotmail.com"
COMPANY="ZAIB"
MAILSUB="$COMPANY INFO -$HOSTNAME-$IP- List of account expired on $TODAY"

##################################################
##################################################
# Temp folder and files setup for various actions
##################################################
##################################################
TEMP="temp"
# Temp holders to store users list
ALLEXPLIST=/$TEMP/all_time_expired_users_list.txt
TODEXPLIST=/$TEMP/only_today_expired_users_list.txt
FILE=/$TEMP/check_user_expiration_exec.txt

# Checking if /temp folder is previously present or not , if not create one ...
{
if [ ! -d "/$TEMP" ]; then
echo
mkdir /$TEMP
fi
}

# remove and recreate users list to avoid any Duplication or issue
{
if [ -f $ALLEXPLIST ]; then
rm $ALLEXPLIST
touch $ALLEXPLIST
fi
}
{
if [ -f $TODEXPLIST ]; then
rm $TODEXPLIST
touch $TODEXPLIST
fi
}
# File Holder to store last execution date
{
if [ ! -f $FILE ]; then
touch $FILE
fi
}

############################
############################
###### START thE script cOdE
############################
############################

CHK_GREP=`grep -c $DATE $FILE`
echo "Current Date time is $FULL_DATE
"
# If script is executed successfully in current date, then dont re-run and exit now
echo "Stage-1:
Checking if the script have already ran successfully for today, by getting current date from the $FILE"
if grep -q $DATE $FILE >/dev/null 2>&1
then
echo "
Result:
It seems the script was executed successfully today $DATE, It will run on next date change. Exiting now ..."
exit 1
fi

# Check if time is matched that is greater or equals to $SCR_SCHEDULED_TIME and also check if script hae ran successfully or not previously by getting date from $FILE
echo "
Stage-2: Checking if current hour is equals or greater then '$SCR_SCHEDULED_TIME hours' & previous run is not done yet ..."
if [ "$CURR_HOUR" -ge "$SCR_SCHEDULED_TIME" ] && [ "$CHK_GREP" == "0" ]; then
echo "
Stage-2:
Time matched that is equals or greater then $SCR_SCHEDULED_TIME"
# If all matches, then run the code ! and add time stamp in file to avoid repeatingo/re-running the following script code on next RUN
echo "Finally:
All conditions time + this day first execution matched, Now running the script code ..."
date +%d-%m-%Y >> $FILE

# Pull users that are expiring from beginning till TODAY, to avoid missing any part
$CMD "use $DB; select username from $TBL where expiration between '$BEGIN' AND '$TODAY';" |sort > $ALLEXPLIST
# Pull user list that are expiring today only, for email purposes
$CMD "use $DB; select username from $TBL where expiration ='$TODAY';" |sort > $TODEXPLIST

# IF no user found , show error and exit - zaib
CHK=`wc -m $ALLEXPLIST | awk {'print $1}'`
if [ "$CHK" -eq 0 ]
then
echo "No user found expiring today, exiting ..."
exit 1
fi

# Apply formula
num=0
cat $ALLEXPLIST |while read data
do
num=$[$num+1]
USERNAME=`echo $data`

# Update user status in RADgroup & users table so that he will rejected on next login
IS_EXPIRED=`$CMD "use $DB; select is_expired from users where username ='$USERNAME';"`
if [ "$IS_EXPIRED" = "N" ]; then
echo "user_IS EXIPRED is NO *************************************************************************************************"
$CMD "use $DB; update $GROUP set groupname='$NEXTSRV' where username='$USERNAME';"
$CMD "use $DB; update $TBL set is_expired='Y' where username='$USERNAME';"
$CMD "use $DB; update $TBL set is_days_expired='Y' where username='$USERNAME';"
$CMD "use $DB; INSERT into $TBL_LOG (data, msg) VALUES ('$USERNAME', '$USERNAME - User reached Expiration, Group udpated.');"
fi

# CHECK ONLINE AND KICK
# Pull account session id from radacct table, which will be used to COA OR user disconnection
ACCTSESID=`$CMD "use $DB; select acctsessionid from radacct where username ='$USERNAME' AND acctstoptime is NULL;"`
# If user is not Online , just give info that he is not online
if [ -z "$ACCTSESID" ]; then
$CMD "use $DB; INSERT into $TBL_LOG (data, msg) VALUES ('$USERNAME', '$USERNAME - User reached Expiration, Group udpated but its already offline');"
echo "$USERNAME - User reached Expiration, Group udpated but its already offline."
else
# Kick user by getting his NAS ip, secret and other info and log
# Mikrotik NAS IP and Radport and Shared Secret
NAS_IP=`$CMD "use $DB; select nasipaddress from radacct where username ='$USERNAME' AND acctstoptime is NULL;"`
NAS_SECRET=`$CMD "use $DB; select secret from nas where nasname ='$NAS_IP';"`
NAS_COA_PORT=`$CMD "use $DB; select nas_coa_port from nas where nasname ='$NAS_IP';"`
# Disconnect users now using RADCLIENT with username adn Account session ID taken from radacct table
echo user-name=$USERNAME,Acct-Session-Id=$ACCTSESID | radclient -x $NAS_IP:$NAS_COA_PORT disconnect $NAS_SECRET
# LOG into LOG TABLE in radius DB
$CMD "use $DB; INSERT into $TBL_LOG (data, msg) VALUES ('$USERNAME', '$USERNAME - User reached Expiration, kicked & updated,.');"
echo "$USERNAME - User reached Expiration, kicked & updated."
fi
done

#TOT=`cat $TODEXPLIST | wc -l`
#echo "
#-----------
#-----------

#$COMAPNY _ List of TODAY $TODAY expired users, Total = $TOT"
#cat $TODEXPLIST

# Send Email to all admin - currently 4 users
sendemail -t $GMAILID -u "$MAILSUB" -o tls=yes -s $SMTP -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TODEXPLIST -o message-content-type=text
fi

Regard’s
Syed Jahanzaib

June 19, 2018

NTP Server configuration in Ubuntu

Filed under: Linux Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 4:44 PM

ntp show

Task:

We want to create a local NTP server so that our local devices like switches / routers / systems can syn time with it without requiring internet access. The NTP daemon allows a machine on your network (if you would like) to operate as an NTP time server. Doing so will allow other machines on your local network to synchronize with your LAN time server in a very quick and accurate manner, since network latency is minimized. In this way, the differences in clocks between machines on your network is kept as minimal as possible. Mac, and even Windows boxes are also able to synchronize with an NTP server.

Note: If your windows workstation is part of domain, you will not be able to see INTERNET TIME setup in DATE TIME because workstation will sync time with the Domain.


OS: Ubuntu 16.04.4 LTS with internet access

First, Install the NTP daemon

sudo aptitude remove ntpdate
sudo aptitude install ntpd

Note: Once you have found one good syncing peer,  add it to the list, putting ‘iburst’ after the most promising one. For instance:

server 91.189.91.157 iburst

This will cause ntpd to synchronize very quickly with this server after starting up.

Now restart NTPD daemon …

sudo /etc/init.d/ntp restart

It may take few seconds or up to 15-20 minutes for the initial time sync.

Next, monitor your system log to see if you synchronize with a time server:

tail -f /var/log/syslog

root@linux:~# ntpq -c lpeer
remote refid st t when poll reach delay offset jitter
==============================================================================
+alphyn.canonica 132.246.11.231 2 u 109 1024 377 195.030 -3.184 1.820
-jiro.paina.net 131.113.192.40 2 u 55 1024 377 285.680 55.800 15.483
*ntp5.mobinnet.n 85.199.214.98 2 u 1026 1024 377 208.593 -2.359 3.459
+118.140.184.98 223.255.185.2 2 u 1207 512 174 128.292 2.083 30.041
-103.47.76.177 193.0.0.229 2 u 757 1024 17 110.355 7.986 75.054

You can test if NTP Server is working or not, just download NTPTOOL and Query.
As showed in the image below …

ntp.JPG


Configure Cisco Switch to sync with ubuntu time server

enable
configure terminal
# Timezone for Asia/Karachi, you may adjust it according to your local TZ
clock timezone PST +5
service timestamps log datetime localtime
# change NTP Server IP Address
ntp server 192.168.100.1
end
show ntp associations

Before vs After (on cisco 3850 switch)

BEFORE

Switch#sh clock
*11:36:14.321 UTC Tue Jun 19 2018

enable
configure terminal
clock timezone PST +5
service timestamps log datetime localtime
ntp server 101.11.11.240
end

AFTER

Switch#sh clock
*16:37:16.103 PST Tue Jun 19 2018
Switch#show ntp associations

address ref clock st when poll reach delay offset disp
~101.11.11.240 91.189.91.157 3 11 64 1 1002.8 283436. 7937.9
* sys.peer, # selected, + candidate, - outlyer, x falseticker, ~ configured
Switch#

Done.


 

IBM Lotus Domino/Notes Related Short Notes


We are using IBM Lotus Domino 8.5.3 / FP6 (Yep its decade old version, but we are still using it). Following are some short notes for personal reference.


Lotus Notes Client USER ID file location

Sometimes when we RESET user Lotus notes password on domino server, we have to delete user.id file on user computer so that he can login instantly using new password. To delete user id file , goto

  • C:\Users\XXXXUSERXXX\AppData\Local\Lotus\Notes\Data

or Goto run and type

%userprofile%

& enter , now goto APPDATA , Local , Lotus  , Notes  , Data , & here you can see user.id file.


Delete mail.box

From domino administrator console issue following

# to exit domino
q 

# Move mail boxes files (I had 2 mailbox to hold more mails)

Move mail1.box & mail2.box out of notes data dir via OS file explorer

Now start domino

Open old mail boxes and copy (valid) held messages into new one ….. if required


Reconfigure Lotus Notes Client (Old installation)

Method #1  [Quick]

Close Lotus Notes & rename the Lotus folder following located at

C:\Users\YOURUSER\AppData\Local\Lotus

[Make sure to backup your ID file, sometimes it is required when you do reconfiguration of Notes Client & backup if file will come in handy]. In new lotus notes version starting from 8.5.3, there is no need for ID file, it auto copy from the server

Now start Lotus notes, and it will start the configuration wizard.


Cannot find external name: NAMESORTVIEWPO

  1. Open your inbox
  2. Select Actions – Folder – Upgrade folder design
  3. Choose “Automatic” and complete the process.
  4. Close/reopen mail.

This should fix your problem.


Lotus Notes TEMP location for opened saved files

Goto Start / type

%temp%

and press ENTER. it will show you few folders. Look for folder name starting with “notesxxxxx” this folder contains all the temporary files.


Block extensions with Domino server builtin configuration …

Make sure if you are checking for different types of attachments that you use OR and not AND to build your list of rules.

  • i.e., When Attachment name contains .exe
  • OR When Attachment name contains .zip
  • OR When Attachment name contains .bat

You need to review the rule for exemple:

If your rule have:

(Block *.exe AND *.pif AND *.com) the rule will block only mails that have these 3 files in the same time.

but if you create the rule as:

(Block *.exe OR *.pif OR *.com) the mail rule will block any mails that have anyone of the file extensions specified.

I was not aware of it 😮  , damm


Set Lotus Notes as Default Mail Client in 8.5.x series

To set Lotus Notes as default email client, Open Notes Client click on

  • File
  • Preferences
  • Mail
  • Internet and check “Use Lotus Notes as my default e-mail program

 

Lotus Notes Default Browser Setting

For

  • IBM Lotus Notes – Release 8.5.3
  • Revision 20110916.0921 (Release 8.5.3)
  • Standard Version

Use Following

  1. Goto Files
  2. Preferences
  3. Web Browser
  4. & select ‘Use the Browser I have set as the default for this operating system’. Make sure to set default browser for the system in default apps.

notes default browser.JPG

For

  • IBM Lotus Notes – Release 8.5.3
  • Revision 20110916.0921 (Release 8.5.3)
  • Basic Version

use following

Open Lotus Notes, Edit your ONLINE location (You can do it , Goto Internet Browser, Select Other, and then browse it to chrome file location example

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

lotus web browser setting in basic version.PNG


Fixing Lotus Notes so the inbox opens by default

Ever opened up your mailbox in Lotus Notes and for some reason it opens up by default one of your sub-folders instead of your inbox?

Someone at work had this issue and I felt like banging my head against the wall trying to find a resolution. Anyone who has to help maintain Lotus Notes knows my pain. Considering that Notes is used by so many companies, the amount of help resources online is surprisingly few.

After much searching, I found the answer though on a vaguely worded post on IBM’s Lotus Notes forums that was over 3-years old. It really sounded like a last gasp guess by someone, but with no reply saying if it actually worked.

Which it did!

All you need to do is delete, move, or rename your bookmarks.nsf file from your local Notes client Data folder. The next time Lotus Notes starts up, the bookmarks.nsf file will be recreated and Notes will once again default to your inbox when your mailbox is opened.

Warning: Keep in mind that any other settings made to the bookmarks.nsf file will be lost. For example, any changes to the vertical toolbar on the left side will be gone. That is why the best policy is to backup bookmarks.nsf first. You have been warned.


IBM Sametime Does not Open ! (v7.5)

Fist try to upgrade with latest release, it will solve many issues !

Case # 1

Symptom:
Sametime Connect displays the splash screen but does not start.

Resolution:
Before performing an unnecessary re-installation of the Sametime client, try to resolve the issue by following these steps:

1. Close the Sametime application.

2. Locate the file C:\Documents and Settings\Administrator\IBM\RCP\Sametime\.metadata\plugins\com.ibm.collaboration.realtime.imhub\shelfmemento.xml.

3. Delete the file C:\Documents and Settings\Administrator\IBM\RCP\Sametime\.metadata\plugins\com.ibm.collaboration.realtime.imhub\shelfmemento.xml.

4. Restart the Sametime application.

5. If that does not help, delete or rename C:\Documents and Settings\Administrators\IBM\RCP\Sametime or
C:\Documents and Settings\”Username”\IBM\RCP\Sametime

If nothing works, remove same time, delete its leftover folders, restart, and re install the sametime client.

Case#2

Lotus SameTime doesn’t start when launched

Short Description: Attempting to launch Lotus Sametime results in the application being highlighted in the taskbar but not getting to the splash screen or subsequently launching.

Problem:  In my case, TaskManager will show multiple copies of “rcplauncher.exe” are running but Sametime.exe is not. It appears to be a copy of the file %APPDATA%\Lotus\Sametime\.rcp.lock is…well…locked and preventing the application from launching.

To fix step by step:

Kill all instances of rcplauncher.exe

Remove the hidden attribute from %APPDATA%\Lotus\Sametime\.rcp.lock
delete or rename .rcp.lock (I’m not sure there are a lot of situations in which you would need to back up this file, but if you’re concerned, back it up).

Or run this from command line/as a cmd file:

Taskkill /F /IM rcplauncher.exe (for earlier versions of windows kill.exe may be necessary instead of taskkill)

attrib -a -h %APPDATA%\Lotus\Sametime\.rcp.lock

del /q %APPDATA%\Lotus\Sametime\.rcp.lock

if the file isn’t found and shows in explorer, check that the APPDATA environment variable is set correctly

“set |findstr APPDATA” should return

<users>\<your username>\AppData\Roaming


Lotus Traveler

After the inreasing usage of Android back in year 2013, I installed Lotus traveler (in 2014) so that android users can use IBM Verse mail app in there mobile to sync with office server.

Case#1 ,

JVM: Traveler: Lotus Traveler task did not respond within the allotted time frame (55,000 milliseconds) for action nameLookup and operation key

There is a database or connectivity issue on the server side. If you haven’t run the defrag on the Traveler (load traveler -defrag), do so now !


rvv bucket error

The error “RRV bucket is corrupt” can’t be repaired. RRV bucket means “Record Relocation Vector” table, and if this is damaged, then it can’t be repaired. Fixup, compact, updall and replace design all will fail and will throw the same error. The only solution is to replace with the last back up copy of database. RRV bucket becomes corrupt if the OS hangs, crashes or restarted at the moment when the Record Relocation Vector table is being updated.


Lotus Notes Sent emails are not saving under SENT folder [Added 08-January-2019]

Version: Lotus Notes 8.5.3 (FP6)

Fix:

Goto

File | Preferences | User Preferences | Mail | Sending & Receiving

& look for option “Save copied of mail that I send”, It’s a DROP down menu, select ALWAYS , & ok


Lotus Notes Set Default Font/Size/Color for New Email Composing

  • Compose new email, , now change the text font and size you want to use as Default,
  • From the top menu, Select the text.
  • Open the Text menu and select Set Current Font as Mail Default.

Note:
Your new default font will appear in the next email you compose. It will not effect the current email composition.


Lotus Domino Server LOGGING level for console/mail routing

Set Config Log_Sessions=2

Set Config Log_MailRouting=40
  • If you set the Router log level to 40 (maximum output), you get everything. Server Connected, IP Address, Sender, Recipient, SMTP session
  • If you increase the Session log level to the option introduced back with 8.5.1, you get all of the information about a server/users connection: Name, Client Version Number, IP address and access type (eg: C=native client),


Lotus Notes Create FOLLOW UP

Create Follow Up Flags

Sometimes you may view a message and then want to flag it for further (or special) attention.  To remind yourself to return to the e-mail later, you may mark it with a follow up flag, which places an indicator next to the message in the Inbox.  In addition to the flag indicator, you may also set a reminder alarm to pop up at the time and date of your choosing.

Here are the steps for setting a follow up flag and alarm:

  1. Select the message or open it.
  2. Click the down arrow on the Flag button on the toolbar.
  3. Select Add or Edit Flag.
  4. Choose either Urgent Priority  , Normal Priority  , and Low Priority  .
  5.  This will determine the color of the flag indicator next to the message.
  6. Type a follow up action or note for yourself.
  7. Set a follow up date and time (if desired).
  8. Turn on the alarm if you want a pop-up reminder before the time and date set.
  9. Click OK.

There is a follow up column in your Inbox view by which you may sort your follow up flags.  Lotus Notes will place all messages with follow up flags at the top of the list.

When you are finished with a follow up task and want to clear the follow up flag, select the message, click the down arrow on the Flag button again, and select Remove Flag.


Lotus Traveler on iPhone 7

https://smallbusiness.chron.com/connect-iphone-lotus-notes-7-75665.html


Lotus EXPORT all users details

Goto File > Open > Lotus Notes Application

A new browser window will open, in LOOK IN , seelct your server, & select names.nsf (your Company Directory, ex: XYZ Direcotry), & click OPEN

Now your DIRECOTRY will be displayed,

From file Menu, goto CREATE > VIEW,
A new window will appear,
in VIEW NAME, type any name like XYZ_ALL_EMAIL_ADDRESSESS,
in VIEW TYPE, select PRIVATE, & click “SAVE & CUSTOMZIE”,
new View windows will appear, in this view , click on return ARROW icon, (left side), and directory contact with some info will appear,

Right click on column window , and select APPEND NEW COLUMN

From Lower Right Window, Select FIELD,
You will lot of options, find and select INTERNETADDRESS
and click on Return Arrow on top left ,
You will see all Users Internet Email Addresses,
From this view you can delete any unnecessary column you dont want to see / export

Now to export them in file, Goto FILE / EXPORT, Enter file name, and select TABULAR TEXT in SAVE AS option,
, it will then ask you to select options for Export, do the needful and click OK


Microsoft Products Short Notes – Personnel References


This post contains short notes / Tips for personal references, These are common task that we perform on daily basis in out IT slavery environment!

Regards
Syed Jahanzaib


Event Viewer Codes for various Login Sessions:

Dameware:

Event ID: 111
Description: When any remote user is connected to the system via DAMEWARE MINI REMOTE CONTROL applicaiton

Event ID: 112
Description: When any already connected remote user is disconnected

Windows RDP:

Event ID: 21,22,23,24,25

More Details can be found at Event Viewer > Applications & Services Logs > Microsoft > Windows > TerminalServices-LocalSessionManager — OPERATIONAL

You can make your customized scripting based on above Events 🙂

 


Find Reason/time of Windows Shutdown/Restart

To find out the reason

  • Login to Windows
  • Launch the Event Viewer (or type eventvwr in run)
  • In the event viewer console expand Windows Logs
  • Click System and in the right pane click Filter Current Log

In the Filter Current log box, use below EVENT ID’s number as the event ID. This will filter the events and you will see events only with mentioned ID’s

  • Event ID 6005 (alternate): “The event log service was started.” This is synonymous to system startup.
  • Event ID 6006 (alternate): “The event log service was stopped.” This is synonymous to system shutdown.
  • Event ID 6008 (alternate): “The previous system shutdown was unexpected.” Records that the system started after it was not shut down properly.
  • Event ID 6009 (alternate): Indicates the Windows product name, version, build number, service pack number, and operating system type detected at boot time.
  • Event ID 6013: Displays the uptime of the computer. There is no TechNet page for this id.
  • Event ID 1074 (alternate): “The process X has initiated the restart / shutdown of computer on behalf of user Y for the following reason: Z.” Indicates that an application or a user initiated a restart or shutdown.
  • Event ID 1076 (alternate): “The reason supplied by user X for the last unexpected shutdown of this computer is: Y.” Records when the first user with shutdown privileges logs on to the computer after an unexpected restart or shutdown and supplies a reason for the occurrence.
To differentiate between power loss and a reboot due to bugcheck, look for combination of Event ID 41 (source: Microsoft-Windows-Kernel-Power) and Event ID 1001: (source: BugCheck). Former without the latter indicates power loss or reset.
In the Includes/Excludes event ID’s input field in the Filter Current Log window, You can enter “6005, 6006, 6008, 6009, 6013, 1074, 1076” and it can give you helpful information all together.
You can also probably add Kernel-General with eventid 12, which is typically the first eventid to be logged after a reboot/reset etc and shows the actual “system start time”, i.e.: “The operating system started at system time xxxx‎-xx‎-xxTxx:xx:xx.xxxxxxxxxZ.”

POWERSHELL CMD to find reboot shutdown reasons

The proposed solution is a one-liner Powershell script:

Get-EventLog -LogName System |? {$_.EventID -in (6005,6006,6008,6009,1074,1076)} | ft TimeGenerated,EventId,Message -AutoSize –wrap


Domain joined Workstation Rename Error

 

domain workstation rename error

Today When our IT Support personnel was trying to rename user computer name which was joined with the domain, got above error

To sort this issue we had to run this cmd (RUN AS ADMIN CMD)

net use * /d
net stop workstation /y
net start workstation

Afterwards the rename process went smoothly.

Windows 10 – Add / Disable,Enable Folder in Startup Menu

  • Add program in Windows 10 startup folder
RUN

shell:startup

now copy shortcut of your program in this folder, and it will run on windows startup

  • To disable enable program at startup

Right click on TASK MANAGER / STARTUP


Powershell PSTerminalServices module

This module helped to see who is logged on remote pc via RDP with client ip/name

First download the module from here ….

then import it in powershell. make sure to run powershell RUN as admin.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Get-Module -Name PSTerminalServices -ListAvailable
Import-Module PSTerminalServices
Get-Command -Module PSTerminalServices

# Gets all Active sessions from remote computer ‘comp1′, made from IP addresses that starts with ’10’.

Get-TSSession -ComputerName ZAIBPC

OR

Get-TSSession -ComputerName comp1 -Filter {$_.ClientIPAddress -like '10*' -AND $_.ConnectionState -eq 'Active'}

MORE COMMANDS

# Logs off all the active sessions from remote computer 'comp1', no confirmations
Get-TSSession -ComputerName comp1 -State Active | Stop-TSSession –Force

# Displays a message box inside all active sessions of computer name 'comp1'."}
PS > $Message = "Importnat`n, the server is going down for maintenance in 10 minutes. Please save your work and logoff."
PS > Get-TSSession -State Active -ComputerName comp1 | Send-TSMessage -Message $Message

# Gets all processes connected to session id 0 from remote computer 'comp1'.
PS>Get-TSSession -ID 0 -ComputerName comp1 | Get-TSProcess

Find UPTIME of remote PC

SystemInfo /s ZAIBPC | find "Boot Time:"

Check motherboard version

wmic baseboard get product,Manufacturer,version,serialnumber


PSTOOLS Related

.

Adding Local Account in remote workstation with PSTOOLS

If you are domain admin, and wanted to add local account in remote client workstation, then use pstools’s psexec 

psexec.exe \\target-pc net user /add USERNAME  USERPASSWORD
psexec.exe \\target-pc net net localgroup administrators USERNAME /add

# PSLOGGEDON COMMANDS
To check which user is logged on remote pc,

psloggedon \\remotepc

# PSEXEC COMMANDS

– To execute any command on remote pc like

psexec \\remtotepc ipconfig

OR update group policy on remote PC

PsExec.exe \\REMOTEPC -u DOMAIN\ADMINISTRATOR -p PASSWORD cmd "/c gpupdate /force"
  • Check network configuration and find IP address only,
PsExec.exe \\REMOTEPC ipconfig|findstr /i "IPv4"

– To open COMMAND prompt of remote user

psexec \\remotepc cmd

-Interacting with the Logged On User on the Remote PC

psexec \\remotepc -d -i notepad

# PSINFO COMMANDS
Getting general info with disk info as well

psinfo -d \\remotepc

# PSLIST COMMANDS

pslist \\remotepc

# PSKILL COMMANDS
– Kill remote pc program

pskill \\remotepc notepad

to query time

net time \\REMOTEPC

To change time on remote pc with domain server agpinf05

PsExec.exe \\REMOTEPC -u DOMAIN\ADMIN -p PASS cmd "/c net time \\DC /set /y"

Change IP configuration of remote PC to obtain IP via DHCP

psexec \\REMOTEPC cmd
ipconfig

Then note down the required interface name and issue following command,

  • Check current Config
netsh interface ip show config
  • EXPORT current settings
netsh -c interface dump > c:\location1.txt 
  • Set Manual IP
netsh interface ip set address name="Local Area Connection" static 192.168.0.100 255.255.255.0 192.168.0.1
  • Change IP settings from STATIC to DHCP
netsh interface ip set address "Local Area Connection" dhcp

Batch file to change setting of network adapters to obtain IP from DHCP

Make sure to change adapter names to match your’s …

@echo off
echo Setting IP Address to AUTO DHCP [Office DHCP Server by syed.jahanzaib]...
netsh interface ip set address name="Local Area Connection" source=dhcp
netsh interface ip set dns "Local Area Connection" source=dhcp
netsh interface ip set address name="Wireless Network Connection" source=dhcp
netsh interface ip set dns "Wireless Network Connection" source=dhcp
echo Done....

Command to change IP via CMD

netsh interface ip set address name=”Local Area Connection” static 192.168.0.1 255.255.255.0 192.168.0.254
netsh interface ip set dns name=”Local Area Connection” static 192.168.0.250
netsh interface ip add dns name=”Local Area Connection” 8.8.8.8 index=2

Check Remote PC OS version & other details by CMD

systeminfo /s \\REMOTEPCNAME
# OR
systeminfo /s \\REMOTEPCNAME|findstr /i "host OS "

Result:

C:\>systeminfo /s \\syed_jahanzaib

Host Name: SYED_JAHANZAIB
OS Name: Microsoft Windows 7 Professional
OS Version: 6.1.7601 Service Pack 1 Build 7601
OS Manufacturer: Microsoft Corporation
OS Configuration: Member Workstation
OS Build Type: Multiprocessor Free
Registered Owner: Syed Jahanzaib
Registered Organization:
Product ID: xxxxxx-005-xxxx-xxxx
Original Install Date: 4/11/2017, 1:14:44 PM
System Boot Time: 6/19/2018, 7:44:47 AM
System Manufacturer: INTEL_
System Model: DH77KC__
System Type: x64-based PC
Processor(s): 1 Processor(s) Installed.
[01]: Intel64 Family 6 Model 58 Stepping 9 GenuineIntel ~3392 Mhz
BIOS Version: Intel Corp. KCH7710H.86A.0069.2012.0224.1825, 2/24/20
12
Windows Directory: C:\Windows
System Directory: C:\Windows\system32
Boot Device: \Device\HarddiskVolume1
System Locale: en-us;English (United States)
Input Locale: en-us;English (United States)
Time Zone: (UTC+05:00) Islamabad, Karachi
Total Physical Memory: 8,090 MB
Available Physical Memory: 2,450 MB
Virtual Memory: Max Size: 16,178 MB
Virtual Memory: Available: 10,455 MB
Virtual Memory: In Use: 5,723 MB
Page File Location(s): C:\pagefile.sys
Domain: DOMAIN1
Logon Server: \\DOMAIN_DC
Hotfix(s): 187 Hotfix(s) Installed.
...........................
Network Card(s): 3 NIC(s) Installed.
[01]: Intel(R) 82579V Gigabit Network Connection
Connection Name: DOMAIN - LAN
DHCP Enabled: No
IP address(es)
[01]: 192.168.100.100
[02]: 192.168.50.10
[03]: 192.168.8.23
[02]: VMware Virtual Ethernet Adapter for VMnet1
Connection Name: VMware Network Adapter VMnet1
DHCP Enabled: No
IP address(es)
[01]: 169.254.97.149
[02]: fe80::ad90:fdcb:3f81:6195
[03]: VMware Virtual Ethernet Adapter for VMnet8
Connection Name: VMware Network Adapter VMnet8
DHCP Enabled: No
IP address(es)
[01]: 169.254.80.235
[02]: fe80::5598:be9:b61d:50eb

C:\>

DCHP Related ! [Tested with W2008]

DHCP is running on windows 2008 server, IP is 192.168.0.1


#DCHP BACKUP
netsh dhcp server 192.168.0.1 dump > c:\dhcpoutput.txt all

#DHCP DELETE OLD SCOPE
netsh dhcp server delete scope 192.168.0.0 dhcpfullforce

#DHCP IMPORT
[Disable DHCP Service before import]
netsh dhcp server import c:\tools\dhcpoutput all

#DHCP DISABLE
netsh dhcp server 192.168.0.1 scope 192.168.0.0 set state 0

Disable Internet Explorer Proxy via CMD

REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f

Clear cache in windows

ipconfig /flushdns
net stop dnscache
net start dnscache

Event ID

https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/default.aspx?i=j


Excel 2010 showing Blank Sheet

in Excel 2010 , When you open any excel sheet,( any particular, either yours or sent to you by some one else , it appears blank sheet

This may also occur if your computer’s screen resolution is higher than that of the person who last saved the workbook.

In Excel 2010, go to the View tab.

Select the ‘Arrange All’ button, then choose to Cascade.

OR

Excel 2010
opening blank sheets

ctrl+shift and open file
or its related with MACRO, run macro


Display printers list installed on Remote PC

Get-WMIObject Win32_Printer -ComputerName REMOTE_PC_NAME

CHECK OS COMPUTER OF REMOTE COMPUTER

Get-WmiObject Win32_OperatingSystem -ComputerName "YOURPCNAME" | Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber | FL

GET LIST OF INSTALLED PRODUCTS ON REMOTE PC

POWERSHELL

Get-WmiObject -Class Win32_Product -Computer MYPCNAME

Display Motherboard model via CMD

- To find Board number of local pc
wmic baseboard get product,Manufacturer,version,serialnumber

- To find Board number of remote pc
wmic /node:"remotepc" baseboard get product,Manufacturer,version,serialnumber

- To find remote pc Architechture liek 32bit or 64bit
wmic /node:"remotepc" os get osarchitecture

Adding Static Routes in Windows via CMD

Adding route for single host

route -p ADD 10.1.1.12 MASK 255.255.255.255 101.11.11.4 METRIC 1 IF 11

Notes:

To open a command prompt, click Start, point to All programs, point to Accessories, and then click Command prompt.

To make a static route persistent, you can either enter route add commands in a batch file that is run during system startup or use the -p option when adding routes.

Routes added by using the -p option are stored in the registry under the following key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip \Parameters\PersistentRoutes

Windows 7 Temporary profile Issue:

How to Fix Temporary Profile in Windows 7/ 8.1/10


There is no script engine for file extension .vbs

When we upgraded from win7 to windows 10/2012, our domain welcome logon script stopped working, with above error, to sort it we copied welcome vb script to domain logon folder and used this …

cscript //e:vbscript c:\path\to\script.vbs

Convert bootable USB in ISO file

The instructions for USB to .iso are as follows (for a Windows 7 installation for example):

  1. Install ImgBurn. You can even get a portable version of it, just search for it.
  2. Plug the bootable USB into the computer
  3. Start ImgBurn.
  4. Click on the “Create image file from files / folders” button on the home menu.
  5. In “Sources” browse to the USB drive.
  6. In “Destination” choose where to save the final .iso image.
  7. Go to the “Advanced” tab on the right and then “Bootable Disk”.
  8. Check the box “Make Bootable Image” and then, in the “Boot image” box browse to file “etfsboot.com” that is in the USB stick found in the folder “boot”.
  9. In the field “Developer ID” put “Microsoft Corporation” and enter “07C0” in the “Load Segment” field.
  10. Enter ‘4’ in the ‘Sectors To Load’ field if your etfsboot.com file is 2K is size, enter ‘8’ if it’s 4K. In other words, x = size of etfsboot.com in bytes / 512.
  11. Click “Build” and you’re done!

Credits: https://mindthebandgap.wordpress.com/2013/03/13/how-to-convert-bootable-usb-into-an-iso-file/


Reboot / Shutdown – Remote Workstation from Domain Admin PC

shutdown /r /t 60 /m \\REMOTE-PC /c "YOU PC WILL REBOOT AFTER 1 MINUTE..."
shutdown /r /f 60 /m \\REMOTE-PC /c "YOU PC WILL REBOOT AFTER 1 MINUTE..."

60 is seconds, you can up n down this value as per your requiremnts


.NET Framework 3.5 error code 0x800F081F on Windows 10.

net error.png

To solve it, use following.

Dism /online /enable-feature /featurename:NetFx3 /All /Source:D:\sources\sxs /LimitAccess

In above command make sure to change the path D:\sources\sxs to your windows 10 dvd / usb location. Basically You have to provide the Windows installation DVD/USB path so that it can copy the required files for .net

Get Installed Printer list from remote workstation using PS cmd

Get-WmiObject win32_printer -ComputerName "REMOTE_PC_NAME"

Disable Internet Explorer (chrome) Proxy via CMD

REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f

Check System Info & HOTFIXES / Windows Updates

Windows Built In cmd’s to query for System information & windows updates list


wmic qfe | find “982802”
systeminfo > c:\updates.txt

PowerShell:


get-hotfix
To search for a specific hotfix
get-hotfix | out-string -stream | select-string "KB977236"


Find windows version remotely

systeminfo /s 10.1.1.2 | findstr /B /C:"Host Name" /C:"OS Name" /C:"OS Version"

Get computer hardware details

wmic computersystem get model,name,manufacturer,systemtype

wmic csproduct get name

wmic bios get serialnumber

wmic csproduct get name

FOLDER’s Related CMD’s

To delete all folders starting with 1

Direct CMD run command

for /d %i in (1*) do rd /s/q "%i"

CMD to be used in BATCH file

for /d %%i in (1*) do rd /s/q "%%i"

To count folders numbers

dir /a:-d /s /b "C:\Users\MYNAME\AppData\Local\Temp" | find /c ":"

Windows Patches List

wmic qfe list

Search particular Patch

wmic qfe | find "4013389"

Powershell:

get-hotfix

DHCP related CMD’s


########### DHCP COMMANDS ##############

# Search user by mac IP ADdress
Get-DhcpServerv4Lease -ComputerName 10.11.11.5 -IPAddress 10.11.17.70

# Get all leases from DHCP Server
Get-DhcpServerv4Lease -ComputerName 10.11.11.5 -ScopeId 10.0.0.0
Get-DhcpServerv4Lease -ComputerName 10.11.11.5 -ScopeId 10.0.0.0 -AllLeases

# Get particular information only for in all leases
Get-DhcpServerv4Lease -ComputerName 10.11.11.5 -ScopeId 10.0.0.0 | select-object IPAddress,ClientId,HostName,Description

# Search user by MAC Address
Get-DhcpServerv4Lease -ComputerName 10.11.11.5 -ScopeId 10.0.0.0 -EA SilentlyContinue -ClientId fa-52-78-b8-ef-d8
Get-DhcpServerv4Scope -ComputerName 10.11.11.5 | Get-DhcpServerv4Lease -EA SilentlyContinue -ClientId 3c-52-82-59-87-76
Get-DhcpServerv4Scope | foreach {Get-DhcpServerv4Lease -computername $env:YOURDC -allleases -ScopeId ($_.ScopeId) as [string] } | ? clientid -match '00-04-f2-f'

#Get FREE IP Addressess details
Get-DhcpServerv4FreeIPAddress -ComputerName 10.11.11.5 -ScopeId 10.0.0.0

# ADD IP Reservation IN DHCP VIA CMD
Add-DhcpServerv4Reservation -ComputerName 10.11.11.5 -ScopeId 10.0.0.0 -IPAddress 10.11.14.235 -ClientId 54-ee-75-e8-ad-18 -Description "temp.guest" -Name "temp.guest"
# ADD GATEWAY for reserved IP IN DHCP VIA CMD
Set-DhcpServerv4OptionValue -ComputerName 10.11.11.5 -ReservedIP 10.11.14.235 -Router 10.11.11.6

Change Windows Remote Desktop (RDP) Default Port to other value

First check what is current port


Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "PortNumber"

Now to change it use below code , Ensur eyou are opening powershell CMD as RUN AS ADMINISTRATOR


$portvalue = 44440

Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "PortNumber" -Value $portvalue

Now you can access the remote PC RDP like 192.168.0.1:44440


Regard’s
Syed Jahanzaib

June 13, 2018

Skype for business WEBAPP stops on Loading

Filed under: Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 1:31 PM

Skype for business webapp is a quick method to join meetings invitation sent by remote parties. Today when one of our user (with Windows 7 & IE8) tried to join the meeting  using Google Browser (latest version) (with S4B webapp plugin installed) , the window stuck at Loading … as showed in the image below …

SKYPE FOR BUSINESS STUCK ON LOADING ERROR

After some R&D, it found that if you have IE 8 or below, you must upgrade to new version.

After we upgraded IE from 8 to 11 , the S4B webapp worked smoothly.

skype working ok afger IExplorer 11 updates.png

June 8, 2018

Disabling Email for CRON Job’s

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

If you have configured many cronjob’s to run every minute or so on, & also using Gmail as mail relay system on the same box, you might see following in ​​/var/log/mail.log

Jun 8 10:21:10 radius postfix/smtp[5192]: 6DA0D16E0118: to=, relay=smtp.gmail.com[74.125.71.108]:587, delay=3.3,
delays=0.01/0/2.9/0.41, dsn=5.4.5, status=bounced (host smtp.gmail.com[74.125.71.108] said:
550 5.4.5 Daily user sending quota exceeded. e188-v6sm2329623wmf.21 - gsmtp (in reply to DATA command))

gmail error.JPG
gmail error

CRON will only email you if there is some output from you job. With everything redirected to null, there is no output and hence cron will not email you.

Using > /dev/null 2>&1 will redirect all your command output (both stdout and stderr) to /dev/null, meaning no outputs are printed to terminal.

If you have configured an emailing system which is using gmail (which limits 500 messages per day) as mail relay then put the following command at the end of the cron job line that always output the result.

Example:

Before:

*/5 * * * * /temp/mybashscript.sh

After:

*/5 * * * * /temp/mybashscript.sh  >/dev/null 2>&1

Regard’s
Syed Jahaznaib

June 1, 2018

Phpmyadmin – Short Notes

Filed under: Linux Related — Tags: , , , — Syed Jahanzaib / Pinochio~:) @ 11:24 AM


1# ROOT access error in phpmyadmin v 4.6.6deb5 with Ubuntu 18.0.4

If you have installed phpmyadmin in Ubuntu 18, & trying to login with root, you may see following error,

phpmyadmin root error

It’s recommended to add another user & use this ID to login in phpmyadmin.

Create User in Mysql:

Login to mysql & issue below commands, make sure to change user name and passwords

CREATE USER 'NEWUSER'@'%' IDENTIFIED BY 'NEWPASSWORD';
GRANT ALL PRIVILEGES ON *.* TO 'NEWUSER'@'%' WITH GRANT OPTION;
exit;

2# When viewing Tables in phpmyadmin, Popup Error Appears ‘some errors have been detected on the server, please look at the bottom of this window’

When viewing tables in Phpmyadmin v4.6.6deb5 [Ubuntu 18.0.4] , below error appears …

phpmyadmin view table error.JPG

FIX:

It seems that phpMyAdmin v4.6.6 is not fully compatible with PHP 7.x. Upgrade to new version v4.8 or above which will fix these compatibility issues.

OR following method.

Warning …

Make sure to backup sql.lib.php before any modification

cp /usr/share/phpmyadmin/libraries/sql.lib.php /usr/share/phpmyadmin/libraries/sql.lib.php.bak

Edit sql.lib.php

sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php

Press CTRL + W and search for

|| (count($analyzed_sql_results['select_expr'] == 1)

Replace it with

|| ((count($analyzed_sql_results['select_expr']) == 1)

Save file and Exit.

Hopefully you will not see the above errors any more 🙂


Upgrade PHPMYADMIN in Ubuntu 18

phpmyadmin latest: 4.9.0.1 [as of Dec 2019]

Default version of PHPMYADMIn is 4.6.6deb5 & using below code we will upgrade to to > 4.9.1deb2

sudo add-apt-repository ppa:phpmyadmin/ppa
sudo apt-get update
apt-get -y install phpmyadmin

mysqli::real_connect(): (HY000/2002): No such file or directory when I try to access my project on live server

Scenario:

Today we got following error while login to phpymadin panel.

OS: Ubuntu 18 
PhpmyAdmin Version: 4:5.0.4+dfsg2-2~bpo10+1+bionic1

Error:

To fix this, edit file

 nano /etc/phpmyadmin/config.inc.php 

& search for

 $cfg['Servers'][$i]['host'] 

& change it to below

 $cfg['Servers'][$i]['host'] = '127.0.0.1'; 

Save & Exit, nwo try to login to phpMYADMIN & hopefully it will work insha Allah


Regard’s
Syed Jahanzaib

%d bloggers like this: