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

Monday 19 November 2012

Checking the existence of a database using shell script

#!/bin/bash

#############################################
# script to check whether database exists or not                                      
#                                                                                                                    
#                                                                                                                    
#                                                                                                                    
# Made By : Damanpreet Singh (DEMON)                                                   
# http://damanpreet.co.cc/                                                                            
#                                                                                                                    
#                                                                                                                 
# created : 13-11-2012                                                                                            #   VER=1.1                                                                                              
#                                                                                                                
#############################################

echo "enter mysql username"
read u
echo "enter mysql password"
read p
echo "enter database name to check"
read db_name
RESULT=`mysql --user="$u" --password="$p" --skip-column-names -e "SHOW DATABASES LIKE '$db_name'"`
if [ $RESULT ]; then
    echo "Database exist"
else
    echo "Database does not exist"
fi

Thursday 4 October 2012

arrays in shell script

I needed to make changes in a file that is downloaded to the system,
the changes include inserting the database name, database user_name,
etc. Firstly I tried so many methods but they were insufficient and
did not solve the purpose correctly, so I tried changes to it and was
able to do so. I could make changes to the settings.py file( the file
i wanted to make changes to) using "sed" command(sed=stream editor).
There was one big problem, I was using the same command multiple
times, so I used the for loop and put the different elements in
arrays.
Harman's mail on using arrays in shell script was very helpful, I
faced very less problem thanks to it. Secondly, I restricted the use
of sed to particular lines(rows in file) specifying the line in a
array .
Now what I have just made(just the main part):


###########################################################
array1=("db_name" "db_user" "db_password" "user_name" "email_add")
array2=("15" "16" "17" "86" "110")

len=${#array[*]}

file=Automation/settings.py

i=0
while [ $i -lt $len ]; do
        read -p "${array[$i]}" ${array1[$i]}
        #echo ${!array1[$i]}
        sed -i "${array2[$i]} s/${array1[$i]}/${!array1[$i]}
/" $file
        let i++
done
###########################################################

This code works fine, but I need to improve it.
 
 

Sunday 30 September 2012

jason statham - the transporter





 I only have two rules. Rule 1, no names. Rule 2, there is no such thing as rule 2. ;-)-----transporter2

Thursday 9 August 2012

Adding Django-catalog

Django-catalog
This application was created to organize the objects in a tree structure.

Installation
A. Download

At present, a stable release Django-catalog there, but you can download the development version from the repository on github

pip install django-catalog


Two. Connect the application

To connect the installed Django-catalog, add in your project settings.py configuration file the following contents

INSTALLED_APPS = (
    'Catalog',
    'Catalog.contrib.defaults',

)
Three. Connect URLs applications

Add the URL of the application in the Django-catalog of your project urls.py

To use the scheme to access items on the tree slug

urlpatterns  = patterns ('',
    (r '^ catalog /', include ('catalog.urls.by_slug')),
)

To use the scheme to access elements of a tree on their id

urlpatterns  = patterns ('',
    (r '^ catalog /', include ('catalog.urls.by_id')),
)

4. Creating models

In order to use the directory to create for him a model. Previously, we hooked INSTALLED_APPS application directory implements the basic models and methods of work with them. At this stage, to ensure the health directory, we have enough. Start the synchronization of the database to create a catalog of standard models

python manage.py syncdb

Five. The administrative interface

To fill the catalog of categories and products go to the Django administration interface and select the Manage catalog.

6. The use of templates

Django-catalog is supplied with ready-made templates for the work, which should be enough to start using the directory.

Friday 3 August 2012

Matrix on terminal

First of all, install cmatrix using the following command:

$ sudo apt-get install cmatrix

After cmatrix is installed, run the followinf command with different options such as, -a, -b, -B, etc

$ cmatrix -b

and what you get is the output. :-)

Terminal music player

For the past two months i have been using terminal(mplayer) to play my
songs, I found it quite interesting to use terminal to play music than
using some other applications. I learnt how to use mplayer and run
songs on it, everytime I had to select a song, then play it and run
the command

mplayer abc.mp3

Then came the issue of playing multiple songs, used

mplayer *.mp3

Then I wanted the songs to play in a random pattern(shuffle). For that
I created a playlist in the directory containing the .mp3 files and
ran command

 find -type f -iname \*.mp3 > demon.txt

and hence a playlist named demon.txt is created, I would run it using
the command

mplayer -shuffle -playlist demon.txt

this would play songs in shuffle pattern. I created a script to play
songs in shuffle. But there was a problem that the script would run
only if the Drive containing .mp3 files and the playlist was mounted,
and if the drive was unmounted it would show error. I then learnt to
Mount drive using terminal commands and making small changes, and made
a script that would play when the drive was unmounted. One can learn
how to mount a drive from terminal from
https://help.ubuntu.com/community/Mount/USB

Now i have finally made a script, that checks whether the .mp3
containing drive is mounted or not, if the drive is mounted it simply
plays song from the playlist demon.txt.
and if the drive is not mounted, the script would fetch another script
in my folders that would unmount the drive and then run the playlist
demon.txt.

Here is the script i use, kept in my home folder
http://202.164.53.122/~daman/scripts/hi.sh

And the other script I use to Mount
http://202.164.53.122/~daman/scripts/demon.sh


I am really happy, removed banshee and rhythm box from my system :D.

Wednesday 13 June 2012

ways to see text using terminal commands

Following are some ways to display data in different applications using following commands:

To see text in Gedit
demon@demon-pc:~/ gedit text.txt

To see text in vim
demon@demon-pc:~/ vim text.txt

To see text in office(Libre Office)
demon@demon-pc:~/ soffice text.txt

We can use the same for GEANY.