Monday, 31 March 2014

conditional statements if...then if...then...else

We can check the conditional statement in bash scripting

1. if..then..fi statement (Simple If)

2. if..then..else..fi statement (If-Else)

3. if..elif..else..fi statement (Else If ladder)

4. if..then..else..if..then..fi..fi..(Nested if)

File Operations


-s    file exists and is not empty
-f    file exists and is not a directory
-d    directory exists
-x    file is executable
-w    file is writable
-r    file is readable


Numeric Comparison


expr1 -eq expr2   Returns true if the expressions are equal
expr1 -ne expr2   true if the expressions are not equal
expr1 -gt expr2   true if expr1 is greater than expr2
expr1 -ge expr2   Returns true if expr1 >= to expr2
expr1 -lt expr2   Returns true if expr1 is less than expr2
expr1 -le expr2   Returns true if expr1 is >= expr2
! expr1    Negates the result of the expression


-lt<
-gt>
-le<=
-ge>=
-eq==
-ne!=

String Comparison

Str1 = Str2    Returns true if the strings are equal
Str1 != Str2   Returns true if the strings are not equal
-n Str1        Returns true if the string is not null
-z Str1        Returns true if the string is null


=equal
!=not equal
<less then
>greater then
-n s1string s1 is not empty
-z s1string s1 is empty


if..then..fi

if [ expression ]
then
   Statement(s) to be executed if expression is true
fi


Here Shell expression is evaluated. If the resulting value is true, given statement(s) are executed.If expression is false then no statement would be not executed. Most of the times you will use comparison operators while making decisions.

#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
   echo "$a is equal to $b"
fi

if [ $a != $b ]
then
   echo "a is not equal to b"
fi


#!/bin/bash
count=100
if [ $count -eq 100 ]
then
  echo "Count is 100"
fi


#!/bin/bash
if [ $? -eq 0 ]
then
echo 'Success!'

  else
echo "Failed!!!!"
fi


#!/bin/bash
count=`wc -l /root/nopass | cut -f1 -d" "`

echo $count
if [ "$count" > "150" ]
then
echo "File has more than 150 lines"
fi


#!/bin/bash
gender="female"
if [[ "$gender" == f* ]] #syntax differ when * comes
then
echo "Welcome, Madame.";
fi


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


Note: you can give the system commands in two ways: 
        1. inside tilde `` Or using second method
        2. $()

if..then..else..fi

; semi-colon is a command terminator in bash

Use single quote when you want to literally print everything inside the single quote.
echo 'Hostname=$HOSTNAME ;  Current User=`whoami` ; Message=\$ is USD'

Use double quotes when you want to display the real meaning of special variables.
echo "Hostname=$HOSTNAME ;  Current User=`whoami` ; Message=\$ is USD"

Double quotes will remove the special meaning of all characters except the following:

$ Parameter Substitution.
` Backquotes
\$ Literal Dollar Sign.
\´ Literal Backquote.
\” Embedded Doublequote.
\\ Embedded Backslashes.

Before special variables use escape characters

#!/bin/sh
# This is some secure program that uses security.

VALID_PASSWORD="secret" #this is our password.

echo -n "Please enter the password:"
read PASSWORD

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
        echo "You have access!"
else
        echo "ACCESS DENIED!"
fi

If..then..else if..then..else if..then..else [Nested if]


#!/bin/sh

# Prompt for a user name...
echo -n "Please enter your name:"
read USERNAME

# Check for the file.
if [ -s ${USERNAME}_DAT ]; then
        # Read the age from the file.
        AGE=`cat ${USERNAME}_DAT` # This is how you execute a command and put                                                # the text output from the command into a                                                    # variable.
        echo "You are $AGE years old!"
else
        # Ask the user for his/her age
        echo "How old are you?"
        read AGE

 if [ "$AGE" -le 2 ]; then
  echo "You are too young!"
 else
  if [ "$AGE" -ge 100 ]; then
   echo "You are too old!"
  else
          # Write the age to a new file.
          echo $AGE > ${USERNAME}_DAT
         fi
        fi
fi


If..elif (else if) 

if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi


#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi


#!/bin/sh

# Prompt for a user name...
echo "Please enter your age:"
read AGE

if [ "$AGE" -lt 20 ] || [ "$AGE" -ge 50 ]; then
 echo "Sorry, you are out of the age range."
elif [ "$AGE" -ge 20 ] && [ "$AGE" -lt 30 ]; then
 echo "You are in your 20s"
elif [ "$AGE" -ge 30 ] && [ "$AGE" -lt 40 ]; then
 echo "You are in your 30s"
elif 
\[ "$AGE" -ge 40 ] && [ "$AGE" -lt 50 ]; then
 echo "You are in your 40s"
fi


 Nested if/else


#!/bin/bash

# Declare variable choice and assign value 4
choice=4

# Print to stdout
 echo "1. Bash"
 echo "2. Scripting"
 echo "3. Tutorial"
 echo -n "Please choose a word [1,2 or 3]? "

# Loop while the variable choice is equal 4
# bash while loop

while [ $choice -eq 4 ]; do

# read user input
read choice

# bash nested if/else
if [ $choice -eq 1 ] ; then

        echo "You have chosen word: Bash"

else

        if [ $choice -eq 2 ] ; then
                 echo "You have chosen word: Scripting"
        else

                if [ $choice -eq 3 ] ; then
                        echo "You have chosen word: Tutorial"
                else
                        echo "Please make a choice between 1-3 !"
                        echo "1. Bash"
                        echo "2. Scripting"
                        echo "3. Tutorial"
                        echo -n "Please choose a word [1,2 or 3]? "
                        choice=4
                fi
        fi
fi

done

********************************************

Exmp1:

#!/bin/bash
# Author: 

# Date: 
# Purpose: 

password="IF"
echo -n "Please enter your password:"
read passwd

if [ $password = $passwd ]; then
 echo "You have the access to run this script"
else
 echo "Access Denied"
exit
fi

if [ -d ~/IF ]; then
echo "Directory exists. creting file"
 cd /home/ec2-user/IF ; touch iftesting
else
 echo "directory does not exists...Creating directory"
  mkdir /home/ec2-user/IF
exit
fi



Exmp2:

#!/bin/sh

# Prompt for a user name... 
 
echo "Please enter your name:"
read USERNAME

# Check for the file.
 
if [ -s ${USERNAME}_DAT ]; then
        # Read the age from the file.
        AGE=`cat ${USERNAME}_DAT`
        echo "You are $AGE years old!"
else
        # Ask the user for his/her age
        echo "How old are you?"
        read AGE

 if [ "$AGE" -le 2 ]; then
  echo "You are too young!"
 else
  if [ "$AGE" -ge 100 ]; then
   echo "You are too old!"
  else
          # Write the age to a new file.
          echo $AGE > ${USERNAME}_DAT
         fi
        fi
fi

Exmp3:


#!/bin/sh
# Prompt for a user name... 
 
echo "Please enter your age:"
read AGE

if [ "$AGE" -lt 20 ] || [ "$AGE" -ge 50 ]; then
 echo "Sorry, you are out of the age range."
 
elif [ "$AGE" -ge 20 ] && [ "$AGE" -lt 30 ]; then
 echo "You are in your 20s"
 
elif [ "$AGE" -ge 30 ] && [ "$AGE" -lt 40 ]; then
 echo "You are in your 30s"
 
elif [ "$AGE" -ge 40 ] && [ "$AGE" -lt 50 ]; then
 echo "You are in your 40s"
fi
 
Exmp4:
 
#!/bin/bash
# Purpose: Detecting Hardware Errors
# Author: 
# Note : The script must run as a cron-job.
# Last updated on : 
# -----------------------------------------------
 
# Store path to commands
LOGGER=/usr/bin/logger
FILE=/var/log/mcelog
 
# Store email settings
AEMAIL="jeffinm@gmail.com "
ASUB="H/W Error - $(hostname)"
AMESS="Warning - Hardware errors found on $(hostname) @ $(date). See log file for the details /var/log/mcelog."
OK_MESS="OK: NO Hardware Error Found."
WARN_MESS="ERROR: Hardware Error Found."
 
 
# Check if $FILE exists or not
if test ! -f "$FILE" 
then   
 echo "Error - $FILE not found or mcelog is not configured for 64 bit Linux systems."
 exit 1
fi
 
# okay search for errors in file
error_log=$(grep -c -i "hardware error" $FILE)
 
# error found or not?
if [ $error_log -gt 0 ]
then    # yes error(s) found, let send an email
 echo "$AMESS" | email -s "$ASUB" $AEMAIL
else    # naa, everything looks okay
 echo "$OK_MESS"
fi 
 
 

Sunday, 23 March 2014

Sunday, 16 February 2014

How to setup BackUp PC in centos

BackupPC is an entirely disk-based backup and recovery system.

Backup PC Support any client OS and has a Web interface to allows user control of and access to backups.

How BackupPC Works, Install BackupPC server

The BackupPC model has one user per client. BackupPC emails the owner if it cannot back up the client after a configurable time, and the owner can control restores using the web interface.

# yum install perl-Compress-Zlib perl-Archive-Zip perl-File-RsyncP perl-XML-RSS mod_perl perl httpd

# wget http://dev.centos.org/centos/5/testing/i386/RPMS/backuppc-3.1.0-1.el5.centos.i386.rpm

if error came
error: Failed dependencies:
    perl(Time::ParseDate) is needed by backuppc-3.1.0-1.el5.centos.i386
 

search
 

# yum whatprovides "perl(Time::ParseDate)"
perl-Time-modules-2006.0814-1.el5.rf.noarch

# yum install perl-Time-modules

# rpm -ivh backuppc-3.1.0-1.el5.centos.i386.rpm

1. Add user backuppc to your machine, User backuppc will be created upon installation. Change apache user to backuppc.

 # vim /etc/httpd/conf/httpd.conf

     Change ‘User apache‘ to ‘User backuppc

2. Edit file /etc/httpd/conf.d/backuppc.conf

# vim /etc/httpd/conf.d/backuppc.conf

change ‘Allow from 127.0.0.1‘ to ‘Allow from all‘

3. Create password for cgi-bin admin user

# htpasswd -c /var/lib/backuppc/passwd/htpasswd admin

passwd: backup

4. Edit backuppc config file

# vi /etc/BackupPC/config.pl

 Find and change accordingly

$Conf{ServerHost} = 'localhost';
$Conf{SplitPath} = '/usr/bin/split';
$Conf{CatPath} = '/bin/cat';
$Conf{GzipPath} = '/bin/gzip';
$Conf{Bzip2Path} = '/usr/bin/bzip2';
$Conf{BackupPCUser} = 'backuppc';
$Conf{TopDir} = '/var/lib/backuppc';
$Conf{ConfDir} = '/etc/BackupPC';
$Conf{LogDir} = '/var/log/BackupPC';
$Conf{InstallDir} = '/usr';
$Conf{CgiDir} = '/usr/share/backuppc/cgi-bin';
$Conf{ServerInitdPath} = '/etc/init.d/backuppc';
$Conf{ServerInitdStartCmd} = '$sshPath -q -x -l root $serverHost$serverInitdPath start';
$Conf{SshPath} = '/usr/bin/ssh';
$Conf{NmbLookupPath} = '/usr/bin/nmblookup';
$Conf{PingPath} = '/bin/ping';
$Conf{CgiAdminUsers} = 'admin';

5.Grant passwordless sudo for user backuppc to run /bin/gtar and  /bin/tar

# visudo

Add these entries :

Defaults !lecture  # to disable lecture

backuppc ALL=NOPASSWD:/bin/gtar,/bin/tar   # enable user backuppc to run /bin/tar and /bin/gtar without authentication.

Comment this entry,

# Defaults requiretty

Restart apache and backuppc service

# /etc/init.d/httpd start

# /etc/init.d/backuppc restart

Open your browser and point it to ‘http://backuppc_server_ip/backuppc‘ and you should see the backuppc web interface

http://192.168.1.67/backuppc
admin
backup

After this, you have to do almost all the configuration through the web interface. To test, you can run localhost backup first. You have to create the host, fill up all the setting and you are ready to go. Record the host and ip in /etc/hosts.

# vim /etc/hosts
192.168.1.67  cloudcc.ctechz.blogspot.com cloudcc  ---------. add every machines host name here.

Once you have hosts with backups, there will be some very useful graphs displaying pool storage size.

Changing the Backuppc Pool Directory

By default, all your backups are stored at /var/lib/backuppc. However, I wish to store my backups on another disk drive that has a lot more storage than my system disk.  To do this we need to create a soft link from the default backup directory to whatever directory you wish to store the backups.  You will notice that we create two directories called "pc" and "cpool".

"pc" is where all the files are stored, and those two directories were originally causing permission issues.


# cd /var/lib/backuppc
 

# sudo mkdir pc cpool    ----- done this only if there is no 'pc' and 'cpool' directories.
 

# sudo chown -R backuppc * ----> check the ownership of directories in /vae/lib/backuppc/

If you have problems, it may be a permissions issue:
# sudo chmod -R 777 backuppc

I would recommend not leaving the permissions wide open... just make sure it is a permission error and slowly restrict the permissions until everything works correctly.  Now the backups should redirect directly to your new drive.

Adding Hosts in BackupPC

Now we need to add some hosts for backup.  Select "Edit Config" from the left menu.  Click on the "Hosts" tab.  Here we can add hosts for backup. I personally have DNS reservations for all of my hosts, so I can add by IP, however if your hosts will have different IP's I would highly recommend checking the DHCP option. As long as your hosts are registered in DNS backuppc can track them and back them up no matter where they are.  Add the hosts you will be backing up, hit save, and then click on the "Xfer" tab.

Setting Default Xfer Options (for Windows)

we need to set the default transfer settings. This is mostly a setting for large networks of pc's that are set up the same way, which makes it unnecessary for the admin to configure each pc individually. Click on "Edit Config" on the menu on the left, and select "Xfer" from the top menu.  How you set this up depends entirely on your network setup.  I have two Windows 7 PC's, so I will be setting the default settings for a SMB share.

The above screen shot shows the settings I set for the default.  I chose SMB for the transfer method.  The advantage of using SMB is that it is already built into Windows... which is good from an ease of use scenario, but is not as good from a security standpoint.  For the SMB share name, I added the administrative C$ share, which is the entire C$.  In this instance I also should have set default "Include/Exclude" settings.  This part is not extremely intuitive.

To ensure that only the right files are backed up, we need to add first the "SmbShareName" to the "New Key" field, and click "Add".  Once we have added the base share name, we can add the individual paths that we wish to backup.  You will notice above that I told backuppc to backup only the "Users" directory under the C$ share.  So now, instead of backing up the entire OS, backuppc will only backup "C:\Users", which is a much better option. You can obviously add more than one folder.  You can also add folders to exclude, which is a nice option as well. Notice that the "Override" box is checked... that just means that this host differs from the default configuration in this area.

Backing up the Localhost

The easiest way to backup your linux localhost is through "tar".  In the top host drop-drop menu, select "localhost".  Click on "Edit Config" which will enter the host-specific configuration.  Select "tar" and from the "XferMethod" drop-down menu. Next, we need to select the tar share names that we wish to back up.  Since the localhost is not running a whole lot of services, and is not mission critical, I am only backing up the /var and /etc directories.  Go ahead and save the config and you should be ready to backup your localhost!.

Samba Configuration

----> $Conf{XferMethod} = 'smb';
       What transport method to use to backup each host. If you have a mixed set of WinXX and linux/unix hosts you will need to override this in the per-PC config.pl.

----> $Conf{XferLogLevel} = 1;
       Level of verbosity in Xfer log files. 0 means be quiet, 1 will give will give one line per file, 2 will also show skipped files on incrementals, higher values give more output.

----> $Conf{ClientCharset} = '';
        Filename charset encoding on the client. BackupPC uses utf8 on the server for filename encoding. If this is empty, then utf8 is assumed and client filenames will not be modified. If set to
         a different encoding then filenames will converted to/from utf8 automatically during backup and restore.

----> $Conf{SmbShareName} = 'C$';
        Name of the host share that is backed up when using SMB. This can be a string or an array of strings if there are multiple shares per host. Examples:
        
$Conf{SmbShareName} = 'c';          # backup 'c' share
$Conf{SmbShareName} = ['c', 'd'];   # backup 'c' and 'd' shares

   This setting only matters if $Conf{XferMethod} = 'smb'.

----> $Conf{SmbShareUserName} = '';
 

Smbclient share user name. This is passed to 
 smbclient's -U argument.

----> $Conf{SmbSharePasswd} = '';
        Smbclient share password. This is passed to smbclient via its PASSWD environment variable. There are several ways you can tell BackupPC the smb share password.

----> $Conf{SmbClientPath} = '';
 Full path for smbclient. Security caution: normal users should not allowed to write to this file or directory.
 

smbclient is from the Samba distribution. smbclient is used to actually extract the incremental or full dump of the share filesystem from the PC.

Tar Configuration

Which host directories to backup when using tar transport. This can be a string or an array of strings if there are multiple directories to backup per host. Examples:

$Conf{TarShareName} = '/';                  # backup everything
$Conf{TarShareName} = '/home';              # only backup /home
$Conf{TarShareName} = ['/home', '/src'];    # backup /home and /src

The fact this parameter is called 'TarShareName' is for historical consistency with the Smb transport options. You can use any valid directory on the client: there is no need for it to correspond to any Smb share or device mount point.

you can also use $Conf{BackupFilesOnly} to specify a specific list of directories to backup. It's more efficient to use this option instead of $Conf{TarShareName} since a new tar is run for each entry in $Conf{TarShareName}.

On the other hand, if you add --one-file-system to $Conf{TarClientCmd} you can backup each file system separately, which makes restoring one bad file system easier. In this case you would list all of the mount points here, since you can't get the same result with $Conf{BackupFilesOnly}:

$Conf{TarShareName} = ['/', '/var', '/data', '/boot'];



Linux History Tricks

Showing timestamp using HISTTIMEFORMAT

# export HISTTIMEFORMAT='%F %T '

Repeat previous commands

# !! ---------> execute the last run command
 

# !-4 --------> executed the 4th command executed
                from backward
 

# !c  --------> execute the command that you run last, 
                which start with the specific word c
 

# ctrl+P -----> will display the previous command
 

# ctrl+r -----> for reverse search the commands
 

# history | more,less ----> check the command that you 
               looking for and note its line number also
 

141  08:55:33 2012-02-02 clear ( her line number is 141) to execute this command run
 

    # !141
 

# cd !^   --------> !^ will get the next argument after cd command

Control the total number of lines in the history using HISTSIZE

Append the following two lines to the .bash_profile
 

HISTSIZE=450
HISTFILESIZE=450

Change the history file name using HISTFILE

By default, history is stored in ~/.bash_history file. Add the following line to the .bash_profile to store the history command in .commandline_warrior file instead of .bash_history file.


# vi ~/.bash_profile
HISTFILE=/root/.commandline_warrior

Eliminate the repeated entry from history using HISTCONTROL

In the following example pwd was typed three times, when you do history, you can see all the 3 continuous occurrences of it. To eliminate duplicates, set HISTCONTROL to ignoredups as shown below.


# export HISTCONTROL=ignoredups --- after giving this if u type any comands repeately it shows only once in commandline


Erase duplicates across the whole history using HISTCONTROL

The ignoredups shown above removes duplicates only if they are consecutive commands. To eliminate duplicates across the whole history, set the HISTCONTROL to erasedups as shown below.


# export HISTCONTROL=erasedups  ------> previous commands will not go, only commands that come after this will have its effect.

Force history not to remember a particular command using HISTCONTROL

When you execute a command, you can instruct history to ignore the command by setting HISTCONTROL to ignorespace AND typing a space in front of the command as shown below.


# export HISTCONTROL=ignorespace  ------> and when u execute a particular command, put a space before the command and that command will not showing in the history.

example:- # export HISTCONTROL=ignorespace
 

#  service httpd stop [Note that there is a space at the beginning of service,to ignore this command from history]

Disable the usage of history using HISTSIZE

If you want to disable history all together and don’t want bash shell to remember the commands you’ve typed, set the HISTSIZE to 0 as shown below.
 

# export HISTSIZE=0

Ignore specific commands from the history using HISTIGNORE

Sometimes you may not want to clutter your history with basic commands such as pwd and ls. Use HISTIGNORE to specify all the commands that you want to ignore from the history.


Please note that adding ls to the HISTIGNORE ignores only ls and not ls -l. So, you have to provide the exact command that you would like to ignore from the history.

# export HISTIGNORE="pwd:ls:ls -ltr:"

after this history will not record pwd, ls and ls -ltr

Samba File Server / Install SWAT

I. Server

# yum install samba samba-common samba-client
# yum install xinetd samba-swat

Daemon: /usr/sbin/smbd

Configuration File:  vim /etc/samba/smb.conf

Ports: 445 ------ smbd (tcp) linux service
       137 ------ nmbd (udp) windows servicing


# vim /etc/samba/smb.conf


[global]
workgroup = MYGROUP
server string = Samba Server Version %v

hosts allow = 127. 10.21. 192.168.

log file = /var/log/samba/%m.log

security = user
passdb backend = tdbsam

## Public Share With Read-Wright


[SAM]
comment = SharE DiR
path = /ctechz-samba
# Public is for anonymous user
public = yes
#valid users = jeff manu
writable = yes
browseable = yes
printable = yes
write list = +groupname /
#            @groupname

# service smb restart
# chkconfig smb on

# mkdir /ctechz-samba  ----> Share directory

# If writable = Yes and public access only then give,
# setfacl -m u:nobody:rwx /ctechz-samba

## Check the status of the samba configuration file using testparm

# testparm
Load smb config files from /etc/samba/smb.conf
Processing section "[SAM]"
Loaded services file OK.
Server role: ROLE_STANDALONE
Press enter to see a dump of your service definitions

[global]
        workgroup = MYGROUP
        server string = Samba Server Version %v
        passdb backend = tdbsam
        log file = /var/log/samba/%m.log
        hosts allow = 127., 10.21., 192.168.
        cups options = raw


[SAM]
        comment = SharE DiR
        path = /ctechz-samba
        read only = No
        guest ok = Yes
        printable = Yes
           

II. Client side access

# smbclient //10.21.2.110/SAM   -----------> It will ask for password, just press enter to ignore it
Password:
Anonymous login successful
Domain=[MYGROUP] OS=[Unix] Server=[Samba 3.0.33-3.39.el5_8]
smb: \> ls
  .             D        0  Thu Dec 12 17:00:35 2013
  ..            D        0  Thu Dec 12 16:53:38 2013
  apr-0.9.4-24.5.i386.rpm  89620  Thu Dec 12 17:00:35 2013
  j             D        0  Thu Dec 12 17:00:37 2013

       50378 blocks of size 524288. 36841 blocks available

               
[root@localhost ~]# smbclient -N //10.21.2.110/SAM    

-----------> If we add -N it won't ask any password, It will neglect only for public access
Anonymous login successful
Domain=[MYGROUP] OS=[Unix] Server=[Samba 3.0.33-3.39.el5_8]
smb: \> ls
  .          D        0  Thu Dec 12 17:00:35 2013
  ..         D        0  Thu Dec 12 16:53:38 2013
  apr-0.9.4-24.5.i386.rpm  89620  Thu Dec 12 17:00:35 2013
  j          D        0  Thu Dec 12 17:00:37 2013

        50378 blocks of size 524288. 36841 blocks available
smb: \>

III. Configuration with a valid user's

# vim /etc/samba/smb.conf


[global]
workgroup = MYGROUP
server string = Samba Server Version %v

hosts allow = 127. 10.21. 192.168.

log file = /var/log/samba/%m.log

security = user
passdb backend = tdbsam

## Public Share With Read-Wright


[SAM]
comment = SharE DiR
path = /ctechz-samba
valid users = jeff manu
writable = yes
browseable = yes
printable = yes
write list = +groupname /
#            @groupname

# service smb restart
# chkconfig smb on

# mkdir /ctechz-samba

# useradd jeffy
# smbpasswd -a jeffy
New SMB password:
Retype new SMB password:
Added user jeffy.

# smbpasswd -e jeffy   -------> For enabling smb user
Enabled user jeffy.

If it is a valid user,
# chmod 700 /ctechz-samba
# setfacl -m u:jeffy:rwx /ctechz-samba

# service smb restart
# chkconfig smb on

IV. SMB Client for temporary mounting

# smbclient //serverIP/ShareName

# smbclient //serverIP/ShareName -U username 

------> If their is a valid user

# smbclient //10.21.2.110/SAM -U jeffy
Password:
session setup failed: NT_STATUS_LOGON_FAILURE
[root@localhost ~]#
[root@localhost ~]# smbclient //10.21.2.110/SAM -U jeffy
Password:
Domain=[LOCALHOST] OS=[Unix] Server=[Samba 3.0.33-3.39.el5_8]
smb: \> ls
  .             D        0  Thu Dec 12 17:00:35 2013
  ..            D        0  Thu Dec 12 16:53:38 2013
  apr-0.9.4-24.5.i386.rpm 89620  Thu Dec 12 17:00:35 2013
  j             D        0  Thu Dec 12 17:00:37 2013

       50378 blocks of size 524288. 36841 blocks available

If browsing from the client take a web browser and give the URL, Or take it in the file browser first


# smb://ServerIP/ShareName

V. Permenent Mounting

# vim /etc/fstab
//10.21.2.110/SAM  /ctechz-samba  cifs  defaults,username = jeffy, password = jeffy 0 0
# mount -a

# mount.cifs //10.21.2.110/SAM /ctechz-samba -o username=jeffy,password=jeffy
# vim /etc/fstab
//10.21.2.110/SAM  /ctechz-samba  cifs  defaults,credentials=/opt/smbpasswdFile:wq

# mount -a

# vim /opt/smbpasswdFile
username=jeffy
password=jeffy


# chmod 600 /opt/smbpasswdFile

Monday, 13 January 2014

How to configure syslog Server and Client

 Centralized log server (syslog server)

Suppose we have a server and 5 client machines. And we want to monitor the logs of all those client machines. In situations like this, we will use centralized server as a log server. Whatever events are happening in client machines, the logs will be sent to the server. So that we can monitor all the logs from a centralized server. We make use of syslog service for this.


 Features of syslog

1. Logs the daemon information to localhost
2. Logs the daemon information to Remote host
3. Logs the daemon information to List of users
4. Logs the daemon information to console

rsyslog.i386:Enhanced system logging and kernel message trapping daemon


sysklogd.i386:System logging and kernel message trapping daemons.


[root@localhost ~]# rpm -q sysklogd
sysklogd-1.4.1-46.el5
[root@localhost ~]#
[root@localhost ~]# rpm -qf /etc/syslog.conf
sysklogd-1.4.1-46.el5


# yum install sysklogd

# service syslog status
syslogd (pid  1929) is running...
klogd (pid  1932) is running...


I. Server Configuration (Where all logs will collect from remote machines)  ---- 192.168.0.140

Service name: syslog
configuration file: # vim /etc/sysconfig/syslog  ----- Server Configuration File


Port: 514

1. Open the /etc/sysconfig/syslog file and add "-r" option to the variable SYSLOGD_OPTIONS as shown below.

[root@server ~]# vim /etc/sysconfig/syslog
# Options to syslogd
# -m 0 disables 'MARK' messages.
# -r enables logging from remote machines
# -x disables DNS lookups on messages recieved with -r
# See syslogd(8) for more details
SYSLOGD_OPTIONS="-r -m 0"
# Options to klogd
# -2 prints all kernel oops messages twice; once for klogd to decode, and
# once for processing with 'ksymoops'
# -x disables all klogd processing of oops messages entirely
# See klogd(8) for more details
KLOGD_OPTIONS="-x"
#
SYSLOG_UMASK=077
# set this to a umask value to use for all log files as in umask(1).
# By default, all permissions are removed for "group" and "other".
[root@server ~]#

2. Restart the syslog service.
# service syslog restart


Shutting down kernel logger:  [  OK  ]
Shutting down system logger:  [  OK  ]
Starting system logger:       [  OK  ]
Starting kernel logger:       [  OK  ]

# chkconfig syslog on


II. Configuration for Client Machines ---- 192.168.0.108

service name: syslog
Configuration file: /etc/syslog.conf --- Client Configuration File

# vim /etc/syslog.conf

The configuration file /etc/syslog.conf has two parts
Eg:
*.info;mail.none;authpriv.none;cron.none  /var/log/messages
[selector field(Facility.priority)]        [action field]


 They are selector field and actions field. Selector field is again divided into two. Facilities and priorities.

Facility examples are (authpriv,kern,mail,local7 etc)


The priority is one of the following in ascending order: debug(0), info, notice, warning(warn), error(err), crit, alert,emerg(panic(7))


Actions can be regular files,console,list of users,remote machine ip etc.

1. Open the configuration file /etc/syslog.conf and add an entry to redirect the logs to the remote server.

# vim /etc/syslog.conf

# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.*                    /dev/console
*.* @192.168.0.140

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none /var/log/messages

# The authpriv file has restricted access.
authpriv.*                                /var/log/secure

# Log all the mail messages in one place.
mail.*                                    -/var/log/maillog

# Log cron stuff
cron.*                                   /var/log/cron

# Everybody gets emergency messages
*.emerg                                 *

# Save news errors of level crit and higher in a special file.
uucp,news.crit                         /var/log/spooler

# Save boot messages also to boot.log
local7.*                               /var/log/boot.log

# FTP Log
ftp.info                               /var/log/xferlog

# Cron log
cron.*                                /var/log/cron

# Save news errors of level crit and higher in a special file.
uucp,news.crit                       /var/log/spooler

if you want to check the cron logs from a client machine, go to the appropriate log file in server machine and watch the logs.


2. Restart the service
 

# service syslog restart

Checking:-
In server open a terminal and watch /var/log/messages and restart syslog service in client. You can see the log from clinet coming to server.

# tailf /var/log/messages  -----> In Server

now restart syslod service in client machine

Dec 11 07:59:51 192.168.0.108 kernel: Kernel logging (proc) stopped.
Dec 11 07:59:51 192.168.0.108 kernel: Kernel log daemon terminating.
Dec 11 07:59:51 192.168.0.108 exiting on signal 15
Dec 11 07:59:52 192.168.0.108 syslogd 1.4.1: restart.
Dec 11 07:59:52 192.168.0.108 kernel: klogd 1.4.1, log source = /proc/kmsg started.


Here 192.168.0.108 show the response coming from the client machine.

"Date Hostname Name_of_the_application: Actual_log_message"
 

Dec 11 07:59:51 192.168.0.108 kernel:KernelLogging(proc)stopped.
  Date           Hostname   Name_of_the_application:

                                Actual_log_message
  
Allow the port 514 and UDP connection in IPtables if you are using any.


# The Default rule i used is DROP, so you can use the rule as your own

# Allow incoming and outgoing syslogd services
# INCOMING

-A INPUT -i eth0 -p udp --dport 514 -m state --state NEW,ESTABLISHED -j ACCEPT

-A OUTPUT -o eth0 -p udp --sport 514 -m state --state ESTABLISHED -j ACCEPT


# OUTGOING
-A OUTPUT -o eth0 -p udp --dport 514 -m state --state NEW,ESTABLISHED -j ACCEPT

-A INPUT -i eth0 -p udp --sport 514 -m state --state ESTABLISHED -j ACCEPT