Syed Jahanzaib Personal Blog to Share Knowledge !

August 23, 2013

Short References / Notes For UBUNTU / Mysql and Squid

♥♥♥   My Love Is For Ubuntu   ♥♥♥


Syed Jahanzaib

These are short notes , my findings, some commands as reference , I find from time to time … it will continue in general as long as I am breathing on the planet Earth …!

Repeat command using LOOP in terminal

while true; do YOURCOMMAND; sleep 5; done

Find and Delete ZERO SIZE FILES

(in folder name /var/log/mikrotik)

find /var/log/mikrotik/ -name 'mikrotik*' -size 0 -print0 | xargs -0 rm

MYSQL SERVICE & DB Check by bash

# 20-Jun-2016
# Syed Jahanzaib
# aacable at hotmail dot com
#set -x
# Check if $SRV (in this case mysql) is running or not, if NOT, then exit the script
SRVSTATUS=$(pgrep $SRV | wc -l);
if [ "$SRVSTATUS" -ne 1 ];
echo "-$SRV is down. Pleasec check your $srv service first.
Exiting ...";
exit 1
echo "-$SRV is accessible OK. Proceeding further ..."

# Check if $DB (in this case radius ) is accessible or not, if NOT, then exit the script
RESULT=`mysql -u $SQLUSER -p$SQLPASS --skip-column-names -e "SHOW DATABASES LIKE '$DB'"`
if [ "$RESULT" == "$DB" ]; then
echo "-$DB database exist OK. Proceeding further ..."
echo "-$DB database does not exist!"
exit 1


In Bash you quite often need to check to see if a variable has been set or has a value other than an empty string. This can be done using the -n or -z string comparison operators.

The -n operator checks whether the string is not null. Effectively, this will return true for every case except where the string contains no characters. ie:

if [ -n "$VAR" ]; then
echo "VAR is not empty"

Similarly, the -z operator checks whether the string is null. ie:

if [ -z "$VAR" ]; then
echo "VAR is empty"

Note the spaces

Date Time Functions

TODAY=$(date +”%Y-%m-%d”)
TODAYDIGIT=`echo $TODAY  | sed -e ‘s/-//g’`
MONTH=$(date +”-%m”)
CMONTH=`echo $MONTH  | sed -e ‘s/-//g’`
MONTHYEAR=$(date +”%B-%Y”)
ALPHAMONTHYEAR=`echo $MONTHYEAR #| sed -e ‘s/-//g’`
ONEMONTHBACK=$(date +%Y-%m-%d  -d “1 months ago”)

Using SED to remove empty lines from a file

sed -i '/^\s*$/d' /temp/

Using SED to remove brackets in line/file

to remove bracket from text
like we want to remove brackets from following


echo '[test]' | sed 's/\(\[\|\]\)//g'


cat /tmp/test.txt | awk '{print $2}' | sed 's/\(\[\|\]\)//g' | sed 's#/#\ #g'

Using SED to remove word with special characters.

Remove word with special characters in file by cat and sed

Example: Contents of file name file.txt are


and now we want to remove /temp/ word only. here how to do it.

cat file.txt | sed -e 's/\/temp\///'

Add User in Ubuntu and grant SUDO (admin rights)

sudo useradd -m -p zaib1234 zaib
sudo useradd zaib sudo


 Installing phpmyadmin

 sudo apt-get install phpmyadmin apache2-utils


Howto Enable MYSQL remote connectivity

Connect to mysql shell and issue issue these commands



and on new version of mysql  use

GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY 'root';


Also From /etc/mysql/my.cnf

Comment this line:

#bind-address  =

Then run

service mysql restart


How to reset USB device like usb modem without PLUG/UNPLUG physically

The following script will help you in resetting USB device (without physically unplug/plug). It was very useful for me in one case where server was remotely located and no one was physically present there to plug/unplug DLINK USB GSM modem which hangs frequently. So as a short term solution i created an script which first check for USB BUS, then using usbreset it simply reset that usb device. I scheduled it on hourly basis and it worked very good.

USBBUS1=`lsusb | grep D-Link | awk '{print $2}'`
USBBUS2=`lsusb | grep D-Link | awk '{print $4}' |  sed 's/://'`

echo -e "USB Bus1 = $USBBUS1"
echo -e "USB Bus2 = $USBBUS2"

/temp/usbreset /dev/bus/usb/$USBBUS1/$USBBUS2

# Playsmsd restart so that if its in stuck position it should come ALIVE again ; ) : ) zaib
echo playsmsd restart | at now + 1 min

You can create usbreset program from following this url.

OR another link which I have not tested so far..



How to run script every x minute via CRON Job

Edit cron jobs by

crontab -e

then add your script by using

# To run script every one minute
* * * * * /path/

# To run script after FIVE minutes [Example MRTG command with logs]
*/5 * * * *  /etc/

# OR [Example MRTG command with logs]
*/5 * * * * env LANG=C mrtg /etc/mrtg.cfg --logging /var/log/mrtg.log

# Run Script at at 5:00pm Daily
00 17 * * * /temp/

# Run in night at 00:00 hours to send notifications to users whose account have been expired today.
@daily /temp/

# Run Script after every hour
@daily /temp/

# Run script on reboot
@reboot /temp/

How to set Date/Time via CLI on Ubuntu / Linux

If you want to set date and time on Ubuntu box via command/CLI and sync to hardware Bios. use following

sudo date --set="3 OCT 2014 15:54:00"
sudo hwclock --systohc --utc


How to configure / add IP address in UBUNTU via CLI / Command

Sometimes it is required to configure interface card by CLI (command line interface) , for example if you are doing any configuration on remote server via putty, and you want to configure another interface on that server, OR if you are using server edition of ubuntu which dont have GUI, then you will have to do it via CLI.

Configuring a static IP from the command line is a very short task. All you need to edit is one configuration file and restart the networking service.
All you need to know is the settings for your network.

I will show how to set a static IP of <strong></strong> on a network with a gateway and dns of <strong></strong>

Open the configuration file in your favorite editor (mine is nano)

Open terminal and type the following command:

nano /etc/network/interfaces

Remove previous entries for your ethernet (for example eth0 section only)
Add a section as showed in the following example:

# Adding static ip for eth0 / Syed jahanzaib
auto eth0
iface eth0 inet static
network # You can disable this line
broadcast # You can disable this line
gateway # You can disable this if you dont have any gateway - or if its a test lab rat :p

Save & Exit the file.
Now Restart the network service

/etc/init.d/networking restart

You can now verify your new ip by

ifconfig eth0



sudo ifconfig eth0 down
sudo ifconfig eth0 hw ether 00:12:34:BL:AA:AH
sudo ifconfig eth0 up
# if apache is running, dont forget to restart it so it can take new mac, useful in some scenarios
# service apache2 restart



find&nbsp;/path/to/files* -mtime +5 -exec rm {} \;


To Clear Linux Console History

history -c
history -w

First command clears the history, and the second writes the now (empty) history file.


Find what application/process is using the port


sudo netstat -lpn |grep :8080

and press Enter.

You will get an output similar to this one

tcp6       0      0 :::8080                 :::*                    LISTEN      6782/java

I have got the process Id, which is 6782, now this is the process that is using port 8080.

Kill the process, type:

kill 6782
fuser -n tcp 8080

lsof -w -n -i tcp:8080

netstat | grep 8080

$ sudo -i
$ netstat -tulpn


PHP prompts to save file in Apache2

If you open any php file hosted on your linux base system, and it give syou option to OPEN/SAVE rather then displaying content, then install following

sudo apt-get install libapache2-mod-php5
sudo a2enmod php5
sudo /etc/init.d/apache2 restart


Test USB port functionality

root@radius:~# cat /temp/
## Search for a working USB port (/dev/ttyUSB)

for port in /dev/ttyUSB*
[[ -e $port ]] || continue
gcom -d $port info &amp;&gt; /tmp/testusb
testUSB=`cat /tmp/testusb | grep "Error\|Can't"`
if [ -z "$testUSB" ]; then
rm -rf /tmp/testusb

if [ $work != false ]; then
echo "$work is working!"
echo 'Not found a working USB port'


To restart Networking , issue the following command.

To restart Networking services to apply changes you made with your interfaces , issue the following command.

/etc/init.d/networking stop
/etc/init.d/networking start


/etc/init.d/networking restart

OR some other commands for the same

sudo initctl restart network-manager
sudo initctl restart network-interface INTERFACE=eth0


sudo ifconfig eth0 down
sudo ifconfig eth0 up

Static Route lost when ethernet cable unplug/plug [8th-MAR-2016] for UBUNTU 12.x

It is observed that if you have made static route in ubuntu 12.x, they get lost when ethernet cable unplug/plug. to make the persistent on boot/unplug+plug situation, use following.

# The primary network interface

auto eth1

iface eth1 inet static




#ROUTE 1 static

up route add -net gw dev eth1

#ROUTE 2 static

up route add -net gw dev eth1


Howto to ADD / DELETE Route

Adding default Gateway

route add default gw dev eth1

Deleting all default Gateways

ip route del default

Add Route for Local Network using Gateway

route add -net netmask gw dev eth0

Delete Route …

route del -net netmask gw dev eth0


Ubuntu / Debian Linux: Services Configuration Tool to Start / Stop System Services

apt-get install sysv-rc-conf

then run sysv-rc-conf


Howto disable ipv6 in ubuntu.  [12.4]

First edit sysctl.conf file in any editor , e.g:

nano /etc/sysctl.conf

and add following lines in the end

# IPv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1


use following to add them directly to file using echo command

echo &gt;&gt; /etc/sysctl.conf&nbsp; net.ipv6.conf.all.disable_ipv6 = 1
echo &gt;&gt; /etc/sysctl.conf&nbsp;net.ipv6.conf.default.disable_ipv6 = 1
echo &gt;&gt; /etc/sysctl.conf&nbsp;net.ipv6.conf.lo.disable_ipv6 = 1

Save and Exit and execute following to activate changes 🙂

sysctl -p


HOWTO change default text EDITOR in CLI useful for Ubuntu 13 crontab)

export EDITOR=/usr/bin/nano



I assumed that you have installed and configure your Linux box (preferably Ubuntu, but any flavor can do the job, this is the main quality of Linux OS 🙂 ~
To install Webmin , first add its repositories to sources.list, to do this first open sources.list

nano /etc/apt/sources.list

Now paste the following lines in the end of this file.

deb sarge contrib
deb sarge contrib
deb lucid partner

Save & Exit.

OR add them via echo command

echo &gt;&gt; /etc/apt/sources.list deb sarge contrib
echo &gt;&gt; /etc/apt/sources.list deb sarge contrib
echo &gt;&gt; /etc/apt/sources.list deb lucid partner

Save & Exit.

Now update apt-get and install webmin using

apt-get update
apt-get install webmin

It will take some time to install webmin depend on your internet connection (usually less then 10 minutes) , afterward you can access it using


(TIP: you can change the webmin port by editing in /etc/webmin/miniserv.conf and change the port number to any port you like, for example 443 or 1234)



To view IPTABLES rules, use following

iptables -L
iptables -t nat -L


To clear all iptables rules, use following

iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X


To Block Ip RANGE from accessing your linux box (in INPUT chain)

iptables -A INPUT -m iprange --src-range -p tcp --dport 8080 -j DROP

To Block Single Ip from accessing your linux box (in INPUT chain)

iptables -A INPUT --src -j DROP

To Block Single Ip from accessing SSH port 22 of your linux box (in INPUT chain)

iptables -A INPUT --src -p tcp --dport 22 -j DROP

To Block all users from accessing SSH port 22 of your linux box (in INPUT chain)

iptables -A INPUT -p tcp --dport 22 -j DROP

DNAT port 80 request coming from LAN systems to squid 8080 ($SQUID_PORT) , This is to make your squid as transparent proxy

iptables -t nat -A PREROUTING -i LAN_Interface -p tcp --dport 80 -j DNAT --to SQUID_IP:PORT



To Delete single iptables rule via number or name

iptables -vnL –line-numbers
iptables -L INPUT –line-numbers
iptables -D INPUT 4


Using Putty from Shortcut to login to remote linux server without password [Jz]

To login to remote Linux server using PUTTY with out password, you can use public keys or quick way is to use shortcut trick. Not recommended if your system is not secure or used by other people,
For example:

C:\temp\putty.exe -ssh root@ -pw yourpassword

TIP: Change the C:\temp to match your folder where putty.exe is available.

To login from Mikrotik to linux and Linux to Linux, read the below . . .


Bandwidth Monitoring tool for Ethernet Interface [Jz]

There are plenty of tools to do the task, I found bwm-ng the quickest 🙂
To install it on DEBIAN/UBUNTU , use

apt-get install bwm-ng

To install it on FEDORA / CENTOS, use

yum -y install bwm-ng

To run it , type


Use following shortcut to tune bwm-ng

Press + to set time interval, default is set to 0.5 seconds which is too short, make it at least 1.00 or 1.1 to get mroe stable value.

Press u to get DATA in kb (kilobits), default is set to KB (Kilo Bytes)

To see data of eth0, with kilobits, and 1 second refresh rate , use following . . .

bwm-ng +I eth0 -u bits -t 1000


SQUID LOGS & Others[Jz]

To view SQUID access logs for all users, use

tail -f /var/log/squid/access.log

To view SQUID access logs for CACHE HIT

tail -f /var/log/squid/access.log |grep HIT

To view SQUID access logs for specific user ip, use

tail -f /var/log/squid/access.log |grep

To view SQUID process

ps aux |grep squid
ps aux |grep # if you have url rewrite program configured like for youtube caching

Start SQUID in diagnostic mode (no daemon mode)

If you have some problems in your squid config and its not starting, then start squid in debug mode,
use following command

squid -d1N

it will start in no daemon mode and will show you details and errors if any.


Add in squid.conf and reload squid

acl fb dstdomain
http_access deny CONNECT fb all
acl badsites dstdomain
acl badsites dstdomain
acl badsites dstdomain
http_access deny fb

Howto block User IP or series in SQUID ACL

If you want to block specific IP series in SQUID via ACL and want to redirect it to a local page (useful for non payment reminder) use following

#Allow Web Server access where our ad page is hosted , it can be local or remote whatever you like : p
acl allow_web_server dst
http_access allow allow_web_server

# Create ACL to block EXPIRED USERS pool and redirect it to advertisement page
acl expired_clients src
http_access deny expired_clients
deny_info expired_clients



Following script [] will check SQUID service status , and if it found squid stop, it will start it auto, if the squid is already running , it will do nothing :)

First create file in any folder or temp folder by

mkdir /temp
touch /temp/
chmod +x&nbsp; /temp/

Now edit this file

nano /temp/

& paste the following code

pid=`pidof $1`
if [ $pid == ]; then
echo $1 service is NOT running, Trying to start again . . .
service $1 start
echo $1 service is Running OK , no further action required, EXITING&nbsp; . . .


Save & Exit.

Test it by running

/temp/ squid

You can check any service status with above command, if the service is not running , it will try to start with.

You can create its cron entry to run it after every 5 minutes.

For example, add it using CRON by following

crontab -e

and add following line

*/5 * * * * /temp/



To view Disk information

df -h

To view free memory

# in Megabytes

free -m

# in Gigabytes

free -g

To view Linux Release and architecture

lsb-release -a

You will something like below

root@server:~# lsb_release -a
Distributor ID: Ubuntu
Description:    Ubuntu 10.04.4
LTSRelease:        10.04
Codename:       lucid

To view Linux Architecture if its 32bit (x86) or 64bit

uname -a

root@server:~# uname -a
Linux server 2.6.32-50-server #112-Ubuntu SMP Tue Jul 9 20:45:08 UTC 2013 x86_64 GNU/Linux

x86_64 shows that the architecture is 64 bit

if you see something i386 , or i686 ,  it means you have 32 bit version.


To view CPU support

cat /proc/cpuinfo

and look for flag “lm” in the flags: column. If it’s there then it’s 64bit CPU.



To empty any file contents, For example if you want to clear all the contents in the squid.conf file , so that you can start with new, use following

cat /dev/null /etc/squid/squid.conf


One way to do this is to use awk.

awk '{ printf YOURTEXT; print }'&nbsp; CURRENT_FILENAME&nbsp; &amp;gt; OUTPUT_FILENAME

If you want to modify the file in place, you can use sed with the -i switch.

sed -i -e 's_.*_YOURTEXT;_'&nbsp; CURRENT_FILENAME


Adding PROXY for command line programs like WGET [Jz]



To test if SQUID service is not responding to requests, and restart ,


http_proxy= /wget -O /dev/null || squid -k reload


Mount USB in Ubuntu Server (12.x or any)

You can either install “usb-mount”, or mount it manually
Get the information (what is the device, e.g. /dev/sdb1):

fdisk -l

Create any foldeer where you will mount your USB, like in /usb

mkdir /usb

Mount the USB drive:

mount -t ntfs /dev/sdb1 /usb

-t is the filesystem type. Most flash drives are NTFS formatted if used on windows, or FAT32 (vfat).

To Unmount the drive:


umount /dev/sdb1
umount /usb


Mysql Related Commands

Following are few MYSQL related stuff for personnel reference.

To print RM Managers from DB

use radius;
show tables;
select * from rm_managers limit 0 , 30;

to execute commands in mysql terminal

go&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (\g) Send command to mysql server.
exit&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (\q) Exit mysql. Same as quit.

To search from table (for online radius users)

SELECT * FROM radacct WHERE acctstoptime IS NULL;

To search from table with specific condition matched;

SELECT username, owner from rm_users where username='zaib' AND owner='admin';

To view MYSQL command history

cat ~/.mysql_history

Create DB in mysql

create database test;
create user 'zaib'@'localhost' identified by 'zaib';
grant all on test.* to zaib@localhost;


mysql&gt; create database test;
Query OK, 1 row affected (0.00 sec)

mysql&gt; create user 'zaib'@'localhost' identified by 'zaib';
Query OK, 0 rows affected (0.00 sec)

mysql&gt; grant all on test.* to zaib@localhost;
Query OK, 0 rows affected (0.00 sec)

Adding Virtual NIC in ubuntu

To add virutal nic in ubuntu, issue this command you can also add these commands in startup as well.

ip link add link eth0 address 11:22:33:44:55:66 eth0.1 type macvlan

ifconfig eth0.1 up

ifconfig eth0.1

Change MYSQL old ROOT password

mysql -u root -pOLDPASSWORD
use mysql;
update user set password=PASSWORD('NEW-PASSWORD') where User='root';
flush privileges;


use mysql;
SET PASSWORD FOR 'conntrack'@'localhost' = PASSWORD('NEW-PASSWORD');

#Then change password in radius manager related Files for user 'radius'


Change the password to new password in above files.

Howto install ‘sendemail’ tool to send email via Gmail ID.

Very Well with Tested For UBUNTU 12.4 / 32bit …

Quick copy paste …

apt-get -y install libio-socket-ssl-perl libnet-ssleay-perl perl


tar zxvf sendEmail-v1.56.tar.gz

cd sendEmail-v1.56/

To test email use following command, make sure to change the GMAIL ID and password.

# To send simple email

/temp/sendEmail-v1.56/sendEmail -u "Test Email - subject" -o tls=yes -s -t -xu -xp GMAIL-PASS&nbsp;-f &nbsp; -o -o message-content-type=text -m "this is meail body - zaib"

# To send simple email with file attached
/temp/sendEmail-v1.56/sendEmail -u "Test Email - subject" -o tls=yes -s -t -xu -xp GMAIL-PASS&nbsp;-f -o -o message-content-type=text -m "this is meail body - zaib" -o message-file=/temp/test.txt -o message-content

Mount Remote Windows Share in local /mnt/win folder

If we want to mount remote windows shared folder in local /mnt/win folder, the follow below  commands…

sudo apt-get install cifs-utils

#Make WIN folder under/mnt

mkdir /mnt/win

#mount remote windows shared folder using

mount -t cifs -o uid=1000,gid=1000,username=ADMINISTRATOR_ID,password=MY_PASSWORD //REMOTE_SERVER_IP_OR_NAME/FOLDER /mnt/win/


Execute Powershell command on remote windows

winexe -U DOMAIN/ID%'PASS' //IP_OR_NAME 'powershell.exe -inputformat none -command "c:\script\powershell_script_name.ps1 "'

Syed Jahanzaib



  1. Dear SJ

    can i know is it possible to chose another Directory for Chache on Another Drive.

    Becuase in your Tutorial we are creating Cache directory in Filesystem of ubuntu. but i have added another Drive of 1 TB just for Squid Cache.

    then how can we define such directory so that all cache contents saved in 2nd HArd Drive


    Comment by Maria — June 12, 2014 @ 1:00 PM

  2. Sir………………this script “check squid” is not working on Squid 2.7 st-9

    pid=`pidof $1`
    if [ $pid == ]; then
    echo $1 service is NOT running, Trying to start again . . .
    service $1 start
    echo $1 service is Running OK , no further action required, EXITING . . .

    plz sir update about this script …..ALLAH aap ko Jaza e Khair de…..


    Comment by Salman — December 27, 2014 @ 7:11 AM

  3. […] sendEmail tool to send email [you can use some other methods as well] […]


    Pingback by Acquiring Cisco Switch Customized Report via Sms/Email | Syed Jahanzaib Personal Blog to Share Knowledge ! — January 28, 2017 @ 10:02 AM

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: