Showing posts with label bash script. Show all posts
Showing posts with label bash script. Show all posts

Wednesday, 8 June 2016

How to generate GPG Key?

Prerequisites

packages to be installed

  1. rngd
  2. gpgv OR gpgv2
Step1: Create a Temporary Folder and CD to it
Step2: Generate GPG Key
  1. eval `gpg-agent --daemon --no-grab --write-env-file $HOME/.gpg-agent-info`
  2. export GPG_TTY=`tty`
  3. export GPG_AGENT_INFO
  4. gpg --gen-key
    1. Enter passphrase: ******
  5. Run in a Different terminal rngd -f -r /dev/urandom
Step3: read the key' s.

 gpg -k

Sample Output:

GPG Key o/p:
.......+++++
+++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
.+++++
.................+++++
gpg: key 50F6E79D marked as ultimately trusted
public and secret key created and signed.

gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
pub   2048R/50F6E79D 2015-08-14
Key fingerprint = 3C2C 81AA 5B9E 6772 1AEA  9AF3 78B2 D37D 50F6 E79D
uid ZeroOnePrograms  <developer@zerooneprograms.com>
sub   2048R/EA01868C 2015-08-14

How to create debian package without tarball file?


Prerequisites

  1. Installed packages 
    1. build-essential
    2. fakeroot
    3. devscripts
    4. gnupg-agent
    5. debhelper
    6. dh_make
Notes:

  1. This tutorial is useful to develop a quick Debian package example.
  2. This tutorial doesn't have any explanation' s for 
    1. Debian rules.
    2. Various Debian build stage' s.
    3. license creation and attaching to Debian package.
    4. Debian man pages creation& integrating to the Debian package.
    5. Debian package creation from existing tarball.
    6. how to write debian package build changes.
    7. gpg key for Debian Package

Step1: add Debian Package default Name, Email-Id to global environment variables /etc/environment.

DEBEMAIL="developer@zerooneprograms.com"
DEBFULLNAME="zerooneprograms"
EMAIL="support@zerooneprograms.com"

Step2: add Debian Package Name, installation script file name, HOME Folder Path for Script& Package Version.

SOURCEBINPATH=$(pwd)
SOURCEBIN=zerooneprograms
DEBFOLDER=zerooneprograms
DEBVERSION=1.0

Step3: Create Folder Debian Package with below  naming Conventions

DEBFOLDERNAME=$DEBFOLDER-$DEBVERSION
# Create your scripts source dir
mkdir $DEBFOLDERNAME

Step4: Copy the installation script file to the Debian Package HOME Folder.

# Copy your script to the source dir
cp $SOURCEBINPATH/$SOURCEBIN $DEBFOLDERNAME
cd $DEBFOLDERNAME

Step5: Create Sample Files& Folder/ Skeleton from Standard Debian Package Format.

# Create the packaging skeleton (debian/*)
dh_make  -s --indep --createorig

|-- debian
|   |-- rules
|   |-- copoyright
|   |-- control
|   |-- changelog
|   |-- patches
|   |-- source
|   `-- upstream
|-- doc
|   |-- man
|   |   `-- fr
|   |-- syntax
|   `-- texinfo
|-- m4
|-- po
`-- src

Step6: Change the script files for below, based on package requirements

  1. add zerooneprograms script file to root folder 
  2. preinstallation scripts
  3. post installation scripts
  4. pre remove scripts
  5. post remove scripts
  6. control file
  7. rules

echo "\nchange control file, preins, postins,prerm and postrm and hit the <Enter> with any key"
read temp

Step7: Create custom Linux terminal commands,  debian/install has instructions to create File& Folder' s while installing the package. Below line will add the file zerooneprograms script in /usr/bin, which creates a terminal command.
echo $SOURCEBIN usr/bin > debian/install

add the instructions to create Folder' s and to copy the files& Folder to the Specific path.

Step8: Remove the all unnecessary files 
# Remove the example files
rm debian/*.ex

Step9: Remove the all unnecessary files 
dpkg-buildpackage -uc -us   #without key


Example Script for creating the debian package  create.sh 

#!/bin/bash
# Configure your paths and filenames
SOURCEBINPATH=$(pwd)
SOURCEBIN=zerooneprograms
DEBFOLDER=zerooneprograms
DEBVERSION=1.0


DEBFOLDERNAME=$DEBFOLDER-$DEBVERSION

# Create your scripts source dir
mkdir $DEBFOLDERNAME

# Copy your script to the source dir
cp $SOURCEBINPATH/$SOURCEBIN $DEBFOLDERNAME
cd $DEBFOLDERNAME

# Create the packaging skeleton (debian/*)
dh_make  -s --indep --createorig

echo "\nchange control file, preins, postins,prerm and postrm and hit the <Enter> with any key"
read temp

# Remove make calls
#grep -v makefile debian/rules > debian/rules.new
#mv debian/rules.new debian/rules

#mkdir -p debian/tmp

#cp $SOURCEBINPATH/$SOURCEBIN  debian/tmp/
# debian/install must contain the list of scripts to install
# as well as the target directory
echo $SOURCEBIN usr/bin > debian/install
#echo test opt >> debian/install

# Remove the example files
rm debian/*.ex

# Build the package.
# You  will get a lot of warnings and ../somescripts_0.1-1_i386.deb
#debuild -S -rfakeroot -k<gpg_key_id>

#debuild -S -rfakeroot -k50F6E79D
#(or)
dpkg-buildpackage -uc -us   #without key


Example rules for Debian Package Creation

#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

#%:
# dh $@
clean:
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp

install: build
dh_testdir
dh_testroot
dh_clean -k 
dh_installdirs

# Add here commands to install the package into debian/flare.

install -d debian/opt/ZeroOnePrograms
cp -r $(CURDIR)/../ZeroOnePrograms    $(CURDIR)/debian/zerooneprograms/opt


# Sample RULE's

# install -m 755 $(DISTSDIR)/*              $(CURDIR)/debian/tmp/opt/
# bunzip2                          $(CURDIR)/debian/tmp/usr/share/doc/debian-book/*pdf*.bz2
# install -m 644 $(DISTSDIR)/*latex*.bz2    $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# cp -r          $(SRCDIR)/htmlsplit        $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# install -m 644 $(CURDIR)/debian/copyright $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# install -m 644 $(SRCDIR)/*.html           $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# install -m 644 $(SRCDIR)/*.css            $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# cp -r          $(SRCDIR)/images           $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# cp             $(CURDIR)/LICENSE          $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# cp             $(CURDIR)/AUTHORS          $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# gzip           $(CURDIR)/debian/tmp/usr/share/doc/debian-book/AUTHORS
# cp             $(CURDIR)/README           $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# gzip           $(CURDIR)/debian/tmp/usr/share/doc/debian-book/README
# cp             $(CURDIR)/TODO             $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# gzip           $(CURDIR)/debian/tmp/usr/share/doc/debian-book/TODO
# cp             $(CURDIR)/README.Debian    $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# gzip           $(CURDIR)/debian/tmp/usr/share/doc/debian-book/README.Debian
# cp             $(CURDIR)/ChangeLog        $(CURDIR)/changelog
# mv             $(CURDIR)/changelog        $(CURDIR)/debian/tmp/usr/share/doc/debian-book/
# Build architecture-independent files here.
binary-indep: build install
# We have nothing to do by default.

# Build architecture-dependent files here.
binary-arch: build install
dh_testdir
dh_testroot
dh_installchangelogs 
# dh_installdocs --exclude=CVS
# dh_installexamples
dh_install
# dh_installmenu
# dh_installdebconf
# dh_installlogrotate
# dh_installemacsen
# dh_installpam
# dh_installmime
# dh_installinit
# dh_installcron
# dh_installinfo
# dh_installman
dh_link
# dh_strip
dh_compress --exclude=.pdf --exclude=LICENSE
dh_fixperms
# dh_perl
# dh_python
# dh_makeshlibs
dh_installdeb
# dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb

binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install configu 


Reference

How to Validate SSL Certificates with bash script?

Prerequisites

  1. SSL Certificates
  2. OpensSSL to be Installed


Step1: Prompt for the SSL Certificates File Paths

echo "Reference"
echo "---------"
echo "enduser-example.com.crt
enduser-example.com.key
enduser-example.com.chain"
echo ""
echo ""
echo "Please Provide full Path for Certificate (enduser-example.com.crt)"

            if [ -e $PATH_CERT_FILE ];then
                    #Do Nothing
               echo ""
            else
                    echo "Wrong Path"
                exit 1
            fi

echo "Please Provide full path for Intermediate Certificate (enduser-example.com.chain|gd_bundle.crt)"
            read PATH_INTERMEDIATE_CERT
                        if [ -e $PATH_CERT_FILE ];then
                                #Do Nothing
                                echo ""
                        else
                                echo "Wrong Path"
                                exit 1
                        fi

echo "Please Provide the full path for Private Key File(enduser-example.com.key)"
            read PATH_KEY_FILE
                        if [ -e $PATH_CERT_FILE ];then
                                #Do Nothing
                                echo ""
                        else
                                echo "Wrong Path"
                                exit 1
                        fi

Step2: validate the certificates with OpenSSL tool

#Validating Certificates
_status=$(openssl verify -CAfile $PATH_INTERMEDIATE_CERT  $PATH_CERT_FILE | grep OK)
            result=$(echo $_status | cut -f2 -d ':')
            if [ "$result" != " OK" ]; then
                echo "Please Verify The Certificates and Try Again.."
                exit 1
            fi

How to change VHost Name & respective SSL Certificates with Bash Script?

Step1: change the VHost ServerName/Domain Name with sed
sed -i "s@OldDomain.*@NewDomain@g"

Step2: Prompt for the New Certificates Absolute Path& Validate them from above Procedure
Step3: On Successful validation, copy the certificate files to new Folder.

            #Configuring the Certificates
            _date=$(date +"%H%M%S")
            mkdir -p /etc/apache2/$_date
            echo $_date
            cp $PATH_CERT_FILE    /etc/apache2/"$_date"/
            cp $PATH_INTERMEDIATE_CERT /etc/apache2/"$_date"/
            cp $PATH_KEY_FILE  /etc/apache2/"$_date"/       


Step4: Copy the absolute path of each certificate to a variable.
            _CERT_FILE=$(echo "$PATH_CERT_FILE"| rev |cut -f1 -d '/' |rev)
            NEW_PATH_CERT_FILE=/etc/apache2/"$_date"/"$_CERT_FILE"

                _INTERMEDIATE_CERT_FILE=$(echo "$PATH_INTERMEDIATE_CERT"| rev |cut -f1 -d '/' |rev)
            NEW_PATH_INTERMEDIATE_CERT=/etc/apache2/"$_date"/"$_INTERMEDIATE_CERT_FILE"

            _KEY_FILE=$(echo "$PATH_KEY_FILE"| rev |cut -f1 -d '/' |rev)    
            NEW_PATH_KEY_FILE=/etc/apache2/"$_date"/"$_KEY_FILE"

Step5: Replace the SSL File Paths in Apache Configuration files.
            #Seetting New SSL Paths in Apache Configuration
            sed -i "s@SSLCertificateFile.*@SSLCertificateFile  $NEW_PATH_CERT_FILE@g"  /etc/apache2/sites-available/zerooneprograms.conf
            sed -i "s@SSLCertificateKeyFile.*@SSLCertificateKeyFile  $NEW_PATH_KEY_FILE@g"  /etc/apache2/sites-available/zerooneprograms.conf
            sed -i "s@SSLCertificateChainFile.*@SSLCertificateChainFile  $NEW_PATH_INTERMEDIATE_CERT@g"  /etc/apache2/sites-available/zerooneprograms.conf

Step6: Check the Apache Syntax and restart the web server.

Sunday, 5 June 2016

How to check prerequisite in linux bash script?

Check the user is root or not?

if [ "$(whoami)" != 'root' ]; then
        echo "You have no permission to run $0 as non-root user."
        exit 1
fi

Check the OS?

OS=`cat /etc/issue |head -n 1 |awk '{ print $1 }'`
if [ $OS != "Ubuntu" ]; then
          echo "OS Architecture Not Supported...!"
       exit 1
fi

Check the VCPU' s?

vcpu=$(lscpu | grep "^CPU(s):.*$"|awk '{print $2}')
if [ $vcpu -lt 2 ];then
        echo "Minimum 2 vcpu's are Required...!"
        exit 1
fi


Check the Total Memory/RAM?

TotalMemory=$(grep MemTotal /proc/meminfo | awk '{print $2}')

if [ $TotalMemory -lt 8113442 ];then
        echo "Insuffiecient Memory 'Total RAM Should be 8G'"
        exit 1
fi

<<'COMMENT'
Total Memory        -  8G/100%  -   8388608KB
Operational Memory  -  .30%     -   25165.824KB
Remaining           -  99.7%    -   8363442.176
Required            -  6G/100%  -   6291456KB
COMMENT

Check the Available Memory/RAM?

FreeMemory=$(grep MemFree: /proc/meminfo |awk '{print $2}')
if [ $FreeMemory -lt 6291456 ];then
       echo "Insuffiecient Memory 'Require 6G Free Memory'"
       exit 1
fi

Check the any other installation' s are in progress?

if lsof /var/lib/apt/lists/lock >>/dev/null 2>&1 ;then
                echo "/var/lib/apt/lists/lock  locked"
                exit 1
fi

if lsof /var/lib/dpkg/lock >>/dev/null 2>&1 ;then
                echo "/var/lib/dpkg/lock  locked"
                exit 1
fi

Check the availability of Port?

nc -z 127.0.0.1 80;

if test "$?" -eq "0"  #if port 80 is in Listening mode
then
        echo "Port 80 is not available."
        exit 1
fi


Note: Tested under Ubuntu 12.x& 14.x

How to repair the MongoDB with bash script?


repair_and_restart_mongod(){

  if [ -f /etc/default/mongodb ]; then . /etc/default/mongodb; fi

  ENABLE_MONGODB="yes"
  if [ "x$ENABLE_MONGODB" = "xyes" ]; then
        if [ -f $MONGODB_HOME/mongod.lock ]; then
                rm $MONGODB_HOME/mongod.lock >> /dev/null
                sudo -u mongodb /usr/bin/mongod --config /etc/mongodb.conf --repair >> /dev/null
        fi
        #exec start-stop-daemon --start --quiet --chuid mongodb --exec  /usr/bin/mongod -- --config /etc/mongodb.conf
        service mongodb start >> /dev/null  2>&1
  fi
}

Tested under Ubuntu Server 12.x& 14.x

How to check the MongoDB Status in bash script?


is_mongod_running(){
PID=$(cat $MONGODB_HOME/mongod.lock)
        status=$(service mongodb status 2>&1)
        echo $status | grep -q "mongodb start/running, process.*"

        if [ $? -eq 0 ] && [ "x$PID" != "x" ] ;then     #&& kill -0 $PID 2>/dev/null; then
                _status=0 #echo "mongod is running"
        else
                _status=1 #echo "mongod is not running"
        fi
        return $_status
}


Note: Tested under Ubuntu Server 2.x& 14.x

How to check the Apache Tomcat Status with bash script?


##check the status of tomcat
is_tomcat_running(){
        PID=$(cat $TOMCAT/conf/catalina.pid 2>&1)
        if [ "x$PID" != "x" ]&& kill -0 $PID 2>/dev/null; then
                _status=0 #echo "tomcat already running"
        else
                _status=1 #echo "tomcat is not running"
        fi
        return $_status
}

How to stop the Tomcat with bash script?


stop() {
  pid==$(cat $TOMCAT/conf/catalina.pid 2>&1)
  if [ -n "$pid" ]
  then
    echo -e "\e[00;31mStoping Tomcat\e[00m"
    #/bin/su -p -s /bin/sh $TOMCAT_USER
        sh $CATALINA_HOME/bin/shutdown.sh

    let kwait=$SHUTDOWN_WAIT
    count=0;
    until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ]
    do
      echo -n -e "\n\e[00;31mwaiting for processes to exit\e[00m";
      sleep 1
      let count=$count+1;
    done

    if [ $count -gt $kwait ]; then
      echo -n -e "\n\e[00;31mkilling processes didn't stop after $SHUTDOWN_WAIT seconds\e[00m"
      terminate
    fi
  else
    echo -e "\e[00;31mTomcat is not running\e[00m"
  fi

  return 0
}


Note: We need to kill/terminate the tomcat if it is failed to shutdown with in the given period of time& we need to clear the PID.

How to check Apache Web Server Status in Ubuntu with bash script?


##Check Apache Web Server running
is_apache_running(){
        a=$(service apache2 status) >> /dev/null
        if [ "$a" = " * apache2 is running" ];
        then
                _status=0  #echo "Apache WebServer Already Running"
        else
                _status=1  #echo "Apache WebServer is not Running"
        fi
        return $_status
}


##Check Apache Syntax
is_apache_syntax_ok(){

_syntax=$(apache2ctl -t 2>&1)

if [ "$_syntax" = "Syntax OK" ]; then
         _syntax_ok=0
else
         _syntax_ok=1
fi
        return  $_syntax_ok
}

Above snippet is tested under Ubuntu Server 12.x & 14.x.

How to validate Fully Qualified Domain with bash script?

#!/bin/bash

fqdn="www.google.com"

#FQDN Validation
{
        echo $fqdn | grep -P "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"
} && {
        echo "valid FQDN"  
} || {
        echo "Invalid FQDN Address"
exit 1
}


How to validate the email with bash script?


If else structure created with shell script operators

{
// shell script snippet A
} && {
// shell script snippet B
} || {
//shell script snippet C
}

snippet A executes, B will execute upon successful execution of script A & C will execute upon unsuccessful execution of script A.

grep is a linux command based tool to search the string match pattern' s where -E option for extended regular expression evaluation.



#!/bin/bash
email="test@gmail.com"

#Email Validation
{
echo  | grep -E "^[a-z0-9!#\$%&'*+/=?^_\`{|}~-]+(\.[a-z0-9!#$%&'*+/=?^_\`{|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]*[a-z0-9])?\$"
} && {
echo "Valid E-Mail Address"
} || {
echo "Invalid E-Mail Address"
exit 1
}







Friday, 3 June 2016

How to check MongoDB is running with linux shell script?


#!/bin/bash

if pgrep mongod >>/dev/null ;then
    echo "Mongo DB Server is Running"
else
    echo "Mongo DB Server is not Running"
fi


Explanation: pgrep is signal process, it looks through running process and list the process id' s that matches the name of the process.