Syed Jahanzaib Personal Blog to Share Knowledge !

April 22, 2019

MySql Database Recovery from Raw Files

Filed under: Linux Related, Radius Manager — Tags: , , , , , — Syed Jahanzaib / Pinochio~:) @ 2:31 PM

mysql recovery.PNG


Disclaimer: This worked under particular case. It may or may not work for everyone.

Scenario:

OS: Ubuntu 12.4 Servedit Edition / x86

MYSQL: Ver 14.14 Distrib 5.5.54, for debian-linux-gnu (i686) using readline 6.2

The OP was running radius for AAA. The disk got faulty for some unknown reasons and were unable to boot from it. There was no database backup [Real example of bad practices] So restoration from mysqldump to new system was not an option there !

Requirements:

We need to restore the Database using mysql raw files. Luckily the faulty disk was able to got attached to other system & we were able to copy the core /var/lib/mysql/ folders (along with all sub folders in it)


Quick & Dirty Restoration Step !

Requires some good level of Linux / DB knowledge]

  • Setup a test SANDBOX, Install same level of OS along with MYSQL on new system/disk. Create databases / tables as required. Verify all is working by logging to mysql
  • Stop the MYSQL service.
  • Copy the folder /var/lib/mysql [copied from faulty disk] to this new box under /var/lib/mysql/  
  • Set the permission on newly copied files/folders
    chown mysql -R /var/lib/mysql/

After this point Try to start the MYSQL service , IF it starts successfully & you can see your DATA , then skip below steps , ELSE continue through below steps …

  • Edit the /etc/mysql/my.cnf & add following line under [mysqld] section
    innodb_force_recovery = 6
  • Start MYSQL service & the service will start in Safe Mode with limited working support. Verify if you can able to login to MYSQL service by
    mysql -uroot -pPASS
  • If above step works, Export the Database backup using mysqldump cmd e.g:
    mysqldump -uroot -pSQLPASS   radius  >  radius_db_dump_.sql
  • Once done, Open the file in nano or any other text editor, & verify if it contains the required data.

Now copy the radius_db_dump_.sql to safe location & you know what to do next 🙂

  • Import this mysqldump file to your working radius system !

TIPS:

best-practice2

Make sure you have multistage backup strategies in place for any mission critical server.

Example for mysql Database, You can do following

  • If your server is VM, then VEEAM B&R will be your best friend & guardian, go for it
  • 1st Stage Backup: [Highly recommended for live replication]
    ideally, you should have at least 2 Replica servers & configure either Master-Master or Master-Slave Replication
  • 2nd Stage backup:
    Create bash scripts to export DB backup in local folder on a daily basis, (or hourly basis if required]
  • 3rd Stage backup:
    Attach external USB disk to the server, and in your backup script, add this usb as additional backup repository
  • 4th Stage backup:
    Configure DROPBOX and add it as additional backup repository
  • 5th Stage backup:
    The admin should manually copy the backup folders to his desktop so that if all other backups gets failed , this should come in handy.

Regard’s
Syed Jahanzaib

 

 

 

January 16, 2019

BASH script to monitor Cisco Switch Port Status

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

portmonitor

2019-01-17 10.05.47.jpg

Following script was designed for an OP who wanted to monitor his cisco switch ports status via linux base bash script.

  • Created: February, 2016
  • Revision: January, 2019

 

OP Requirements:

  • We need a bash script that can acquire ports status of Cisco switch using SNMP query & act accordingly based on the results, example send sms/email etc,
  • The script should first check target device network connectivity by ping, if PING NOT responding, Exit,
  • If ping OK, then check SNMP status, if SNMP NOT responding, then error report, & Exit,
  • If Ping / SNMP responds OK, then check the port status, if port status is NOT UP , then send email/sms alert 1 time until next status change.

Hardware / Software Used in this post:

  • Cisco 3750 24 Gigabit Ports Switch
  • Ubuntu 12.4 Server Edition
  • Bash Script
  • SNMP support enabled on Cisco switch to query port status using MIB names

Solution:

I made following script which checks PING/SNMP status, and then Port Status of Cisco 3750 Switch. This is just an example. You can use your own techniques to acquire the same result. This is fully tested and working script. There are many other ways to do the same like using any NMS app like Nagios, or DUDE which have good GUI control so no need to do coding in the dark : )

Surely this contains too much junk or some unwanted sections, so you may want to trim it according to your taste and requirements.

Regard’s
Syed Jahanzaib


  1. Install SNMP MIBS

First we need to make sure that MIB are installed, Do so by

sudo apt-get install -y snmp
apt-get install -y snmp-mibs-downloader
sudo download-mibs

After this , Add SNMP Mibs entry in

/etc/snmp/snmp.conf

by adding this line

mibs +ALL

Save & Exit

Now query your switch by following command to see if snmpwalk is working …

root@Radius:/temp# snmpwalk -v1 -c wl 10.0.0.1 IF-MIB::ifOperStatus

& you should see something line below if SNMP is working …

IF-MIB::ifOperStatus.1 = INTEGER: up(1)
IF-MIB::ifOperStatus.17 = INTEGER: up(1)
IF-MIB::ifOperStatus.5182 = INTEGER: down(2)
IF-MIB::ifOperStatus.5183 = INTEGER: down(2)
IF-MIB::ifOperStatus.5184 = INTEGER: down(2)
IF-MIB::ifOperStatus.10601 = INTEGER: up(1)
IF-MIB::ifOperStatus.10602 = INTEGER: down(2)
IF-MIB::ifOperStatus.10603 = INTEGER: down(2)
IF-MIB::ifOperStatus.10604 = INTEGER: down(2)
IF-MIB::ifOperStatus.10605 = INTEGER: up(1)
IF-MIB::ifOperStatus.10606 = INTEGER: up(1)
IF-MIB::ifOperStatus.10607 = INTEGER: up(1)
IF-MIB::ifOperStatus.10608 = INTEGER: up(1)
IF-MIB::ifOperStatus.10609 = INTEGER: up(1)
IF-MIB::ifOperStatus.10610 = INTEGER: up(1)
IF-MIB::ifOperStatus.10611 = INTEGER: up(1)
IF-MIB::ifOperStatus.10612 = INTEGER: up(1)
IF-MIB::ifOperStatus.10613 = INTEGER: up(1)
IF-MIB::ifOperStatus.10614 = INTEGER: up(1)
IF-MIB::ifOperStatus.10615 = INTEGER: up(1)
IF-MIB::ifOperStatus.10616 = INTEGER: up(1)
IF-MIB::ifOperStatus.10617 = INTEGER: up(1)
IF-MIB::ifOperStatus.10618 = INTEGER: up(1)
IF-MIB::ifOperStatus.10619 = INTEGER: up(1)
IF-MIB::ifOperStatus.10620 = INTEGER: up(1)
IF-MIB::ifOperStatus.10621 = INTEGER: up(1)
IF-MIB::ifOperStatus.10622 = INTEGER: up(1)
IF-MIB::ifOperStatus.10623 = INTEGER: up(1)
IF-MIB::ifOperStatus.10624 = INTEGER: up(1)
IF-MIB::ifOperStatus.10625 = INTEGER: down(2)
IF-MIB::ifOperStatus.10626 = INTEGER: down(2)
IF-MIB::ifOperStatus.10627 = INTEGER: down(2)
IF-MIB::ifOperStatus.10628 = INTEGER: down(2)
IF-MIB::ifOperStatus.14501 = INTEGER: up(1)

OR getting UP/DOWN result for particular port (port 10)

snmpwalk -v1 -c wl 10.0.0.1 IF-MIB::ifOperStatus.10610 -Oqv

Output Result:

up

 

 


the Script!

  • mkdir /temp
  • cd /temp
  • touch monitor_sw_port.sh
  • chmod +x monitor_sw_port.sh
  • nano monitor_sw_port.sh

and paste following, make sure to edit all info accordingly…

#!/bin/bash
#set -x
# Script to check Cisco Switch Port Status and send alert accordingly
# It will first check PING, then SNMP Status, then PORT status & act accordingly
# Email: aacable at hotmail dot com / http : // aacable . wordpress . com
# 15-Jan-2019
HOST="$1"
PORT="$2"
SNMP="public"
DEVNAME="ZAIB_Main_Switch"
HOSTNAME=`hostname`
TEMP="temp"
COMPANY="ZAIB (Pvt) Ltd."
DATE=`date`
# GMAIL DETAILS
GMAILID="MYGMAIL@gmail.com"
GMAILPASS="GMAIL_PASS"
ADMINMAIL1="aacableAThotmail.com"
SENDMAIL="/temp/sendEmail-v1.56/sendEmail"
# SMS RELATED and KANNEL INFO
# KANNEL SMS Gateway Info
KANNELURL="127.0.0.1:13013"
KANNELID="kannel"
KANNELPASS="KANNEL_PASS"
CELL1="03333021909"
PING_ATTEMPTS="2"
HOST_PING_STATUS="/$TEMP/$HOST.$PORT.ping"
HOST_PORT_STATUS="/$TEMP/$HOST.$PORT.port"
LAST_DOWNTIME_HOLDER="/$TEMP/$HOST.$PORT.last_down.status.txt"
touch $HOST_PING_STATUS
touch $HOST_PORT_STATUS
touch $LAST_DOWNTIME_HOLDER
# If ip parameters are missing, then inform & exit
if [ -z "$HOST" ];then
echo "Error: IP missing, Please use this,
./monitor_sw_port.sh 10.0.0.1 10601"
exit 1
fi
# If port parameters are missing, then inform & exit
if [ -z "$PORT" ];then
echo "Error: PORT number missing, Please use this,
./monitor_sw_port.sh 10.0.0.1 10601"
exit 1
fi
# Test PING to device
count=$(ping -c $PING_ATTEMPTS $HOST | awk -F, '/received/{print $2*1}')
if [ $count -eq 0 ]; then
echo "$HOST $DEVNAME is not responding to PING Attempts, cannot continue without , por disable ping check] !"
exit 1
else
echo "- PING Result : OK"
fi
# Test SNMP Result of device
snmpwalk -v1 -c $SNMP $HOST SNMPv2-MIB::sysDescr.0 > /tmp/$HOST.$PORT.snmp.status.txt
if [ ! -f "/tmp/$HOST.$PORT.snmp.status.txt" ]; then
echo "- ALERT: ..... $HOST $DEVNAME is not responding to SNMP Request, Cannot continue without it ... Exit"
exit 1
else
echo "- SNMP Result : OK"
fi
# If all OK, then pull Port Description
PORT_DERSCRIPTION=`snmpwalk -v1 -c $SNMP $HOST IF-MIB::ifDescr.$PORT -Oqv`
# Check if folder exists, if not create one and continue
if [ ! -d "/$TEMP" ]; then
echo
echo
echo "/$TEMP folder not found, Creating it so all ping results should be saved there . . ."
mkdir /$TEMP
fi
### START ACTION
################################
### CHECK PORT STATUS - for UP #
################################
CHKPORT=`snmpwalk -v1 -c $SNMP $HOST IF-MIB::ifOperStatus.$PORT -Oqv`
#CHKPORT="up"
# If Port number does not exists, then inform and exit
if [ -z "$CHKPORT" ]; then
echo "ALERT: .... Port number $PORT NOT found on $HOST $DEVNAME , Please check Port Number, Exiting ..."
exit 1
fi
#########################################
# SMS/EMAIL Messages for PORT UP / DOWN #
#########################################
# Temporary file holder for PORT DOWN/UP storing sms/email
PORT_DOWN_MSG_HOLDER="/$TEMP/$HOST.$PORT.down.msg"
PORT_UP_MSG_HOLDER="/$TEMP/$HOST.$PORT.up.msg"
echo "ALERT:
$DEVNAME $HOST port $PORT $PORT_DESCRIPTION is DOWN @ $DATE
$COMPANY" > $PORT_DOWN_MSG_HOLDER
echo "INFO:
$DEVNAME $HOST port $PORT $PORT_DESCRIPTION is OK @ $DATE!
$COMPANY" > $PORT_UP_MSG_HOLDER

PORT_DERSCRIPTION=`snmpwalk -v1 -c $SNMP $HOST IF-MIB::ifDescr.$PORT -Oqv`
HOST_PORT_DOWN_ALERTONSCREEN="ALERT: .... $HOST $DEVNAME port nummber $PORT $PORT_DERSCRIPTION is DOWN @ $DATE"
HOST_PORT_UP_ALERTONSCREEN="INFO: .... $HOST $DEVNAME port nummber $PORT $PORT_DERSCRIPTION is OK @ $DATE"
# Check if port is UP
if [ "$CHKPORT" = "up" ]; then
echo -e "$HOST_PORT_UP_ALERTONSCREEN"
# Check if port isUP and its previous state was DOWN, then send UP sms/email
if [ $(grep -c "$HOST" "$HOST_PORT_STATUS") -eq 1 ]; then
echo "INFO: This port was previosuly DOWN, and now its UP ,Sending UP SMS 1 time only"
# Sending PORT DOWN ALERT via EMAIL
$SENDMAIL -u "$HOST_PORT_UP_ALERTONSCREEN" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$PORT_UP_MSG_HOLDER -o message-content-type=text
# Sending PORT DOWN ALERT via SMS using KANNEL SMS Gateway
cat $PORT_UP_MSG_HOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
sed -i "/$HOST/d" "$HOST_PORT_STATUS"
fi
fi
##################################
### CHECK PORT STATUS - for DOWN #
##################################
if [ "$CHKPORT" = "down" ]; then
echo "$HOST_PORT_DOWN_ALERTONSCREEN"
#check if port staus was previosly UP, then act
if [ $(grep -c "$HOST" "$HOST_PORT_STATUS") -eq 1 ]; then
echo "ALERT: ..... $HOST $DEVNAME port $PORT $PORT_DERSCRIPTION is DOWN. SMS have already been sent."
fi
if [ $(grep -c "$HOST" "$HOST_PORT_STATUS") -eq 0 ]; then
echo "ALERT: ..... $HOST $DEVNAME port $PORT $PORT_DERSCRIPTION is now down! - SENDING PORT DOWN SMS ..."
echo "$HOST" > $HOST_PORT_STATUS
echo "SMS Sent FOR $HOST $DEVNAME port $PORT $PORT_DERSCRIPTION DOWN have been sent only 1 time until next status change ..."
# Sending PORT DOWN ALERT via EMAIL
$SENDMAIL -u "$HOST_PORT_DOWN_ALERTONSCREEN" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$PORT_DOWN_MSG_HOLDER -o message-content-type=text
# Sending PORT UP ALERT via SMS
cat $PORT_DOWN_MSG_HOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
fi
fi
####################
# SCRIPT ENDS HERE #
# SYED JAHANZAIB #
####################

Usage:

change the IP and port number.

  • /temp/monitor_sw_port.sh 10.0.0.1 10610

You can add entry in cron like this

# Check for Service remote host port status
*/5 * * * * /temp/portmon.sh 10.0.0.1 10610

RESULT:

SMS result:
2019-01-17 10.05.47.jpgEmail Result:

email alert on port down vlan.PNG

# Monitoring Port # 10 , when port is DOWN ...

root@Radius:/temp# ./monitor_sw_port.sh 10.0.0.1 10610
- PING Result : OK
- SNMP Result : OK
ALERT: .... 10.0.0.1 WL_Main_Switch port nummber 10610 GigabitEthernet2/0/10 is DOWN @ Tue Jan 15 12:44:45 PKT 2019
ALERT: ..... 10.0.0.1 WL_Main_Switch port 10610 GigabitEthernet2/0/10 is DOWN. SMS have already been sent.

root@Radius:/temp# ./monitor_sw_port.sh 10.0.0.1 10610
- PING Result : OK
- SNMP Result : OK
ALERT: .... 10.0.0.1 WL_Main_Switch port nummber 10610 GigabitEthernet2/0/10 is DOWN @ Tue Jan 15 12:44:51 PKT 2019
ALERT: ..... 10.0.0.1 WL_Main_Switch port 10610 GigabitEthernet2/0/10 is DOWN. SMS have already been sent.

# Monitoring Port # 10 , when port is UP now ...
root@Radius:/temp# ./monitor_sw_port.sh 10.0.0.1 10610
- PING Result : OK
- SNMP Result : OK
INFO: .... 10.0.0.1 WL_Main_Switch port nummber 10610 GigabitEthernet2/0/10 is OK @ Tue Jan 15 12:45:01 PKT 2019
INFO: This port was previosuly DOWN, and now its UP ,Sending UP SMS 1 time only
Jan 15 12:45:11 radius sendEmail[18700]: Email was sent successfully!
0: Accepted for delivery

# Monitoring Port # 10 , when port is working UP ...
root@Radius:/temp# ./monitor_sw_port.sh 10.0.0.1 10610
- PING Result : OK
- SNMP Result : OK
INFO: .... 10.0.0.1 WL_Main_Switch port nummber 10610 GigabitEthernet2/0/10 is OK @ Tue Jan 15 12:45:12 PKT 2019

September 27, 2018

DNSMASQ Short Notes to self

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

dnsmasq.jpg

Dnsmasq is a lightweight, easy to configure DNS forwarder, designed to provide DNS (and optionally DHCP and TFTP) services to a small-scale network.

As compared to `​BIND`​, which is a bit complex to configure for beginners, `DNSMASQ` is very easy and requires minimum configuration. This post is just a reference guide for myself.


Install DNSMASQ in Ubuntu !

apt-get update
sudo apt-get install -y dnsmasq

After this edit /etc/dnsmasq.conf file ,  For Shorter version, I am pasting required important options only, (by removing all lines & using these one only …)

nano /etc/dnsmasq.conf

domain-needed
#IF you want to listen on multiple interface, add them (by duplicating following line)
interface=enp6s0
bogus-priv
strict-order
expand-hosts
cache-size=10000

After every change in the config, make sure to restart DNSMASQ service.

service dnsmasq restart


Forwarding Queries to Upstream DNS

By default, DNSMASQ forwards all requests which are not able to be resolved in /etc/hosts to the upstream DNS servers defined in /etc/resolve.conf like below

cat /etc/resolv.conf

nameserver 127.0.0.1
nameserver 8.8.8.8

Make Sure to setup 127.0.0.1 in your network adapter as well exampledns-nameservers 127.0.0.1 8.8.8.8



Add DNS Records (static dns entries if required for local servers like media sharing etc)

Adding customized domain entries, dns spoofing i guess. Add the records in /etc/hosts file

cat /etc/hosts

127.0.0.1 localhost
1.2.3.4 zaib.com

 


Restart DNSMASQ Service

After every change in the config, make sure to restart dnsmasq service.

service dnsmasq restart

Monitor DNS traffic

DSNTOP is your best friend. for full details read

http://dns.measurement-factory.com/tools/dnstop/dnstop.8.html


# ACL / Secure you DNS from open relay / flooding

To allow only specific ip series to query your dns server, you can use following bash script.

We have multiple ip pools, and we have made a small text file , we can small bash script to read from the file and add iptables rules accordingly

Sample of /temp/localips.txt

10.0.0.0/8
172.16.0.0/16
192.168.0.0/16

Now you can execute the bash script manually or add it in /etc/rc.local file to execute on every reboot.

cat /etc/fw.sh

#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Very Basic Level of Firewall to allow DNS only for some ip range
# Script by Syed Jahanzaib
# 26-SEP-2018
#set -x

# Setting various Variables

#Local IP files which contains ip/ranges
IPFILE="/temp/localips.txt"

#Destination Port we want to restrict
DPORT="53"

#Destination Port type we want to restrict
DPORT_TYPE1="udp"
DPORT_TYPE2="tcp"

# Flush all previous iptables Rules
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X

# Allow localhost access to query DNS service
iptables -A INPUT -s 127.0.0.1 -p $DPORT_TYPE1 --dport $DPORT -j ACCEPT
iptables -A INPUT -s 127.0.0.1 -p $DPORT_TYPE2 --dport $DPORT -j ACCEPT

# LOOP - Read from localip.txt file , and apply iptables rules
for IP in $(cat $IPFILE); do echo "Allowing $IP for $DPORT_TYPE1 $DPORT Server queries access ..."; iptables -A INPUT -s $IP -p $DPORT_TYPE1 --dport $DPORT -j ACCEPT; done
for IP in $(cat $IPFILE); do echo "Allowing $IP for $DPORT_TYPE2 $DPORT Server queries access ..."; iptables -A INPUT -s $IP -p $DPORT_TYPE2 --dport $DPORT -j ACCEPT; done

# DROP all other requests going to DNS service
iptables -A INPUT -p $DPORT_TYPE1 --dport $DPORT -j DROP
iptables -A INPUT -p $DPORT_TYPE1 --dport $DPORT -j DROP

# Script ends here
# Syed Jahanzaib

add this in /etc/rc.local so that it can run on every reboot!

Also note that if you have large ip pool, its better to use IPSET which is more efficient

SIMPLE QUEUE for traffic going to/from DNS Server

/queue simple
add max-limit=10M/10M name="NS1 DNS Traffic 10mb limit" target=X.X.X.X/32

NSLOOKUP with details on Windows BOX

nslookup -all - 8.8.8.8

Regard’s
Syed Jahanzaib

July 11, 2018

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.


 

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 — 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 vi /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 🙂


Regard’s
Syed Jahanzaib

March 8, 2018

Short Notes on LibreNMS !

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

libre dashboard

This post contains short notes & step by step guide on open source network omonitoring system called LIBRENMS , it is based on Php/MySQL/Snmp.


STEP BY STEP iNSTALLATION FOR LIBRENMS

OS: Ubuntu 16 (Server Edition/64bit)

First install required support packages

apt-get update
# Now install all the required components in a single GO ...
apt install -y apache2 composer fping git graphviz imagemagick libapache2-mod-php7.0 mariadb-client mariadb-server mtr-tiny nmap php7.0-cli php7.0-curl php7.0-gd php7.0-json php7.0-mcrypt php7.0-mysql php7.0-snmp php7.0-xml php7.0-zip python-memcache python-mysqldb rrdtool snmp snmpd whois curl acl
[select your php version and install it accordingly)
apt-get install php-mbstring
sudo apt-get install php7.0-mbstring
sudo apt-get install php7.1-mbstring
sudo apt-get install php7.2-mbstring

Add local user for librenms

useradd librenms -d /opt/librenms -M -r
usermod -a -G librenms www-data
systemctl restart mysql

Create user & DB

mysql -uroot -pzaib1234
CREATE DATABASE librenms CHARACTER SET utf8 COLLATE utf8_unicode_ci;
CREATE USER 'librenms'@'localhost' IDENTIFIED BY 'zaib1234';
GRANT ALL PRIVILEGES ON librenms.* TO 'librenms'@'localhost';
FLUSH PRIVILEGES;
exit

Now edit maria-db config file

nano /etc/mysql/mariadb.conf.d/50-server.cnf

& add following

[Within the [mysqld] section please add]

innodb_file_per_table=1
sql-mode=""
lower_case_table_names=0

& restart mysql
systemctl restart mysql
Save & Exit.

Web Server Config

Edit PHP files & setup TIMEZONEs

nano /etc/php/7.0/apache2/php.ini
nano /etc/php/7.0/cli/php.ini

Search for ‘date.timezone‘ & change it to

date.timezone = Asia/Karachi

Save & EXit.

Configure Apache

nano /etc/apache2/sites-available/librenms.conf

Add the following config,


DocumentRoot /opt/librenms/html/
ServerName  librenms.campusN.ws.nsrc.org
CustomLog /opt/librenms/logs/access_log combined
ErrorLog /opt/librenms/logs/error_log
AllowEncodedSlashes NoDecode

Require all granted
AllowOverride All
Options FollowSymLinks MultiViews


Save & Exit

a2dissite 000-default
a2ensite librenms.conf
a2enmod rewrite
systemctl restart apache2

Edit SNMPD Config file to enable SNMP on localhost

Now edit SNMPD config file and add our SNMP community string like public or other

nano /etc/snmp/snmpd.conf

Edit the text which says rocommunity public and set your own community string.
save and exit.

curl -o /usr/bin/distro https://raw.githubusercontent.com/librenms/librenms-agent/master/snmp/distro
chmod +x /usr/bin/distro
systemctl restart snmpd

Install LIBRE-NMS via composer command

cd /opt
composer create-project --no-dev --keep-vcs librenms/librenms librenms dev-master

Example:

1- install libre via cmd

CRONJOBS for librenms

cp /opt/librenms/librenms.nonroot.cron /etc/cron.d/librenms
cp /opt/librenms/misc/librenms.logrotate /etc/logrotate.d/librenms
chown -R librenms:librenms /opt/librenms
setfacl -d -m g::rwx /opt/librenms/rrd /opt/librenms/logs
setfacl -R -m g::rwx /opt/librenms/rrd /opt/librenms/logs

Start Configuration of LIBRENMS

cd /opt/librenms

cp config.php.default config.php

sudo chown -R librenms:librenms /opt/librenms

sudo setfacl -d -m g::rwx /opt/librenms/bootstrap/cache /opt/librenms/storage /opt/librenms/logs /opt/librenms/rrd

sudo chmod -R ug=rwX /opt/librenms/bootstrap/cache /opt/librenms/storage /opt/librenms/logs /opt/librenms/rrd

Now access libre-nms via browser …

http://yourip/install.php

& follow onscreen steps…

2- libre first step of gui

Make sure to add id password which is authorized to change DB , as required …

and click on FINISH on GUI.

Adding config.php

At one point, IF REQUIRED You may have to create the config.php manually as showed here.

nano /opt/librenms/config.php

& paste the data as showed in the config window.

<!--?php

## Have a look in includes/defaults.inc.php for examples of settings you can set here. DO NOT EDIT defaults.inc.php!

### Database config
$config['db_host'] = 'localhost';
$config['db_user'] = 'librenms';
$config['db_pass'] = 'zaib1234';
$config['db_name'] = 'librenms';

// This is the user LibreNMS will run as
//Please ensure this user is created and has the correct permissions to your install
$config['user'] = 'librenms';

### This should *only* be set if you want to *force* a particular hostname/port
### It will prevent the web interface being usable form any other hostname
$config['base_url'] = "/";

### Enable this to use rrdcached. Be sure rrd_dir is within the rrdcached dir
### and that your web server has permission to talk to rrdcached.
#$config['rrdcached'] = "unix:/var/run/rrdcached.sock";

### Default community
$config['snmp']['community'] = array('public');

### Authentication Model
$config['auth_mechanism'] = "mysql"; # default, other options: ldap, http-auth
#$config['http_auth_guest'] = "guest"; # remember to configure this user if you use http-auth

### List of RFC1918 networks to allow scanning-based discovery
#$config['nets'][] = "10.0.0.0/8";
#$config['nets'][] = "172.16.0.0/12";
#$config['nets'][] = "192.168.0.0/16";

# Uncomment the next line to disable daily updates
#$config['update'] = 0;

# Number in days of how long to keep old rrd files. 0 disables this feature
$config['rrd_purge'] = 0;

# Uncomment to submit callback stats via proxy
#$config['callback_proxy'] = "hostname:port";

# Set default port association mode for new devices (default: ifIndex)
#$config['default_port_association_mode'] = 'ifIndex';

# Enable the in-built billing extension
$config['enable_billing'] = 1;

# Enable the in-built services support (Nagios plugins)
$config['show_services'] = 1;

Save & Exit.

Add User if required

php adduser.php admin2  admin2 10 aacable@yourmail.com

librenms install done

 

Make sure to remove COMPOSER & set permissions when all is OK. Else it will give error in VALIDATION part.

chown -R librenms:librenms /opt/librenms
apt-get remove composer

 


Some more snaps

  • Add Device

 

add device

librenms add device with snmp

Devices Overview

device view

libre dashboard.JPG

February 26, 2018

Power of Open Source / Traffic Controlling with TC

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

speed meter

 

pwoerful pawn

Living in the Dark & Playing  & with the Open Source is Fun & Amazingly Powerful ! z@iB


Scenario:

We have few Linux base FTP/HTTP base media file sharing server setup. User can access these server by bypassing the router as we donot want to put load on the router itself & user should access these servers from switch level by intervlan routing setup.

Problem:

Since the FTP data is in many terabytes and hundreds of users are accessing it, this is creating bottleneck for server’s network/storage.

Solution:

On Linux we can use TRAFFIC CONTROLLER (TC) to limit bandwidth on per user IP basis.  We will create a simple bash script which will do the following in sequence …

  • FTP Server IP: 101.11.11.254
  • Clear any existing shaping rules
  • Create 4 bandwidth packages as following
    – 1024kbps  [for General Users subnet 101.11.11.0/24]
    – 2048kbps  [for Support Staff  subnet 101.11.50.0/24]
    – 512kbps     [for ICMP, so that ping should work fine , Protocol base]
    – 128kbps    [for any unknown IP series, that is no define above, for ALL 0.0.0.0/0.0.0.0]
  • Assign ip subnet to these packages (/24 and it will create per ip base rules via LOOP statement)
  • In this example, we are limiting Bandwidth in one way only, means packets sending from server to client will be applied limitation .. For both ways just duplicate rules and use src as well.

Create , the script!

mkdir /temp
touch /temp/shaper.sh
chmod +x /temp/shaper.sh

Now Edit

nano /temp/shaper.sh

& paste following,

#!/bin/bash
# Traffic Shaping Using `TC` in Linux / This was made for specific requirements.
# ITs customzied designed to fulfill some specific requirements & it went well.
# Following Script will limit outgoing bandwidth for specific ip range series.
# It will also allow ICMP more bandwidth so that ping to local server may not delay or imtout.
# It will then limit all other ips that are not listed to minimum bandwidth that is 128kbps.
# Adjust is as per your requirements.
# Syed Jahanzaib / aacable @ hotmail . com / https://aacable.wordpress.com :~)
# 23-Febraury-2018

# Enable following to see debug
# set -x

# Local Network Interface name
INT="ens33"
INT_SPEED="100Mbit"

# First IP Range & its package with class
IP1="101.11.11"
IP1_PKG="1mbit"
IP1_CLASSID="1:10"

# Second IP Range & its package with class
IP2="101.11.50"
IP2_PKG="2mbit"
IP2_CLASSID="1:20"

# Separate Bandwidth for ICMP protocol to minimze delay in PING/ICMP packets
ICMP_PKG="512kbit"
ICMP_CLASSID="1:200"

# Other Default Package Line, means all other unmarked IP's or traffic
UNKNOWN_PKG="128kbit"
UNKNOWN_CLASSID="1:201"

if [[ "$1" != "start" && "$1" != "stop" && "$1" != "status" ]]; then
echo "Usage:

./shaper.sh start
./shaper stop
./shaper status

by Jz!"
exit 1
fi

if [ $1 == "stop" ]; then
echo "Clearing all existing Queues on user request ...

Done!"
tc qdisc del dev $INT root 2> /dev/null > /dev/null
exit 1
fi

if [ $1 == "status" ]; then
echo "Showing Current TC Class and Filter Status
=========================================="
tc class show dev $INT
echo "

"
tc -s -d class show dev $INT
echo "=========================================="

exit 1
fi

if [ $1 == "start" ]; then
echo "Starting Shaper ...
Clearing all existing Queues for re-implementation ...
=========================================="
"

# clean existing down- and uplink qdiscs, hide errors
tc qdisc del dev $INT root 2> /dev/null > /dev/null

echo "
Adding Queues ...."
# Create egress shaping for all required classes
tc qdisc add dev $INT root handle 1: htb default 20 r2q 50
tc class add dev $INT parent 1: classid 1:1 htb rate $INT_SPEED ceil $INT_SPEED
tc class add dev $INT parent 1:1 classid $IP2_CLASSID htb rate $IP1_PKG ceil $IP1_PKG prio 100
tc class add dev $INT parent 1:1 classid $IP1_CLASSID htb rate $IP2_PKG ceil $IP2_PKG prio 100
tc class add dev $INT parent 1:1 classid $ICMP_CLASSID htb rate $ICMP_PKG ceil $ICMP_PKG prio 100
tc class add dev $INT parent 1:1 classid $UNKNOWN_CLASSID htb rate $UNKNOWN_PKG ceil $UNKNOWN_PKG prio 100

# ICMP reply Adjustment so ping may not timeout or high delay may not occur at client end for this server local IP
tc filter add dev $INT parent 1: protocol ip prio 100 u32 match ip protocol 1 0xff flowid $ICMP_CLASSID

# IP-1 series limitation applies here ...
for (( i = 1 ; i <= 255; i++ ))
do
b=$i
tc filter add dev $INT parent 1: protocol ip prio 100 u32 match ip dst $IP1.$i flowid $IP1_CLASSID
done

# IP-2 series limitation applies here ...
for (( i = 1 ; i <= 255; i++ ))
do
b=$i
tc filter add dev $INT parent 1: protocol ip prio 100 u32 match ip dst $IP2.$i flowid $IP2_CLASSID
done

# Send every unknown IP to classid UNKNOWN_CLASS that is lowest. so that any IP that is not listed above will get htis lowest bandwidth
tc filter add dev $INT parent 1: protocol ip prio 100 u32 match ip dst 0.0.0.0/0.0.0.0 flowid $UNKNOWN_CLASSID

echo "
Done!"
fi

Result:

linux TC down-result.jpg

 

Older Posts »

%d bloggers like this: