Tuesday, August 23, 2016

find files with and without matching string in Linux



****************************************************************************
Find all files without string "successfully completed" in directory
****************************************************************************
find /home/oracle/test -type f | xargs grep -L "successfully completed"


****************************************************************************
Find all files with macthing string "successfully completed" in directory
****************************************************************************
find /home/oracle/test -type f | xargs grep -l -n "successfully completed"

Monday, March 14, 2016

change hostname on a linux machine -centos

I want to change my Linux hostname from Linux01 to Linux03

[root@Linux01 Desktop]# vi /etc/sysconfig/network

[root@Linux01 Desktop]# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=Linux03

************************************************************************
YOU MIGHT ALSO WANT TO CHECK THE /ETC/HOSTS FILE FOR IP SETTINGS
************************************************************************


RESTART THE SERVER NOW. AFTER REBOOT

[oracle@Linux03 Desktop]$ hostname
Linux03

[oracle@Linux03 Desktop]$

Configure gmail to send emails from your Linux machine

In this how to, I assume you already have a running CentOS 6.7 server. I am going to share how to install and setup ssmtp.x86_64 0:2.61-22.el5 on CentOS 6.7 version. This how to has been tested with mutt-1.5.20-7 as a mail client.

First, we must ensure everything are up to date by running the following commands: –

[root@Linux01 Desktop]# wget -c http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm

Resolving dl.fedoraproject.org... 209.132.181.26, 209.132.181.25, 209.132.181.23, ...
Connecting to dl.fedoraproject.org|209.132.181.26|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 12232 (12K) [application/x-rpm]
Saving to: “epel-release-5-4.noarch.rpm”

100%[==================================================================================================================>] 12,232      --.-K/s   in 0s    

2016-02-22 09:50:52 (93.2 MB/s) - “epel-release-5-4.noarch.rpm” saved [12232/12232]

[root@Linux01 Desktop]# rpm -ivh epel-release-5-4.noarch.rpm
Preparing...                ########################################### [100%]
   1:epel-release           ########################################### [100%]
[root@Linux01 Desktop]# yum -y install ssmtp
Loaded plugins: fastestmirror, refresh-packagekit, security
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirror-centos.hostingswift.com
 * epel: archive.linux.duke.edu
 * extras: mirror.sesp.northwestern.edu
 * updates: mirror-centos.hostingswift.com
base                                                                                                                                 | 3.7 kB     00:00  
epel                                                                                                                                 | 3.6 kB     00:00  
epel/primary_db                                                                                                                      | 2.9 MB     00:01  
extras                                                                                                                               | 3.4 kB     00:00  
updates                                                                                                                              | 3.4 kB     00:00  
updates/primary_db                                                                                                                   | 3.9 MB     00:03  
Resolving Dependencies
--> Running transaction check
---> Package ssmtp.x86_64 0:2.61-22.el5 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================================
 Package                            Arch                                Version                                     Repository                         Size
============================================================================================================================================================
Installing:
 ssmtp                              x86_64                              2.61-22.el5                                 epel                               55 k

Transaction Summary
============================================================================================================================================================
Install       1 Package(s)

Total download size: 55 k
Installed size: 93 k
Downloading Packages:
:
:
:
:                                                                                                             1/1

Installed:
  ssmtp.x86_64 0:2.61-22.el5                                                                                                                              

Complete!

[root@Linux01 Desktop]# help sendmail
bash: help: no help topics match `sendmail'.  Try `help help' or `man -k sendmail' or `info sendmail'.
[root@Linux01 Desktop]# man -k sendmail
sendmail             (1)  - Postfix to Sendmail compatibility interface
sendmail             (8)  - Postfix to Sendmail compatibility interface


[root@Linux01 Desktop]# cd /etc/ssmtp
[root@Linux01 ssmtp]# ls -ll
total 8
-rw-r--r--. 1 root root  200 Apr 16  2001 revaliases
-rw-r-----. 1 root mail 1371 Jan 12  2015 ssmtp.conf
[root@Linux01 ssmtp]# mv /etc/ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf.ori
[root@Linux01 ssmtp]# touch /etc/ssmtp/ssmtp.conf
[root@Linux01 ssmtp]# mv /etc/ssmtp/revaliases /etc/ssmtp/revaliases.orig
[root@Linux01 ssmtp]# touch /etc/ssmtp/revaliases
[root@Linux01 ssmtp]# vi /etc/ssmtp/ssmtp.conf
[root@Linux01 ssmtp]# vi /etc/ssmtp/revaliases

Next, we will configure sSMTP to forward email to any shared hosting server either running CPanel or DirectAdmin.

Include the following below in /etc/ssmtp/ssmtp.conf file: –

root=postmaster
mailhub=mail.yourdomain.com:587
Hostname=localhost
FromLineOverride=YES
AuthUser=abcd@yourdomain.com
AuthPass=YourPassWord
UseSTARTTLS=YES

Include the following below in /etc/ssmtp/revaliases file: –

root:username@yourdomain.com:mail.yourdomain.com:587

Include the following below in /root/.muttrc file: –

set envelope_from=yes
set from="username@yourdomain.com"
set realname="Prefer From Display"

You can use GMAIL server to forward your mails. Use below seetings to configure the GMAIL SMTP

If you an option to forward email to Gmail server, you can configure using steps below.

Replace previous configuration to below in /etc/ssmtp/ssmtp.conf file: –

root=postmaster
mailhub=smtp.gmail.com:587
Hostname=abcd@gmail.com
FromLineOverride=YES
AuthUser=abcd@gmail.com
AuthPass=YourPassWord
UseSTARTTLS=YES

Replace previous configuration to below in /etc/ssmtp/revaliases file: –

root:username@gmail.com:smtp.gmail.com:587

Replace previous configuration to below in /root/.muttrc file: –

set envelope_from=yes
set from="abcd@gmail.com"
set realname="Prefer From Display"

Next, you can start sending email using your preferred email server using command below: –

[root@Linux01 ~]# echo "Testing outgoing email" | mutt -s "Testing" arvind.toorpu@nelnet.net
bash: mutt: command not found
[root@Linux01 ~]# yum install mutt
Loaded plugins: fastestmirror, refresh-packagekit, security
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirror-centos.hostingswift.com
 * epel: mirror.steadfast.net
 * extras: mirror.sesp.northwestern.edu
 * updates: mirror-centos.hostingswift.com
Resolving Dependencies
--> Running transaction check
---> Package mutt.x86_64 5:1.5.20-7.20091214hg736b6a.el6 will be installed
--> Processing Dependency: urlview for package: 5:mutt-1.5.20-7.20091214hg736b6a.el6.x86_64
--> Processing Dependency: libtokyocabinet.so.8()(64bit) for package: 5:mutt-1.5.20-7.20091214hg736b6a.el6.x86_64
--> Running transaction check
---> Package tokyocabinet.x86_64 0:1.4.33-6.el6 will be installed
---> Package urlview.x86_64 0:0.9-7.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================================
 Package                             Arch                          Version                                                Repository                   Size
============================================================================================================================================================
Installing:
 mutt                                x86_64                        5:1.5.20-7.20091214hg736b6a.el6                        base                        1.2 M
Installing for dependencies:
 tokyocabinet                        x86_64                        1.4.33-6.el6                                           base                        428 k
 urlview                             x86_64                        0.9-7.el6                                              base                         24 k

Transaction Summary
============================================================================================================================================================
Install       3 Package(s)

Total download size: 1.7 M
Installed size: 5.6 M
Is this ok [y/N]: y
Downloading Packages:
(1/3): mutt-1.5.20-7.20091214hg736b6a.el6.x86_64.rpm                                                                                 | 1.2 MB     00:00  
(2/3): tokyocabinet-1.4.33-6.el6.x86_64.rpm                                                                                          | 428 kB     00:00  
(3/3): urlview-0.9-7.el6.x86_64.rpm                                                                                                  |  24 kB     00:00  
------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                       1.5 MB/s | 1.7 MB     00:01  
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : tokyocabinet-1.4.33-6.el6.x86_64                                                                                                         1/3
  Installing : urlview-0.9-7.el6.x86_64                                                                                                                 2/3
  Installing : 5:mutt-1.5.20-7.20091214hg736b6a.el6.x86_64                                                                                              3/3
  Verifying  : 5:mutt-1.5.20-7.20091214hg736b6a.el6.x86_64                                                                                              1/3
  Verifying  : urlview-0.9-7.el6.x86_64                                                                                                                 2/3
  Verifying  : tokyocabinet-1.4.33-6.el6.x86_64                                                                                                         3/3

Installed:
  mutt.x86_64 5:1.5.20-7.20091214hg736b6a.el6                                                                                                            

Dependency Installed:
  tokyocabinet.x86_64 0:1.4.33-6.el6                                               urlview.x86_64 0:0.9-7.el6                                            

Complete!
[root@Linux01 ~]# vi /root/.muttrc
[root@Linux01 ~]# clear

[root@Linux01 ~]# echo "Testing outgoing email" | mutt -s "Testing" abcd@gmail.com
[root@Linux01 ~]# clear


Finally, with all the configuration above I hope you are able to use and enjoy your sSMTP to send an email. Thank you.

script to check if the file exists

#!/usr/bin/ksh
## This is a simple script to check if the file exists in a dir or not
## Created by : Arvind Reddy
## This will prompt for

echo " file name please : "
read FILENAME;
export dataDir=/u01/app/oracle/dpump;
sourceFile=SCOTT.dmp;

cd /u01/app/oracle/dpump;
echo `pwd`

##Did we get a file?

if [ -e ${dataDir}/${sourceFile} ];then
echo "Found file !! "
else
echo " No file found !!! "
fi

Linux os level backup and cleanup cmds

REMOVE ALL FILES OLDER THAN 15 DAYS:

[oracle@Linux01 dpump]$
find /u01/app/oracle/dpump/*.dmp -mtime +15 -exec rm {} \;

GZIP ALL FILES OLDER THAN 15 DAYS: (This will make individual GZIP files)

[oracle@Linux01 dpump]$
find /u01/app/oracle/dpump/*.dmp -mtime +90 -exec gzip {} \;


MOVE FILES OLDER THAN 15DAYS

find /home/arvind -maxdepth 1 -iname "*.txt" -mtime -15 -exec mv {} /home/arvind/test1/ \;


COUNT FILES OLDER THAN 90 DAYS

find /u01/app/oracle/admin/adump/*.aud -mtime +90 | exec wc -l {} \;


TAR ALL FILES OLDER THAN 15 DAYS: 
(This will make 1 TAR FILE With date format at end)

[oracle@Linux01 dpump]$

find /u01/app/oracle/admin/ORCL/adump/*.aud -mtime +90 | xargs  tar -czvPf  /u01/app/oracle/admin/ORCL/adump/ARCH_AUD_$(date +%F).tar.gz

Wednesday, February 24, 2016

Convert all text in a file from UPPER to lowercase on LINUX

Convert all text in a file from UPPER to lowercase

To translate or delete characters use tr command. The basic syntax is:

Lets create a simple text file with mix of lower and upper case chars :
oracle@Linux01:[/u01/app/oracle/admin/bin] $ vi TGTGTG.txt

oracle@Linux01:[/u01/app/oracle/admin/bin] $ cat TGTGTG.txt
as This IS in Upper

Here I am passing the TGTGTG.txt as inprt and converting the output to lower case:
oracle@Linux01:[/u01/app/oracle/admin/bin] $ tr '[:upper:]' '[:lower:]' < TGTGTG.txt > output.txt

oracle@Linux01:[/u01/app/oracle/admin/bin] $ cat output.txt
as this is in upper

Here I am passing the TGTGTG.txt as inprt and converting the output to UPPER case:
oracle@Linux01:[/u01/app/oracle/admin/bin] $ tr '[:lower:]' '[:upper:]' < TGTGTG.txt > output_UP.txt

oracle@Linux01:[/u01/app/oracle/admin/bin] $ cat output_UP.txt
AS THIS IS IN UPPER

oracle@Linux01:[/u01/app/oracle/admin/bin] $

EXIT status messages in NIX

Exit Status

By default in Linux if particular command/shell script is executed, it return two type of values which is used to see whether command or shell script executed is successful or not.

(1) If return value is zero (0), command is successful.
(2) If return value is nonzero, command is not successful or some sort of error executing command/shell script.

This value is know as Exit Status.

But how to find out exit status of command or shell script?
Simple, to determine this exit Status you can use $? special variable of shell.

For e.g. If I want to remove a non-existing file

$ rm ABCD
rm: cannot remove `ABCD': No such file or directory
and after that if you give command
$ echo $?
it will print nonzero value to indicate error. Now give command

$ ls
$ echo $?
It will print 0 to indicate command is successful.

Exercise
Try these exit status and check for yourself:

$ expr 1 + 3
$ echo $?

$ echo Welcome
$ echo $?

$ wildwest canwork?
$ echo $?

$ date
$ echo $?

$ echon $?
$ echo $?

Tuesday, February 16, 2016

Uppercase to lowercase or vice versa in BASH

Uppercase to lowercase or vice versa

The bash version 4.x+ got some interesting new features. Type the following commands to convert $VAR into uppercase:


VAR="All THIS will be in UppER Case"
echo "${VAR^^}"

Sample outputs:

ALL THIS WILL BE IN UPPER CASE

Type the following commands to convert $VAR into lowercase:


VAR="All THIS will be in lOWer Case"
echo "${VAR,,}"

Sample outputs:

all this will be in lower case

Thursday, November 19, 2015

Shell Script for log file cleanup

Problem :

lets find the list of file that are older than 30days. That has extension of *.log

-rw-r--r-- 1 oracle oinstall        513 Jul 28 08:27 change_pass.sql
-rw-r----- 1 oracle oinstall     188416 Jul 30 11:37 testnetlink.dmp
-rw-r--r-- 1 oracle oinstall       1477 Jul 30 11:37 impi_temp.log
-rw-r--r-- 1 oracle oinstall       1433 Jul 30 12:58 impi1_temp.log

Requirement :

Now I want to remove the files that are older than 30 days and at same time I want keep a log of the files that are being deleted.


### Script starts here ###

#!/usr/bin/ksh

cd /u01/app/oracle/dpump; ## location where I want to cleanup the log files
echo " we are now in : `pwd`"


for FILE in `find /u01/app/oracle/dpump/*.log -mtime +30`
   do echo $FILE
   rm -f $FILE ##2>/dev/null # Gets rid of directory or permission errors
done  2>&1 1> /u01/app/oracle/dpump/log.txt




sample output of log file :

lets see what is captured in cleanup log file.

cat u01/app/oracle/dpump/log.txt

u01/app/oracle/dpump/AUDIT_PART1.log
/u01/app/oracle/dpump/impi1_temp.log
/u01/app/oracle/dpump/impi_temp.log
/u01/app/oracle/dpump/test1.log

Thursday, November 5, 2015

shell script to find files in a directory



####This script starts here ####
###This script cheks if the a file exist current Directory ##
## script will propmt for filename ##
#!bin/ksh

echo "eneter Filename :"
read DUMPFILE;
echo " **** checking if the File exists **** "
if [ -e ${DUMPFILE} ];
then
echo " **** Given file exists in directory `pwd` ****"
else
echo " **** ERRR : Given file does not exist in directory `pwd` ****"
fi


Lets see how to use this code :



atoorpu@Linux01:[~/scripts] $ ls -al testfile
ls: testfile: No such file or directory

atoorpu@Linux01:[~/scripts] $ . check_file.sh
eneter Filename :
testfile
**** checking if the File exists ****
**** ERRR : Given file does not exist in directory /home/atoorpu/scripts ****

atoorpu@Linux01:[~/scripts] $ touch testfile

atoorpu@Linux01:[~/scripts] $ ls -al testfile
-rw-rw-r-- 1 atoorpu atoorpu 0 Oct 23 14:03 testfile

atoorpu@Linux01:[~/scripts] $ . check_file.sh
eneter Filename :
testfile
**** checking if the File exists ****
**** Given file exists in directory /home/atoorpu/scripts ****

atoorpu@Linux01:[~/scripts] $
atoorpu@Linux01:[~/scripts] $

using UNIX pipes to export oracle table and compress

Script explanation:

This script is to export the dump file and compress the exported data using UNIX pipes. This method is best suited when there is not enough space on disk. The file exported and compressed at same time, this method will not require much space while exporting the dumpfile.

Note: Using of UNIX pipe's will also speed up the export process & yes there will consume a good amount of CPU.



#!/usr/bin/ksh:


#### This script will export the dumpfile and compress at same time using linux pipe

#### You can use normal gunzip cmd to unzip the zipped file

####



export mydate=`date "+%d%b%Y"`;

export TEST_BAK=TEST_MKNOD_"$mydate";

DUMPFILE=$TEST_BAK".dmp";  ## Setting dumpfile name here

LOGFILE=$TEST_BAK".log";            ## Setting logfile name here

DPUMP=/u01/app/oracle/dpump;                  ## Setting target directory for dump & log







## create exp

## you can use the pipe for compress the file

mknod $DPUMP/exp.pipe p



## compress dmp with file using pipe

gzip < $DPUMP/exp.pipe > $DPUMP/$DUMPFILE.gz &



exp USERNAME/PASSWORD@ORCL file="$DPUMP"/exp.pipe log="$DPUMP/$LOGFILE" tables=TEST statistics=none



## remove the pipe created

rm $DPUMP/exp.pipe



echo $' \n ';



echo " export completed "

Shell script - Check if the files exists in a file


This is a simple script to look for a file in a given location.



















#!/usr/bin/ksh
 
echo " File name please : "
read FILENAME;
dataDir=/u01/app/oracle/dpump; ### Directory to look for a file ###
sourceFile=SCOTT.dmp; ### file name to search for ###
 
cd /u01/app/oracle/dpump;
echo " Present directory : " `pwd`"";
 
##Did we get a file?
 
if [ -e ${dataDir}/${sourceFile} ];
then
echo "Found file !! "

else
echo " No file found !!! "

fi

Backup unix files and folders using tar - compress and backup files





Because of various reasons some of which hearken back to the era of tape drives, Unix uses a program named tar to archive data, which can then be compressed with a compression program like gzip, bzip2, 7zip, etc.



In order to "zip" a directory, the correct command would be



tar -zcvf archive.tar.gz directory/

This will tell tar to c (create) an archive from the files in directory (tar is recursive by default), compress it using the z (gzip) algorithm, store the output as a f (file) named archive.tar.gz, and v (verbosely) list all the files it adds to the archive.



To decompress and unpack the archive into the current directory you would use



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

ARCHIVE FOLDER CONTENTS & CREATE NEW BACKUP FILE:

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



atoorpu@linux01:[~] $ tar -zcvf Output_File.tar.gz SourceFile

ziptest/

ziptest/readme1.txt



--->>> Output_File.tar.gz   >>>   output file

--->>> SourceFile >>> source directory



atoorpu@linux01:[~] $ ls

oswbb733.tar                       patches                readme.txt  sys_checker.sh  ziptest.tar.gz

p19543113_851499_Linux-x86-64.zip  pitt_4_21_2014.dmp.gz  scripts     ziptest1



LIST CONTENTS OF TAR FILE:



atoorpu@linux01:[~] $ tar -ztvf ziptest.tar.gz

drwxrwxr-x atoorpu/atoorpu   0 2015-08-27 14:16:41 ziptest/

-r--r--r-- atoorpu/atoorpu  50 2015-08-27 14:14:20 ziptest/readme1.txt



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

EXTRACT/UNTAR THE FILE USE :

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



To extract one or more members from an archive, enter:

$ tar -zxvf {file.tar.gz}



If your tarball name is backup.tar.gz, enter the following at a shell prompt to extract files:

$ tar -zxvf backup.tar.gz



To extract resume.doc file from backup.tar.gz tarball, enter:

$ tar -zxvf backup.tar.gz resume.doc


Simple Shell script to execute a sql from UNIX






This is a simple shell script to execute a sql from UNIX shell script.





#!/usr/bin/ksh



export ORACLE_SID=ORCL

export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1

export PATH=$ORACLE_HOME/bin:/usr/local/bin:$PATH

export mydate=`date "+%d%b%Y"`





echo " ************** EXECUTING SQL STARTS HERE ************ "



sqlplus -s USERNAME/PASSWORD@ORCL > /u01/app/oracle/dpump/test.log  <<EOF



SET SERVEROUTPUT ON;

SET FEED OFF;



select name from v\$database;



SET SERVEROUTPUT OFF;

EOF



echo " ************** END OF SQL HERE ************ "





Shell script to export a schema and move it to different server





#!/usr/bin/ksh



### local_path is the data pump directory in local server.

### remote_path is the target location in the remote server.

### RMTSERVER is the ip adress (or) hostname of remote host.



export mydate=`date "+%d%b%Y"`;

local_path=/u01/oracle/DPUMP;

RMTSERVER=10.176.33.99;  ### We are hard coding the remote server here ###

remote_path=/u01/app/oracle/dpump;



## echo "Enter Password:"

##read PASSWORD;



echo "Enter SCHEMA name:"

read SCHEMA;





expdp EXPORT_USER/PASSWORD directory=DPUMP dumpfile="$SCHEMA"_"$mydate".dmp logfile="$SCHEMA"_exp"$mydate".log schemas="$SCHEMA" COMPRESSION=ALL



echo "Export Completed"



cd /u01/oracle/DPUMP;

echo `pwd`

export DUMP_FILE="$SCHEMA"_"$mydate".dmp

sftp $RMTSERVER  <<EOF



cd $remote_path;

put $DUMP_FILE



EOF



Unix Permissions and values







Change UNIX permissions by using the simple command.


Syntax:


chmod 775 filename or foldername


Example:



chmod 775 test.txt


In the above cmd we are changing the permission of test file to 775 (Read/Write/Execute).


Below is the table of permissions.



UNIX Permissions:















ValuePermissionDirectory Listing
0No read, no write, no execute---
1No read, no write, execute--x
2No read, write, no execute-w-
3No read, write, execute-wx
4Read, no write, no executer--
5Read, no write, executer-x
6Read, write, no executerw-
7Read, write, executerwx


rwx rwx rwx = 111 111 111
rw- rw- rw- = 110 110 110
rwx --- --- = 111 000 000

and so on...

rwx = 111 in binary = 7
rw- = 110 in binary = 6
r-x = 101 in binary = 5
r-- = 100 in binary = 4

exception handling in shell script

Problem :

I have a a situation where I want to execute script1 and then script 2 in sequence.. But at same time want to make sure if script1 fails, script2 doesn't get executed. In this case I want to explain how to break the script if there were some errors in

lets create twp scripts script1.sh as below

#!bin/ksh
echo " this is with in script 1 "

create script2.sh as below

#!bin/ksh
echo " this is with in script 2 "


now lets create another script handle_errors.sh as below

#!bin/ksh
script1.sh
rc=$?
if [ ${rc} -eq 0 ];then
echo "script1 pass, starting script2"
  script2.sh
  rc=$?
  if [ ${rc} -eq 0 ];then
   echo "script2 pass"
  else
   echo "script2 failed"
  fi
else
 echo "script1 failed"
fi

Sample output :

atoorpu@Linux01:[~/scripts] $ . handle_errors.sh
this is from script1
script1 passed, starting script2 now !!
 this is from script2
script2 has passed
atoorpu@Linux01:[~/scripts] $


now if  you want to mess around you can update one of script1 or script2 :

I changed script1.sh to below now :

#/bin/sh
this is from script1"


If you see here the script has failed on script1 and it didn't go to script2 

atoorpu@Linux01:[~/scripts] $ . handle_errors.sh
-bash: /home/atoorpu/scripts/script1.sh: line 2: unexpected EOF while looking for matching `"'
-bash: /home/atoorpu/scripts/script1.sh: line 4: syntax error: unexpected end of file
script1 failed !!