Wednesday 18 June 2014

secrets of debconf-finally revealed

This is a simple walkthrough of Debconf, go through each and every step carefully, soon you will be using it without any trouble. Best of Luck.
--What is Debconf ? Debconf is a backend database, with a frontend that talks to it and presents an interface to the user. There can be many different types of frontends, from plain text to a web frontend. The frontend also talks to a special config script in the control section of a debian package, and it can talk to postinst scripts and other scripts as well, all using a special protocol. These scripts tell the frontend what values they need from the database, and the frontend asks the user questions to get those values if they aren't set.
Confusing ? Let's go through the three files-config,template and script.
--Template
It contains all the notes, different questions you want to ask the user, be it boolean(true/false), multiple answer, string inputs, displaying notes, everything you want to display or ask the user. P.S. :make sure you leave a space in the begining of the Long Description, check the file in case you have any doubt.
--Config
Next, decide what order the questions should be asked and the messages to the user should be displayed from the template file we talked about earlier. Config script does all this, it has no other job than to display notes and questions from template file and take input from the user in the form of answers to the question it asked.
--Script
The job of this script is to use the input stored in debconf database. It all depends how you want to use the inputs, I jave just printed the inputs stored.
--Where to find the Debconf database ?
/var/cache/debconf/config.dat config.dat stores all the template questions, notes everything you stored in the template file once you have run the config script.
--How to run the scripts ?
  1. Change the permssion of the scripts to executable.
  2. run the first script "sudo ./config" .You need to use sudo inorder to make changes to the debconf database.
  3. run the second script "sudo ./script".
P.S. : The first script would run for only one time as after running if on the first time the flag in the debconf database gets set or "seen", but you can run the second script(script) any number of time. If you want to run the first script(config) again, do the following:
$ sudo gedit /var/cache/debconf/config.dat
and search the template you created and remove "seen" from all the flags of your templates, once you have deleted seen, you can run the config script again.
--That's all for the debconf, best of luck again and enjoy your experience.

MongoDB- Address already in use for socket

Open Terminal and run the following command:
sudo mongod


The following error in the port being used is thrown
[websvr] ERROR: listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:28017
[initandlisten] ERROR: listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017
[websvr] ERROR:   addr already in use
[initandlisten] ERROR:   addr already in use
[initandlisten] now exiting
dbexit:
[initandlisten] shutdown: going to close listening sockets...
[initandlisten] shutdown: going to flush diaglog...
[initandlisten] shutdown: going to close sockets...
[initandlisten] shutdown: waiting for fs preallocator...
[initandlisten] shutdown: closing all files...
[initandlisten] closeAllFiles() finished
[initandlisten] shutdown: removing fs lock...
dbexit: really exiting now
Run the following command to check the mongo processes/
ps -eF | grep 'mongo\|PID'

UID        PID  PPID  C    SZ   RSS PSR STIME TTY          TIME CMD
mongodb    1024     1  0 24077 13052   1 19:09 ?        00:00:05 /usr/bin/mongod --config /etc/mongodb.conf
 
1000      2814  2752  0   832   884   0 19:33 pts/1    00:00:00 grep --color=auto mongo\|PID
 
 
the problem is with the process with id 1024 , use the following command
___________________________________________________
sudo kill 1024
 ___________________________________________________
Try running mongodb again with the following commabd.

sudo mongod
[initandlisten] MongoDB starting...
[websvr] admin web console waiting for connections on port 28017
[initandlisten] waiting for connections on port 27017

Saturday 1 December 2012

Appending a file(>>) using sudo.

>I wanted to append into a system file, that needed sudo permission:

             sudo cat Automation/other_files/hhtp_cont >> /etc/apache2/httpd.conf

>but I got the following error

             x.sh: 1: cannot create /etc/apache2/httpd.conf: Permission denied

>But since sudo can do everything, then why?


>The possible explanation for this is that (>>) works before sudo, so it is not run with the sudo power and hence gives the above stated error
>It can be easily sorted out and can be done as following easily.
>One alternative way is to wrap the whole command in another bash command and then run it with sudo.
>It Works.. :-)
>Try the solution below.

        sudo bash -c  "cat Automation/other_files/hhtp_cont >> /etc/apache2/httpd.conf"


Thursday 29 November 2012

Using $PWD in sed command

>I needed to get the path of my current directory into a file in particular >location, so I tried the conventional method of sed. I used the following code, >where I passed the value of $PWD in variable named path, then I echoed a >string with value of variable path, then I tried to replace GLOBALLY the "path" >with the value of varaible path in the file named a.txt.




path=$PWD
echo "my name is demon and I live in $path"

sed -i "s/path/"$path"/g" a.txt

>I would get the following error

my name is demon and I live in /home/demon/Documents/work/comm
sed: -e expression #1, char 9: unknown option to `s'

>So the solution to this problem is very much simple, just replace the delimiter .with a hash, pipe, colon. and the problem is solved

>example:

path=$PWD
echo "my name is demon and I live in $path"
sed -i "s#path#"$path"#g" a.txt




path=$PWD
echo "my name is demon and I live in $path"
sed -i "s:path:"$path":g" a.txt


path=$PWD
echo "my name is demon and I live in $path"
sed -i "s|path|"$path"|g" a.txt


Works well for me.

Wednesday 28 November 2012

TCC-script

#!/bin/bash

#################################################################
# Settings.py file changing script                              #
#                                                               #
#                                                               #
#  run in terminal, use ./auto.sh                               #
#                                                               #
# Made By : Damanpreet Singh (DEMON)                            #
# http://damanpreet.co.cc/                                      #
#                                                               #
#                                                               #
# created : 4-10-2012                                           #
# last update : 15-11-2012                                      #
# VER=1.3                                                       #
#                                                               #
#################################################################

# this script works only for python 2.7


backup()
{

cp /etc/apache2/httpd.conf Automation/other_files/   #copies httpd.conf file in Automation/other_files folder

}

run()  # the function
{
echo ""
echo "######################################################"
echo "#                                                    #"
echo "#    INSTALLING---TCC-Automation software---         #"
echo "#                                                    #"
echo "######################################################"
echo ""
#################################################################
#
# arrays with their values.
#
#################################################################

file=Automation/settings.py

array=("enter the email address :")
array1=("email_add")
array2=("37")

#################################################################
#
#  asking user to input the mysql username
#
#################################################################

a=1
while [ $a -ne 2 ]
do
{

# inputs database name from the user
read -p "enter mysql username :" db_user
read -p "enter mysql password :" db_password


RESULT=`mysql --user="$db_user" --password="$db_password" --skip-column-names -e "SHOW DATABASES LIKE 'mysql'"` 2> /dev/null
if [ $RESULT ]; then
    echo ""
    echo "Username and password match"
    a=2
    break


else
    echo ""
    echo "Username and password doesn't match"
    echo "re-enter the details"
    echo ""

fi
}
done

sed -i "16 s/db_user/$db_user/" $file
sed -i "17 s/db_password/$db_password/" $file
##################################################################
#
# length of the array
#
##################################################################


len=${#array[*]}

i=0

while [ $i -lt $len ]; do
    read -p "${array[$i]}" ${array1[$i]}                           #this reads input from the user
    sed -i "${array2[$i]} s/${array1[$i]}/${!array1[$i]}/" $file   #uses sed command to replace word from file to be replaced by user inputs
    let i++
done                                                    #end of for loop
       

# this part checks if database name entered is created before or not.       
a=1
while [ $a -ne 2 ]
do
{

# inputs database name from the user
read -p "enter database name you want to create :" db_name

#checks the existance of database
RESULT=`mysql --user="$db_user" --password="$db_password" --skip-column-names -e "SHOW DATABASES LIKE '$db_name'"`
if [ $RESULT ]; then
    echo "The Database exist, choose another name for database."
else
    a=2
    break

fi
}
done   

   
        sed -i "15 s/db_name/$db_name/" $file
#cat Automation/settings.py                       #reads file in terminal


#################################################################################
#
# here the username automatically gets input from the system
#
#################################################################################


NAME=$(who am i | awk '{print $1}')

sed -i "111 s/user_name/$NAME/" $file
echo "the username is $NAME"




######################################################################
#
# changes in django.wsgi file
#
######################################################################

sed -i "s/user_name/$NAME/" Automation/apache/django.wsgi

######################################################################
#
# changes in httpd.conf file
#
#######################################################################

# need sudo power for this

cat Automation/other_files/hhtp_cont >> /etc/apache2/httpd.conf   
      #this appends the text from the file to the httpd.conf


sed -i "s/user_name/$NAME/" /etc/apache2/httpd.conf          
      #this replaces the word to the username



#######################################################################
#
# creating the database and the further changes required by the user
#
#######################################################################


mysqlbash_path='/usr/bin/mysql'             #mysql path address

mysqlbash="$mysqlbash_path --user=$db_user --password=$db_password -e"  #declaring a variable

$mysqlbash "create database $db_name "      #creates databases with the name defined by the user

  # a new database is created

echo ""
echo ""
read -p "enter 'Yes' for the demo database & 'No' for new database : "  db_yesno


#this checks for every yes condition the user might enter in.
if [ $db_yesno = y ] || [ $db_yesno = Y ] ||[ $db_yesno = yes ] ||[ $db_yesno = YES ]    
then
echo ""
echo "now u get the demo.sql in your database"
echo "get ready to use TCC automation software"


# this imports demo.sql to the database defined by the user
mysql --user=$db_user --password=$db_password $db_name < Automation/other_files/demo.sql

cd Automation/

# this creates a new superuser
python manage.py createsuperuser

#defined every possible no condition
elif [ $db_yesno = n ] || [ $db_yesno = N ] || [ $db_yesno = no ] || [ $db_yesno = NO ] 
then
echo ""
echo "now u get a new database"
echo "enjoy your experience"


cd Automation/
python manage.py syncdb                   #creates a blnk database for use, using django commands


# scelect count(*) , counts the number of enteries in the table
result1=`mysql --user=$db_user --password=$db_password --skip-column-names -e "use $db_name;" -e "select count(*) from auth_user;"`

#echo $result1

# ths checks if the count is zero or not
if [ $result1 = 0 ]
then
echo ""
echo "you need to create a superuser"
#this creates a superuser
python manage.py createsuperuser

else

echo ""
fi

# there is a need to enter Organisation details in the database.
echo ""
echo "Now get ready to ADD Organisation details to your software."
echo ""

read -p "enter organisation id :" id
read -p "enter organisation name :" name
read -p "enter organisation address :" address
read -p "phone/contact number :" phone
read -p "Director of the Organisation :" dir
#read -p "logo" logo

# this Inserts into the table the input values.
mysql  --user=$db_user --password=$db_password $db_name << EOF
Insert into tcc_organisation (id, name, address, phone, director, logo_upload) values( "$id", "$name", "$address", "$phone", '$dir', "$logo");
EOF


# There is a need to enter Department details in the database.
echo ""
echo "Now get ready to ADD Departmant details to your software."
echo ""

read -p "enter the Department id :" id
read -p "enter Department name :" name
read -p "enter Department address :" address
read -p "phone/contact number :" phone
read -p "Dean of the Department:" dean
read -p "enter the fax number :" faxno

# this inserts values into corresponding fields in tcc_department table
mysql  --user=$db_user --password=$db_password $db_name << EOF
Insert into tcc_department (id, organisation_id, name, address, phone, dean, faxno) values( "$id", 1, "$name", "$address", "$phone", '$dean', "$faxno");
EOF

fi  
}

restart()
{
/etc/init.d/apache2 restart               #restarts apache
}

browser()
{
gnome-open http://localhost/automation/
}

check()
{
 echo ""
   echo "######################################################"
   echo "#                                                    #"
   echo "#    DOWNLOADING---Automation software---            #"
   echo "#                                                    #"
   echo "######################################################"
   echo ""
  
   #this clones the Automation folder from github
   git clone https://github.com/sandeepmadaan/Automation.git

   backup       #backs up important files in other_files folder(/Automation/other_files/)
   run          #runs run function
   restart      #runs browser function
   browser      #runs browser function
}

#####################################################################################
#
#
#    Script starts here
#
#
#####################################################################################

if  [ -d /usr/local/lib/python2.7/dist-packages/django ] && [ -f /usr/bin/mysql ];
#if django and mysql are installed on the system the function runs.

then
   echo "-------installing required packages------"
   apt-get install apache2 libapache2-mod-wsgi
   apt-get install python-mysqldb
   sudo apt-get install python-setuptools
   easy_install pip
   echo ""
   echo "-------installing django modules---------"
   pip install django-registration
   pip install django-tagging

 

###################################################################
#
#
#checking automation folder before in home directory
#
#
###################################################################

echo "now we test if there is any folder named Automation that exists in home directory"
if (test -d Automation)              #check if the same folder exits
  then


######################################################################
#
# this part makes sure that if there is any existing Automation folder
# in home directory then it renames it with Automation.date.time
#
#######################################################################

#cd /home/$user_name/

#exercise=/home/$user_name/

mDate=$(date +%Y%m%d%H:%M:%S)
for mFName in $PWD/Automation
do
    mPref=${mFName%.log}
    echo $mPref | egrep -q "\.[0-9]{10}:[0-9]{2}:[0-9]{2}"
    [ $? -eq 0 ] && continue
    mv ${mFName} ${mPref}.${mDate}
    echo $PWD3
done



fi
   check
 

else
    echo "Install Django and Mysql, before running the script"              #else exits
    exit
fi

creating HTML page using Shell script

following is the script to create a html page, copy and paste in a document and save it as test.sh

#!/bin/bash

# make_page - A script to produce an HTML file
name=$(logname)
uname=$(uname)
time=$(date +"%x %r %z")
uptime=$(uptime)
function system_info
{
echo "$uptime is the new uptime"
}
cat << EOF
<HTML>
<HEAD>
    <TITLE>
    mysql check
    </TITLE>
</HEAD>

<BODY>
    $system_info <br>
    welcome $name on $uname at $time
    <h1>This checks the mysql conection</h1>
  <form>
    <h3>Enter the mysql username<input type="text" name="name"></h3>
    <h3>Enter the password<input type="password" name="pwd"></h3>
    <input type="submit" value="submit">
  </form>

</BODY>
</HTML>
EOF


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

Then in order to run it on the browser create another script, m.sh and copy paste the content below in it:

sh test.sh > r.html
gnome-open "r.html"

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

In order to run it, just run the latest shellscript- m.sh, just type the following in the terminal


sh m.sh



and the browser automatically opens the crested html file.

Monday 26 November 2012

Shell script to check Mysql Connection.

#!/bin/bash

read -p "enter mysql username :" db_user
read -p "enter the password :" db_password


RESULT=`mysql --user="$db_user" --password="$db_password" --skip-column-names -e "SHOW DATABASES LIKE 'mysql'"` 2> /dev/null
if [ $RESULT ]; then
    echo "successful, connection estabilished"

else
   
    echo "username and password doesn't match"
   
fi