Screen script for multi-user session or reminding you to create a screen on logon

A common problem when many people share large systems as the same user ( I know .. I know but anyways move on )  is that when you logon you might want to take over where someone else left off. Also sometimes you want to share a session with someone for supervision or just team experience.

Screen tool in linux is fantastic for this. I wrote this script to allow people to be reminded to have a screen session and if already there allow you to log on to the screen by either taking over the session or sharing it with the other user.

installation of screen is as easy as :

 

sudo yum install screen -y

or for you debbie penguins out there

 

sudo apt-get install screen -y

 

The script goes like this :

## Screen profile for user session sharing
## by David Saliba (copyleft) 2013 

#!/bin/bash

function greet {
 clear
 cat /etc/motd
 echo "Hostname:" `hostname `
 echo
 ifconfig | grep inet | egrep -v "inet6|localhost|127\.0\.0\.1"
 echo
 #  df -h /
 echo "Welcome ! #  No screen session  #"   
}

function newscreen {

 echo "Would you like to create a new session  ? (Y/n)"

  read -t 10 b
  if [[ $b == "N" || $b == "n" ]]; then
 { # Dummy if no just continue
  echo 
 }
 else
 {
  
  echo " Remember to use <CTRL> + A and then d to leave the screen session active or just disconnect "
  echo -n "Creating "
         sleep 1; echo -n "." ;sleep 1; echo -n "."; sleep 1; echo -n "."
  exec screen -S Workarea
 }
 fi
}

if [ -z "$STY" ]; then
 firstscreen=$(screen -list | grep "(" | cut -f 2 | head -n 1)
# echo $firstscreen

 if [ ! -z "$firstscreen" ]; then
 {
         echo "Found screen ($firstscreen).Do you want to jump on it (Y), or share the session (X)? (Default Y in 10s)"
         read -t 10 a
     if [[ $a == "N" || $a == "n" ]]; then
        {
         greet
        }
     elif [[ $a == "X" || $a == "x" ]]; then
        {
         echo -n "Joining "
         sleep 1; echo -n "." ;sleep 1; echo -n ".";
         exec screen -x $firstscreen
        }
     else
        {
         echo -n "Connecting and taking over"
         sleep 1; echo -n "." ;sleep 1; echo -n ".";
         exec screen -r -d $firstscreen
        }
     fi
 }
 else
 {
   greet   str3amuK
   newscreen
 }
 fi
fi

 

Save this script under /etc/profile.d/screen.sh or some other name you will recognize.

 

Bash While Loop Example

How do I use bash while loop to repeat certain task under Linux / UNIX operating system? How do I set infinite loops using while statement? The bash while loop is a control flow statement that allows code or commands to be executed repeatedly based on a given condition. For example, run echo command 5 times or read text file line by line or evaluate the options passed on the command line for a script.

bash while loop syntax

The syntax is as follows:

while [ condition ]
do
   command1
   command2
   command3
done

command1 to command3 will be executed repeatedly till condition is true. The argument for a while loop can be any boolean expression. Infinite loops occur when the conditional never evaluates to false. For example following while loop will print welcome 5 times on screen:

#!/bin/bash
x=1
while [ $x -le 5 ]
do
  echo "Welcome $x times"
  x=$(( $x + 1 ))
done

Here is a sample shell code to calculate factorial using while loop:

#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
   factorial=$(( $factorial * $counter ))
   counter=$(( $counter - 1 ))
done
echo $factorial

To run just type: $ chmod +x script.sh $ ./script.sh 5 Output:

120

While loops are frequently used for reading data line by line from file:

#!/bin/bash
FILE=$1
# read $FILE using the file descriptors
exec 3<&0
exec 0<$FILE
while read line
do
	# use $line variable to process line
	echo $line
done
exec 0<&3

You can easily evaluate the options passed on the command line for a script using while loop:

......
..
while getopts ae:f:hd:s:qx: option
do
        case "${option}"
        in
                a) ALARM="TRUE";;
                e) ADMIN=${OPTARG};;
                d) DOMAIN=${OPTARG};;
                f) SERVERFILE=$OPTARG;;
                s) WHOIS_SERVER=$OPTARG;;
                q) QUIET="TRUE";;
                x) WARNDAYS=$OPTARG;;
                \?) usage
                    exit 1;;
        esac
done
.......
..

How do I use while as infinite loops?

Infinite for while can be created with empty expressions, such as:

#!/bin/bash
while :
do
	echo "infinite loops [ hit CTRL+C to stop]"
done

Conditional while loop exit with break statement

You can do early exit with the break statement inside the whil loop. You can exit from within a WHILE using break. General break statement inside the while loop is as follows:

while [ condition ]
do
   statements1      #Executed as long as condition is true and/or, up to a disaster-condition if any.
   statements2
  if (disaster-condition)
  then
	break       	   #Abandon the while lopp.
  fi
  statements3          #While good and, no disaster-condition.
done

In this example, the break statement will skip the while loop when user enters -1, otherwise it will keep adding two numbers:

#!/bin/bash

while :
do
	read -p "Enter two numnbers ( - 1 to quit ) : " a b
	if [ $a -eq -1 ]
	then
		break
	fi
	ans=$(( a + b ))
	echo $ans
done

Early continuation with the continue statement

To resume the next iteration of the enclosing WHILE loop use the continue statement as follows:

while [ condition ]
do
  statements1      #Executed as long as condition is true and/or, up to a disaster-condition if any.
  statements2
  if (condition)
  then
	continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done

 

How to recognize the hardware platform you are running on.

It is sometimes required especially when managing many servers to recognize the hardware setup you are running on especially if you have a zoo of different animals. 

Great tool for getting detailed hardware report including bios versions and memory / processor info :

 

dmidecode

While the output varies slightly across distros and sometimes you need to install it e.g.

 yum -y install dmidecode

It is a great tool for understanding the underlying system and to know if you’re on a VM or not.

 

nJoy 😉

Installing Bacula Client on Centos

So the story goes like this :

 

wget http://sourceforge.net/projects/bacula/files/latest/download?source=files

 

tar zxvf bacula-*.tar.gz

cd bacula-<fiolder>

./configure –enable-client-only

make
make install
make install-autostart-fd

 

 

 

nJoy 😉

Reset Mysql password from bash prompt

You can recover MySQL database server password with following five easy steps.

Step # 1: Stop the MySQL server process.

Step # 2: Start the MySQL (mysqld) server/daemon process with the –skip-grant-tables option so that it will not prompt for password.

Step # 3: Connect to mysql server as the root user.

Step # 4: Setup new mysql root account password i.e. reset mysql password.

Step # 5: Exit and restart the MySQL server.

Here are commands you need to type for each step (login as the root user):

Step # 1 : Stop mysql service

# /etc/init.d/mysql stop
Output:

Stopping MySQL database server: mysqld.

Step # 2: Start to MySQL server w/o password:

# mysqld_safe --skip-grant-tables &
Output:

[1] 5988
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[6025]: started

Step # 3: Connect to mysql server using mysql client:

# mysql -u root
Output:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

Step # 4: Setup new MySQL root user password

mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

Step # 5: Stop MySQL Server:

# /etc/init.d/mysql stop
Output:

Stopping MySQL database server: mysqld
STOPPING server from pid file /var/run/mysqld/mysqld.pid
mysqld_safe[6186]: ended
[1]+  Done                    mysqld_safe --skip-grant-tables

Step # 6: Start MySQL server and test it

# /etc/init.d/mysql start
# mysql -u root -p

 

Voila !

 

nJoy  😉

Setting a route for a nic in Linux

In file named after the interface you want to use as gateway:

e.g. /etc/sysconfig/network-scripts/route-eth0

 

Create entries :

 

ADDRESS=192.168.4.0
NETMASK=255.255.255.0
GATEWAY=192.168.1.250

NnJoy 🙂

Limiting access iptables

This is a Script that I use to deploy and script iptables.

Sample handles ssh and mysql it’s easy to extend.

#!/bin/bash
#
# iptables example configuration script
#
# Flush all current rules from iptables
#
 iptables -F
#
# Allow SSH connections on tcp port 22
# This is essential when working on remote servers via SSH to prevent locking yourself out of the system
#
# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# SSH  rules
iptables -A INPUT -i eth0 -p tcp -s 193.50.90.251 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp -s 212.164.176.98 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT

iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT


# mysql rules
iptables -A INPUT -i eth0 -p tcp -s 193.50.90.251 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp -s 212.164.176.98 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
#Allow frontend 1
iptables -A INPUT -i eth0 -p tcp -s 191.94.70.36 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
#Allow Frontend 2
iptables -A INPUT -i eth0 -p tcp -s 191.94.70.38 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT

iptables -A OUTPUT -o eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT




#
# Set default policies for INPUT, FORWARD and OUTPUT chains
#
 iptables -P INPUT DROP
 iptables -P FORWARD DROP
 iptables -P OUTPUT ACCEPT
#
# Set access for localhost
#
 iptables -A INPUT -i lo -j ACCEPT
#
# Accept packets belonging to established and related connections
#
 iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#
# Save settings
#
 /sbin/service iptables save
#
# List rules
#
 iptables -L -v

nJoy 🙂