18
shell script to get cpu usage #!/bin/bash id=0; tot=0; p_id=0; p_tot=0; for ((i=0; $i < 100; ++i )) ; do p_id=$id; p_tot=$tot; x=`cat /proc/stat | grep -w cpu`; id=`echo $x | cut -d " " -f 5`; tot=0; for f in `echo $x`; do tot=$(($tot + $f)); done; echo "idle cpu usage% = "$((($id - $p_id)*100/($tot - $p_tot))); sleep 3; done shell script to kill a process by name #!/bin/bash YOUR_PROCESS_NAME=your_binary_name your_binary_name_process_id=`ps -eo pid,args | grep $YOUR_PROCESS_NAME | grep -v grep | cut -c1-6` if [ "$your_binary_name_process_id" == "" ]; then echo "your_binary_name not running" else

Shell Script Examples

Embed Size (px)

DESCRIPTION

shell script

Citation preview

Page 1: Shell Script Examples

shell script to get cpu usage

#!/bin/bash

id=0; tot=0; p_id=0; p_tot=0;

for ((i=0; $i < 100; ++i )) ; do

    p_id=$id; p_tot=$tot;    x=`cat /proc/stat | grep -w cpu`;    id=`echo $x | cut -d " " -f 5`;    tot=0;    for f in `echo $x`; do        tot=$(($tot + $f));    done;

    echo "idle cpu usage% = "$((($id - $p_id)*100/($tot - $p_tot)));

    sleep 3;done

shell script to kill a process by name

#!/bin/bash

YOUR_PROCESS_NAME=your_binary_name

your_binary_name_process_id=`ps -eo pid,args | grep $YOUR_PROCESS_NAME | grep -v grep | cut -c1-6`

if [ "$your_binary_name_process_id" == "" ]; then     echo "your_binary_name not running"else     echo "PID of "$YOUR_PROCESS_NAME " - "$your_binary_name_process_id     kill -9 $your_binary_name_process_id

Page 2: Shell Script Examples

     echo "killing your_binary_name"fi

shell script to get ip address

echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" echo "XXXXXXX   Getting the Network Interface Card Information    XXXXXXX"echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 

IPLIST=`/sbin/ifconfig | grep "Bcast" | sed -e "s/.*addr:\([^ ]*\).*/\1/"` echo    "These are the current interfaces found on this system:"cnt=0for ii in $IPLIST; do  let cnt=$cnt+1  iface=`/sbin/ifconfig | awk '$0 ~ str{print b}{b=$1}' str="$ii"`  echo "[$cnt] $iface ($ii)"  LISTIP=( "${LISTIP[@]}" $ii )  LISTIF=( "${LISTIF[@]}" $iface )doneecho ""echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 

## OUTPUT##[sgupta@rhel6x64 scripts]$ . ./get-ip-address.sh#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Page 3: Shell Script Examples

#XXXXXXX   Getting the Network Interface Card Information    #XXXXXXX#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX##These are the current interfaces found on this system:#[1] eth0 (192.168.22.64)#[2] virbr0 (192.168.122.1)##XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#

shell script to get kernel version

echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"echo "XXXXXXX          Retrieving the Kernel Information          XXXXXXX"echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

version=`uname -r | awk -F. '{ printf("%d.%d.%d\n",$1,$2,$3); }'`echo " "printf "Kernel Version : %s\n" $versionecho " "echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

getopts example in shell script################################################################# File          :   getopts.sh# Author        :   Saurabh Gupta# Created       :   10:16 AM 12/21/2011# Description   :   getopts example in shell script# Source        :   http://www.ccplusplus.com/p/shell-scipt.html# Note          :   ################################################################

function usage () {

Page 4: Shell Script Examples

    echo -e "Usage: $0 -e \"EXAMPLE\"  -d \"DESCRIPTION\"  -s \"SOURCE\" "}

clear

while getopts "e:d:s:" ARG;    do     case "${ARG}" in        e) EXAMPLE="${OPTARG}";;        d) DESCRIPTION="${OPTARG}";;        s) SOURCE="${OPTARG}";;    esac;done

[ -z "${EXAMPLE}" ] && { usage && exit 1; }

echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"echo "$EXAMPLE by $DESCRIPTION from $SOURCE"echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

## OUTPUT##XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#getopts example by 'Saurabh Gupta' from http://www.ccplusplus.com/#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#

get file modification time shell script#!/bin/bash########################################################################### Name    :    get-file-modification.sh## Author  :    Saurabh Gupta## Date    :    AM 09:25 12 January 2011## Desc    :    get file modification time shell script## Source  :    http://ccplusplus.com/p/shell-scipt.html

Page 5: Shell Script Examples

## Note    :#########################################################################if [ "x$1" == "x" ];then   echo "file name missing !!!"   echo "$0 <file-name>"   exitfiMODIFICATION_TIME=`ls -l $1`

GET_TIME_MONTH=`echo $MODIFICATION_TIME | awk '{print $6}'`DAY=`echo $MODIFICATION_TIME | awk '{print $7}'`HOUR_MIN=`echo $MODIFICATION_TIME | awk '{print $8}'`HOUR=`echo $HOUR_MIN | cut -d ':' -f1`MIN=`echo $HOUR_MIN | cut -d ':' -f2`

echo $GET_TIME_MONTH $DAY $HOUR $MIN

###############################################################    OUTPUT################################################################[sgupta@rhel6x64 scripts]$ ls -ltr get-cpu-usage.sh#-rw-rw-r--. 1 sgupta sgupta 662 Nov  1 22:38 get-cpu-usage.sh#[sgupta@rhel6x64 scripts]$################################################################# [sgupta@rhel6x64 scripts]$ ./get-file-modification get-cpu-usage.sh# Nov 1 22 38# [sgupta@rhel6x64 scripts]$##############################################################

shell script to get linux version#############################################################  Author      : Saurabh Gupta                             ##  Created     : 9:30 AM 23/11/2011                        ##  shell script to get Linux Version Running               ##  get linux version  shell script                         #############################################################

#!/bin/bashecho "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"echo "XXXXXXX          Retrieving Linux Version Information      

Page 6: Shell Script Examples

XXXXXXX"echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

CHECK_OS_VERSION=`uname -r | sed -e 's/\./ /g' | awk '{print $4}'`

echo "Your Linux OS Version is = $CHECK_OS_VERSION"echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"############################################################## OUTPUT#############################################################[sgupta@ivog-ks-200 scripts]$ . ./getOSVersion.shXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX          Retrieving Linux Version Information       XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYour Linux OS Version is = el5XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[sgupta@ivog-ks-200 scripts]$  #

Unixusing !$#@*% - pipeline

If you're familiar with UNIX, the pipeline, or pipe, is an integral part of everyday processing. Originally developed by Malcolm McIlroy, the pipeline allows you to redirect the standard output (stdout) of one command to become the standard input (stdin) of the following command in a single chained execution. Using the pipeline isn't limited to one instance per execution. Quite often, the stdout of one command is used as stdin of the following command,

Page 7: Shell Script Examples

and the subsequent stdout is redirected yet again as stdin to another command and so on.For example, one of the first things most UNIX administrators do on their systems during troubleshooting or daily checks is look at processes running currently on the system. Listing 1 shows such a check.

Listing 1. Example of a daily process check# ps –ef

UID PID PPID C STIME TTY TIME CMD root 1 0 0 Jul 27 - 0:05 /etc/init root 53442 151674 0 Jul 27 - 0:00 /usr/sbin/syslogd root 57426 1 0 Jul 27 - 0:00 /usr/lib/errdemon root 61510 1 0 Jul 27 - 23:55 /usr/sbin/syncd 60 root 65634 1 0 Jul 27 - 0:00 /usr/ccs/bin/shlap64 root 82002 110652 0 Jul 27 - 0:24 /usr/lpp/X11/bin/X -x abx -x dbe -x GLX -D /usr/lib/X11//rgb -T -force :0 -auth /var/dt/A:0-SfIdMa root 86102 1 0 Jul 27 - 0:00 /usr/lib/methods/ssa_daemon -l ssa0 root 106538 151674 0 Jul 27 - 0:01 sendmail: accepting connections root 110652 1 0 Jul 27 - 0:00 /usr/dt/bin/dtlogin -daemon root 114754 118854 0 Jul 27 - 20:22 dtgreet root 118854 110652 0 Jul 27 - 0:00 dtlogin <:0> -daemon root 131088 1 0 Jul 27 - 0:07 /usr/atria/etc/lockmgr -a /var/adm/atria/almd -q 1024 -u 256 -f 256 root 147584 1 0 Jul 27 - 0:01 /usr/sbin/cron root 155816 151674 0 Jul 27 - 0:04 /usr/sbin/portmap root 163968 151674 0 Jul 27 - 0:00 /usr/sbin/qdaemon root 168018 151674 0 Jul 27 - 0:00 /usr/sbin/inetd root 172116 151674 0 Jul 27 - 0:03 /usr/sbin/xntpd root 180314 151674 0 Jul 27 - 0:19 /usr/sbin/snmpmibd root 184414 151674 0 Jul 27 - 0:21 /usr/sbin/aixmibd root 188512 151674 0 Jul 27 - 0:20 /usr/sbin/hostmibd root 192608 151674 0 Jul 27 - 7:46 /usr/sbin/muxatmd root 196718 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.mountd root 200818 151674 0 Jul 27 - 0:00 /usr/sbin/biod 6 root 213108 151674 0 Jul 27 - 0:00 /usr/sbin/nfsd 3891 root 221304 245894 0 Jul 27 - 0:05 /bin/nsrexecd daemon 225402 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.statd root 229498 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.lockd root 241794 151674 0 Jul 27 - 0:51 /usr/lib/netsvc/yp/ypbind root 245894 1 0 Jul 27 - 0:00 /bin/nsrexecd root 253960 1 0 Jul 27 - 0:00 ./mflm_manager root 274568 151674 0 Jul 27 - 0:00 /usr/sbin/sshd -D root 282766 1 0 Jul 27 lft0 0:00 /usr/sbin/getty /dev/console root 290958 1 0 Jul 27 - 0:00 /usr/lpp/diagnostics/bin/diagd root 315646 151674 0 Jul 27 - 0:00 /usr/sbin/lpd root 319664 1 0 Jul 27 - 0:00 /usr/atria/etc/albd_server root 340144 168018 0 12:34:56 - 0:00 rpc.ttdbserver 100083 1 root 376846 168018 0 Jul 30 - 0:00 rlogind

Page 8: Shell Script Examples

cormany 409708 569522 0 19:29:27 pts/1 0:00 -ksh root 569522 168018 0 19:29:26 - 0:00 rlogind cormany 733188 409708 3 19:30:34 pts/1 0:00 ps -ef root 749668 168018 0 Jul 30 - 0:00 rlogind

The listing of the processes currently running on a system can be simple, as shown in Listing 1; however, most production systems run several more processes that make the output of ps much longer. To shorten the list to what you're looking for, redirect the standard output of ps –ef using a pipeline to grep to search for exactly what you want to see. Listing 2 shows the process list from Listing 1 redirected to grep to search for the strings "rpc" and "ksh."

Listing 2. Redirecting the process list to grep# ps –ef | grep –E "rpc|ksh"

root 196718 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.mountd daemon 225402 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.statd root 229498 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.lockd root 340144 168018 0 12:34:56 - 0:00 rpc.ttdbserver 100083 1 cormany 409708 569522 0 19:29:27 pts/1 0:00 -ksh cormany 733202 409708 0 19:52:20 pts/1 0:00 grep -E rpc|ksh

Using the pipeline can be much more complicated when you redirect stdout to stdin several times. In the following example, the previous ps and grep example is expanded to pipeline the stdout to another grep to exclude any previous strings found that includes "grep" or "ttdbserver." When the final grep operation has finished, the stdout is redirected again using a pipeline to anawk statement to print any of the processes found with a process identifier (PID) larger than 200,000:# ps –ef | grep –E "rpc|ksh" | grep -vE "grep|rpc.ttdbserver" | awk -v _MAX_PID=200000 '{if ($2 > _MAX_PID) {print "PID for process",$8,"is greater than", _MAX_PID}}'

PID for process /usr/sbin/rpc.statd is greater than 200000PID for process /usr/sbin/rpc.lockd is greater than 200000PID for process -ksh is greater than 200000

Figure 1 provides a graphical representation of the command's stdout redirecting to stdin for the subsequent command.

Page 9: Shell Script Examples

Figure 1. Pipeline example

Data redirection with >, >>, <, and <<

Another important aspect of executing commands from the command-line interface (CLI) is the ability to write various outputs to a device or to read input into a command from another device. To write the output of a command, append the greater-than symbol (> or >>) and the target file name or device desired after the command to be executed. If the target file doesn't exist and you have Write permissions to the target directory, > and >> create the file with permissions of your umask and write the command's output to the newly created file. If, however, the file does exist, > attempts to open the file and overwrite the entire contents. If you would rather append to the file, simply use >>. Think of it as the flow of output data moving from the command on the left moving to the destination file on the right (that is, <cmd> -> <output> -> <file>).The following example executes the ps –ef and redirects the output to a file namedps_out:

# ps –ef | grep –E "rpc|ksh" > ps_out

Data redirection with >, >>, <, and <<

Page 10: Shell Script Examples

The following code executes the earlier extended pipeline example and redirects the output to the same file—ps_out—but appends to the current data:

# ps –ef | grep –E "rpc|ksh" | grep -vE "grep|rpc.ttdbserver" |

awk -v _MAX_PID=200000 '{if ($2 > _MAX_PID) {print "PID for

process",$8,"is greater than", _MAX_PID}}' >> ps_out

Listing 3 shows the output from the last two redirections.

Listing 3. Output from subsequent redirections

# cat ps_out

root 196718 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.mountd

daemon 225402 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.statd

root 229498 151674 0 11:00:27 - 0:00 /usr/sbin/rpc.lockd

root 340144 168018 0 12:34:56 - 0:00 rpc.ttdbserver 100083 1

cormany 409708 569522 0 19:29:27 pts/1 0:00 -ksh

cormany 733202 409708 0 19:52:20 pts/1 0:00 grep -E rpc|ksh

PID for process /usr/sbin/rpc.statd is greater than 200000

PID for process /usr/sbin/rpc.lockd is greater than 200000

PID for process -ksh is greater than 200000

When redirecting output with > alone, only the stdout of the command is redirected. Keep in mind that with computing, there is stdout as well as stderr: The former is represented as 1, while stderr is 2. Redirecting output in UNIX is no different. Simply place the desired output type before the > (for example, 1>, 2>) to tell the shell where to route the output.Listing 4 attempts to list files fileA.tar.bz2 and fileC.tar.bz2. Unfortunately, as shown in the first command (ls), fileC.tar.bz2 doesn't exist. Thankfully, we remembered to separate stdout into ls.out and stderr into ls.err.

Listing 4. Listing the files fileA.tar.bz2 and fileC.tar.bz2

# ls

fileA.tar.bz2 fileAA.tar.bz2 fileB.tar.bz2 fileBB.tar.bz2

# ls fileA.tar.bz2 fileC.tar.bz2 1> ls.out 2> ls.err

Page 11: Shell Script Examples

# cat ls.out

fileA.tar.bz2

# cat ls.err

ls: 0653-341 The file fileC.tar.bz2 does not exist.

The same rules apply in AIX with > and >> on stdout and stderr. For example, the same output files can be used for future tests, as Listing 5 shows.

Listing 5. Using output files for future tests

# ls fileB.tar.bz2 fileD.tar.bz2 1>> ls.out 2>> ls.err

# cat ls.out

fileA.tar.bz2

fileB.tar.bz2

# cat ls.err

ls: 0653-341 The file fileC.tar.bz2 does not exist.

ls: 0653-341 The file fileD.tar.bz2 does not exist.

There are times when you may need to have both stdout and stderr written to the same file or device. You can do this in either of two ways. The first method is to direct 1> and 2> to the same file:

# ls fileA.tar.bz2 fileC.tar.bz2 1> ls.out 2> ls.out

# cat ls.out

fileA.tar.bz2

ls: 0653-341 The file fileC.tar.bz2 does not exist.

The second method is a simpler and quicker way to accomplish the same thing and is used more frequently by experienced UNIX users:

# ls fileA.tar.bz2 fileC.tar.bz2 > ls.out 2>&1

# cat ls.out

fileA.tar.bz2

ls: 0653-341 The file fileC.tar.bz2 does not exist.

Page 12: Shell Script Examples

Let's break the statement down. First, ls fileA.tar.bz2

fileC.tar.bz2 is executed. The stdout is redirected to ls.out with > ls.out, and stderr is redirected to the same file to which stdout is redirected (ls.out) with 2>&1.Remember that you can redirect output to files as well as other devices. You can redirect data to printers, floppy disks, Terminal Types (TTYs), and various other devices. For example, if you wanted to send a message to a single user on all sessions (or TTYs), you could just loop through who and redirect a message to the TTYs if you have adequate permissions, as shown inListing 6.

Listing 6. Redirecting a message to a TTY

# for _TTY in 'who | grep "cormany" | awk '{print $2}''

> do

> _TTY="/dev/${_TTY}"

> echo "Sending message to cormany on ${_TTY}"

> echo "Test Message to cormany@${_TTY}" > ${_TTY}

> done

Sending message to cormany on /dev/pts/13

Test Message to cormany@/dev/pts/13

Sending message to cormany on /dev/pts/14

Subshells

Sometimes, you need to execute several commands together. For example, if you want to perform a specific action in a different directory, you could use the code in Listing 8.

Listing 8. Execute several commands at the same time# pwd/home/cormany

# cd testdir

# tar –cf ls_output.tar ls.out?

Page 13: Shell Script Examples

# pwd/home/cormany/testdir

This works, but note that after the execution of theses steps, you're no longer in your original directory. By placing the commands into their own subshell, they execute as a single instance of the subshell. Listing 9 shows the same idea executed using a subshell.

Listing 9. Execute several commands at the same time using a subshell# pwd/home/cormany

# (cd testdir ; tar -cf ls_output.tar ls.out?)

# pwd/home/cormany

The test command

The test command, [ ], and [[ ]]When writing a shell script or programming in any modern language, the ability to evaluate expressions or values is essential to competent programs. UNIX has it covered as always with the test command. As the test man page states, the testcommand evaluates expression parameters and, if the expression value is True, returns a zero (True) exit value. For more information on the definition of test and all the available conditions, see the test man page.To use the test command, simply provide the command with the appropriate flag and file name. When test has evaluated the expression, you're returned to a command prompt, where you can verify the return code, as shown in Listing 10.

Listing 10. Verify return code# ls –l-rwxr-xr-x 1 cormany atc 786 Feb 22 16:11 check_file-rw-r--r-- 1 cormany atc 0 Aug 04 20:57 emptyfile

# test -f emptyfile# echo $?0

# test -f badfilename# echo $?1

Page 14: Shell Script Examples

As stated in the definition, test returns a zero exit value if the expression value was True or a non-zero exit value (that is, 1). InListing 10, the file emptyfile was found, so test returned 0; the file badfilename was not found, so 1 was returned.Another way to use the test command is to place the expression to evaluate within single brackets ([ ]). Using the testcommand or replacing it with [ ] returns the same value, as they are identical executions:# [ -f emptyfile ]# echo $?0

# [ -f badfilename ]# echo $?1

Using single brackets ([ ]) versus double brackets ([[ ]]) is a personal preference and really depends on how you've been taught commands and shell scripting. But keep in mind that there are some differences between the two evaluations. Although [ ] and [[ ]] use the same test operators during evaluation, they use different logical operators.

Private and public key pairs for SSH

To help validate identities, SSH has a key management capacity and related agents. When configured with public key authentication, your key proves your identity to remote SSH hosts. An SSH-based identity consists of two parts: a public key and a private key. The private SSH key is the user's identity for outbound SSH connections and should be kept confidential. When a user initiates an SSH or SCP session to a remote host or server, he or she is said to be the SSH client. Through a mathematical algorithm, a private key is like your electronic identification card; the public key is like the lock or gate mechanism that you present your ID card to. Your private key says, "This really is Fred Smythe"; the public key says, "Yes, you are indeed the real Fred Smythe; you are now authenticated: Please enter."Your public key represents who you will allow inbound access to through your gate or lock. Public keys need not be kept secret; they cannot be used to compromise a system or for unwarranted access into a system. On a Linux or UNIX system, these private and public key pairs are stored in ASCII text files; on Windows systems, some programs store the key pairs as text files, some in the Windows registry.Multiple identifications using multiple private keys can be created with an SSH Protocol 2 configuration. Let's look at how to generate, set up, and configure an SSH private and public key pair on typical Linux hosts (see Figure 5).

Page 15: Shell Script Examples

Figure 5. Diagram of the SSH private-public key pair transactions, as defined within the SSH defined architecture model 

Page 16: Shell Script Examples