Category Archives: Scripts

Script to create mount points in LVM

Here is a little script to create a mount point using CSV file which has a mount point name, size, and VG name.

Script to create mount points in LVM

Caution : Use script on your own risk!

Do not use it on production servers. Test it and use it on newly built/dev/testing servers.

Below is the script code. Save it under /tmp/lvm_script.sh and also save your CSV file under the same directory with the name list.csv

CSV file format is mount point name,size in GB,VG name. For example : /data,10,data_vg

Script code :

#Script to create mount point using CSV file
#Author : Shrikant Lavhate (kerneltalks.com)
#Save CSV file as list.csv in current working directory with format mount point name,size in GB,VG name

chckfail()
{
        if [ $? -ne 0 ];then
                echo "Check error above. Halting..."
                exit 1
        fi
}

for i in `cat list.csv`
do
        kt_mountname=`echo $i | cut -d, -f1`
        kt_lvname=`echo $i |cut -d, -f1|cut -c 2-|tr / _`
        kt_vgname=`echo $i | cut -d, -f3`
        kt_lvsize=`echo $i | cut -d, -f2`
        kt_lvsize="${kt_lvsize}G"
        lvcreate -n $kt_lvname -L $kt_lvsize $kt_vgname >/dev/null
        chckfail
        mkfs.ext4 /dev/$kt_vgname/$kt_lvname >/dev/null
        chckfail
        mkdir -p $kt_mountname >/dev/null
        chckfail
        mount /dev/$kt_vgname/$kt_lvname $kt_mountname>/dev/null
        chckfail
        echo "/dev/$kt_vgname/$kt_lvname $kt_mountname ext4 defaults 0 0">>/etc/fstab
        chckfail
done

Breaking the code :

Quick walk through above code.

  • Part one is chckfail function which used to check if the command ran is successful or not. If the command failed, it will stop the execution of the script and exits.
  • Variable part extracts mount point name, size, VG to be used details from CSV file. It also creates LV names out of mount point name in CSV
  • Standard LVM commands to create LV, format it with EXT4, create mount point directory, and mount LV on it.
  • Finally, it adds an entry to /etc/fstab for the persistent mount.

Modifying script for your requirement :

  1. If you are using size in MB then remove line kt_lvsize="${kt_lvsize}G"
  2. If you are using size in TB then replace G with T in above mentioned line.
  3. If you are using filesystem other than ext4 then change mkfs.ext4 & /etc/fstab command accordingly.

One liner scripts to ease your Linux tasks

An assorted collection of one-liner scripts that are helpful in Linux sysadmin’s day to day tasks.

One liner scripts!

In this article, I am consolidating many one-liner scripts that I used or came across which will help you to perform Linux day to day tasks. Great way to save your time in repetitive work ensuring zero human errors!

Setting up hostname in SUSE (older versions)

I always prefer hostnamectl to set hostname in systems running on newer kernels.

# echo myserver.mydomain.com > /etc/HOSTNAME
# sed --in-place 's/preserve_hostname: false/preserve_hostname: true/' /etc/cloud/cloud.cfg #For Cloud servers
# sed --in-place 's/DHCLIENT_SET_HOSTNAME="yes"/DHCLIENT_SET_HOSTNAME="no"/' /etc/sysconfig/network/dhcp
# hostname myserver

Add your hostname instead of myserver and your FQDN domain instead of mydomain.


Setting up nameservers in Linux

# echo "nameserver 10.8.14.33 #Lab nameserver1
nameserver 10.8.17.33 #Lab nameserver2
search lab.kerneltalks.com">>/etc/resolv.conf

Add your own nameserver IPs and search domain in above code.


Add FQDN in hostfile

This applies to server with single IP allocated only.

# echo "`hostname -I` `hostname`.labs.kerneltalks.com `hostname`">>/etc/hosts

Add your own domain instead of labs.kerneltalks.com


Configure sudo so that it asks user’s password when user tries to execute sudo

# sed --in-place 's/Defaults targetpw/#Defaults targetpw/' /etc/sudoers

Remove existing NTP servers and add new in /etc/ntp.conf

# sed -e '/^server/s/^/#/g' -i /etc/ntp.conf
# echo "server 10.8.14.8 #Lab NTP1
server 10.8.14.9 #Lab NTP2">>/etc/ntp.conf

Commands to enable root access in Linux server

Below is a list of the commands you can execute to enable root access on the Cloud server or AWS Linux server.

# sed --in-place 's/PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config

# sed --in-place 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
# service sshd restart
# passwd root

If you are doing it on a public cloud server make sure that you reset the root account password since cloud server spin up with key-based authentication and their root does not carry a password initially.


Test port connectivity using telnet and exit in single command

# echo 'exit' | telnet 10.10.0.1 7657
Trying 10.10.0.1...
Connected to 10.10.0.1.
Escape character is '^]'.
Connection closed by foreign host.

Shell scripting basics: IF, FOR and WHILE loop

Beginners guide to learn shell scripting basics of If statement and for. while loops. The article includes small scripts of if, for and while loop.

Bash scripting : If, FOR & WHILE loop

This article can be referred to as a beginner’s guide to the introduction of shell scripting. We will be discussing various loops that are used in shell or bash scripting. In this chapter, we will discuss on if, for and while loop of scripting: if statement, for loop and while loop.

IF statement

If the loop is a conditional loop in scripting. It is used to check some conditions and perform actions based on the condition being true or false. If the loop structure is :

if [ condition ]
then
<execute this code>
else
<execute this code>
fi

If starts with condition check, if conditions match then it will execute the following code (after then). If the condition is false then it will execute code after else. If a statement can be used without else part too.

Example :

# cat if_statement.sh
#!/bin/bash
if [ $1 -lt 100 ]
then
echo "Your number is smaller than 100"
else
echo "Your number is greater than 100"
fi

# sh if_statement.sh 34
Your number is smaller than 100

If you execute this script, the loop will read the first argument as $1 and compare it with 100. Accordingly it will display output.

Bash FOR loop

Executing the same set of commands for the number of times loops are used in scripting. One of them is for loop. It takes input as a series of values and executes the following code repeatedly for each value. For loop structure is as below :

for i in <values>
do
<execute this code>
done

Here is reads values as a variable i and then $i can be used in the following code. Once all the values processed loops stops and script proceed to the next line of code.

Example :

# cat for_loop.sh
#!/bin/bash
for i in 1 2 3 4 5
do
echo First value in the series is $i
done

# sh for_loop.sh
First value in the series is 1
First value in the series is 2
First value in the series is 3
First value in the series is 4
First value in the series is 5

You can see variable $i is being fed with different values for each run of the loop. Once all values in range processed, the loop exits.

Bash WHILE loop

While is another loop used in programming which runs on condition. It keeps on running until the condition is met. Once the condition is un-matched, it exists. It’s a conditional loop! While loop structure is :

while [ condition ]
do
<execute this code>
done

While loop starts with the condition. If the condition is met it execute the following code and then again goes to verify condition. If the condition is still met then the next iteration of code execution happens. It continues to condition falses.

Example :

# cat while_loop.sh
#!/bin/bash
count=0
while [ $count -lt 3 ]
do
echo Count is $count
count=$(expr $count + 1)
done

# sh while_loop.sh
Count is 0
Count is 1
Count is 2

In the above example we have incremental counter code. We put up a condition for while loop is it can execute till counter less than 3. You can observe output the while loops exist when the counter hits 2.

These are three widely and commonly used for scripting! If you have any suggestions/feedback/corrections for this article please let us know in the comments below.

Bash fork bomb: How does it work

Insights of Bash fork bomb. Understand how the fork bomb works, what it could to your system, and how to prevent it.

Insight of Bash fork bomb

We will be discussing Bash fork bomb in this article. This article will walk you through what is fork bomb, how it works, and how to prevent it from your systems. Before we proceed kindly read the notice carefully.

Caution: Fork bomb may crash your system if not configured properly. And also can bring your system performance down hence do not run it in production/live systems.

Fork bombs are normally used to test systems before sending them to production/live setup. Fork bombs once exploded can not be stopped. The only way to stop it, to kill all instances of it in one go or reboot your system. Hence you should be very careful when dropping it on the system, since you won’t be able to use that system until you reboot it. Let’s start with insights into the fork bomb.

What is fork bomb?

Its a type of DoS attack (Denial of Service). Little bash function magic! Fork bomb as the name suggests has the capability to fork its own child processes in system indefinably. Means once you start fork bomb it keeps on spawning new processes on the system. These new processes will stay alive in the background and keeps eating system resources until the system hangs. Mostly these new processes don’t do anything and keep idle in the background. Also, by spawning new processes it fills up the kernel process limit, and then the user won’t be able to start any new process i.e. won’t be able to use the system at all.

How fork bomb works?

Now, technically speaking: fork bomb is a function. It calls himself recursively in an indefinite loop. Check the below small example :

bombfn ()
{
bombfn | bombfn &
}
bombfn

Above is the smallest variant of the fork bomb function. Going step by step to read this code :

  1. bombfn () : Line one is to define new function named bombfn.
  2. { and } : Contains the function code
  3. bombfn : This last line calls the function (bombfn) to execute
  4. Now the function code within { } – Here the first occurrence of bombfn means function calls himself within him i.e. recursion. Then its output is piped to another call of the same function. Lastly & puts it in background.

Overall, the fork bomb is a function which calls itself recursively, piped output to another call to himself, and then put it in background.  This recursive call makes this whole process repeat itself for indefinite time till system crashes due to resource utilization full.

This function can be shortened as :(){ :|: & };: Observe carefully, bombfn is above example is replaced by : and the last call of function is inlined with ;

 :(){ :|: & };:

Since this seems just a handful of symbols, the victim easily fell for it thinking that even running it on terminal won’t cause any harm as anyway, it will return an error. But it’s not!

How to prevent bash fork bomb?

Fork bomb can be prevented by limiting user processes. If you don’t allow the user to fork many processes then fork bomb won’t be allowed to spawn many processes that could bring down the system. But yes it may slow down system and user running fork bomb won’t be able to run any commands from his session.

Caution : This solution works for non-root accounts only.

Process limit can be set under /etc/security/limits.conf or PAM configuration.

To define process limit add below code in /etc/security/limits.conf file :

user1            soft    nproc          XXX
user1            hard    nproc          YYYYY

Where :

  • user1 is username for which limits are being defined
  • soft and hard are the type of limits
  • nproc is variable for process limit
  • last numbers (XXX, YYYYY) are a total number of processes a user can fork. Set them according to your system capacity.

You can verify the process limit value of user by running ulimit -u from the user’s login.

Once you limit processes and run fork bomb, it will show you below warning until you kill it. But you will be able to use the system properly provided you set limits well within range.

-bash: fork: retry: Resource temporarily unavailable

You can kill it by pressing cntl+c on the next iteration of warning. Or you can kill using root account from another session.

List WWN of online FC in HPUX server

List of commands to check WWN of online FC in the HPUX server. The article also includes a small script that can do this task in seconds!

WWN of online FC in HPUX

For FC connectivity to storage on the HPUX server, we must share the WWN of the online FC. Getting WWN is a three-step process :

Step 1:

Identify FC devices under ioscan output.

# ioscan -fnCfc
Class     I  H/W Path    Driver S/W State   H/W Type     Description
==================================================================
fc        0  2/0/10/1/0  fcd   CLAIMED     INTERFACE    HP AB379-60101 4Gb Dual Port PCI/PCI-X Fibre Channel Adapter (FC Port 1)
                        /dev/fcd0
fc        1  2/0/10/1/1  fcd   CLAIMED     INTERFACE    HP AB379-60101 4Gb Dual Port PCI/PCI-X Fibre Channel Adapter (FC Port 2)
                        /dev/fcd1
fc        2  2/0/12/1/0  fcd   CLAIMED     INTERFACE    HP AB379-60101 4Gb Dual Port PCI/PCI-X Fibre Channel Adapter (FC Port 1)
                        /dev/fcd2
fc        3  2/0/12/1/1  fcd   CLAIMED     INTERFACE    HP AB379-60101 4Gb Dual Port PCI/PCI-X Fibre Channel Adapter (FC Port 2)
                        /dev/fcd3

In above output, you can see /dev/fcd0 to 3 are FC devices.

Step 2:

Check which FCs are online i.e. have cable connectivity with fcmsutil output.

# fcmsutil /dev/fcd0

                           Vendor ID is = 0x1077
                           Device ID is = 0x2422
            PCI Sub-system Vendor ID is = 0x103C
                   PCI Sub-system ID is = 0x12D7
                               PCI Mode = PCI-X 133 MHz
                       ISP Code version = 5.4.0
                       ISP Chip version = 3
                               Topology = PTTOPT_FABRIC
                             Link Speed = 4Gb
                     Local N_Port_id is = 0x010300
                  Previous N_Port_id is = None
            N_Port Node World Wide Name = 0x50060b00006975ed
            N_Port Port World Wide Name = 0x50060b00006975ec
            Switch Port World Wide Name = 0x200300051e046c0f
            Switch Node World Wide Name = 0x100000051e046c0f
              N_Port Symbolic Port Name = server1_fcd0
              N_Port Symbolic Node Name = server1_HP-UX_B.11.31
                           Driver state = ONLINE
                       Hardware Path is = 2/0/10/1/0
                     Maximum Frame Size = 2048
         Driver-Firmware Dump Available = NO
         Driver-Firmware Dump Timestamp = N/A
                                   TYPE = PFC
                         NPIV Supported = YES
                         Driver Version = @(#) fcd B.11.31.1103 Dec  6 2010

Check the driver state in the above output (highlighted). If it’s ONLINE that means this FC has cable connectivity. If its Awaiting Link UP then it does not have cable connectivity.

Step 3:

If it’s online check its WWN by checking N_Port Port World Wide Name value! That’s it. So WWN of above FC is 0x50060b00006975ec.

I have compiled all the above steps in a single script that you can run and get the WWN of online FC in seconds.

First test script in test server. Run it on your own risk.

Sample output :

# sh test.sh

FC : /dev/fcd0
0x50060b00006975ec

FC : /dev/fcd2
0x50060b00006973c8

HPUX: APA configuration testing script

Small APA configuration testing script which will automate checking and verifying your Auto Port aggregation configuration in the HPUX server.

In the past, we have seen the configuration of Auto Port Aggregation in HPUX which explains what is APA and what is the purpose of using APA in your setup. In another post, we learned how to test APA if working perfectly or not. In this post, I will be sharing a script that I coded to automate this APA test.

Do not run this script on running live production. Since testing APA involves disabling of NIC.

Also, make a note that you need to run this script in normal terminal login and not on the server console. Since if the APA test fails you will lose server connectivity on primary NIC IP address. It is recommended to keep a continuous ping session on to IP address (configured on APA) to make sure that you monitor connectivity during the whole APA test. I have also explained the use of this continuous ping in manual APA test post.

Script code :

Execute this script on your own risk!

See below the APA configuration testing script. Save the below code in apa_test.sh file on your server. Execute script with root privileges using sh apa_test.sh or ./apa_test.sh command. Make sure executable permissions are set for the file.

Sample output :

******* APA Configuration Check *******
Caution !! Do not run this script from console

APA group : 900
IP	  : 10.10.5.2
Lan PPA	  : 0

APA group : 900
IP	  : 10.10.5.2
Lan PPA	  : 1

APA is working normally!

Write us suggestions/feedback/corrections in comments.

3 tricks to get multiple commands output in the same row

Three tricks to get two commands output in a single row. Normally two commands outputs will be always separated by a carriage return in Linux terminal. 

One of the major hurdles in scripting is to get your outputs formatted well according to requirements. In Linux/Unix each command stdout its output always in a new line. This is a hurdle in many situations where the coder wants two outputs, two terms, two variables in a single row for example CSV format. In this post, we will see how to present two or more commands output in a single row.

Read also : Scripting related posts

Normally when we execute more than one command, they will display outputs in different rows:

# date ; hostname
Sat Dec 24 01:35:50 EDT 2016
testsrv2

# echo text1; echo text2; echo text3
text1
text2
text3

In the above example, commands have outputs per row. We are going to accomplish all outputs in one row using the below tricks.

Trick 1:

Using the translate function. AS I said earlier each command output is accompanied by a carriage return. We will be translating carriage return with tab character hence getting two or more commands output in a single row.

# (date; hostname) |tr '\n' '\t'
Sat Dec 24 01:36:22 EDT 2016    testsrv2

# (echo text1; echo text2; echo text3) |tr '\n' '\t'
text1   text2   text3

Bypassing outputs to translate function we achieved single row output. Here we instructed tr function to translate all carriage returns (\n) to tab (\t).

If you want to output in CSV format (comma-separated value) then replace tab with a comma and you will get it.

# (date; hostname) |tr '\n' ','
Sat Dec 24 01:43:09 EDT 2016,testsrv2,

# (echo text1; echo text2; echo text3) |tr '\n' ','
text1,text2,text3,

You can observe one trailing comma which shows every command output ends with \n and hence it gets replaced by ,

Trick 2:

By defining each command output as a variable. Here we will store the output of each command in one variable and then we will echo those variables in a single line.

# mydate=`date`

# myname=`hostname`

# echo $myname $mydate
testsrv2 Sat Dec 24 01:46:04 EDT 2016

Here we stored date and hostname command’s output in mydate and myname variables. In the last command, we echoed both variables with space in between. Note that commands output can be stored in a variable by executing the command using backticks (in-line execution)!

Trick 3:

By echoing in-line execution outputs. In-line execution i.e. using backticks to execute commands within another command. We will be using this trick to echo outputs in a single row.

# echo "`date` `hostname`"
Sat Dec 24 01:50:36 EDT 2016 testsrv2

In the above example, first, we have executed commands and got outputs. But those outputs are fed into echo command. Hence echo command stdout them in a single row.

# echo "`echo text1` `echo text2` `echo text3`"
text1 text2 text3

Make a note that we executed each command in separate back tick quotes.

cut command and its examples

Learn how to use the cut command in various scenarios and in scripting with lots of examples. Understand how to extract selective data using cut command.

Everybody in a Linux or Unix environment is familiar with grep command which is used for pattern finding/filtering. This is a kind of selective data extraction from source data. cut is another command which is useful for selective data extraction.

cut command basically extracts a portion of data from each line of a given file or supplied data. Syntax to be used for cut command is –

# cut [options] [file]

Below different options can be used with cut command :

c To select only this number of character.

Roughly you can say its a column number to be extracted. See below example:

# cat test
sd
teh
dxff
cq2w31q5
# cut -b 4 test


f
w

Here, cut is instructed to select only 4th character. If you look closely, in the output it shows only 4th column letters. Lines which are having less than 4 characters are shown blank in cut output!

This option is useful in scripting when there is a need for single-column extraction from supplied data.

-b To select only this number of bytes.

This option tells the command to select only a given number of a byte from each line of data and show in the output. In most cases, its output is the same as -c option since each character is treated as one byte in a human-readable text file.

-d Use specified delimiter instead of TAB

Normally cut uses tab as a delimiter while filtering data. If your file has different delimiter like a comma , in CSV file or colon : in /etc/passwd file then you can specify this different delimiter to cut command. Command will process data accordingly. This option should always be used with b, c or f options. Only using -d option will result in below error :

# cut -d a test
cut: you must specify a list of bytes, characters, or fields
Try `cut --help' for more information.

-f To select only specified number of fields.

This option is to specify which all fields to be filtered from data. This option if not supplied with delimiter character data (-d option/ no TAB in data) then it will print all lines. For example, if you say -f 2 then it searches for TAB or supplied delimiter values if any in data. If found then it will print 2nd field from delimiter for that line. For lines where it won’t find delimiter, it will print the whole line.

# cat test
this is test file
raw data
asdgfghtr
data
#cut -f1 test
this is test file
raw data
asdgfghtr
# cut -d" " -f2 test
is
data
asdgfghtr
data

Field numbering is as below:

Field one is the left side field from the first occurrence of the delimiter
Field second is the right-side field from the first occurrence of the delimiter
Fields third is the right-side second field from the first occurrence of the delimiter

Observe the above example, where it prints all lines as it is when the delimiter is not specified. When the delimiter is defined as single space ” ” then it prints field two according to numbering explained above.

-s To print only lines with delimiters

Missing delimiter causes cut to print the whole line as it is which may mislead the desired output. This is dangerous when the command is being used in scripts. Hence -s option is available which restricts cut to display the whole line in case of missing delimiter.

# cut -f1 -s test

Using the same test file from the above example when -s is specified then there is no output. This is because the default delimiter TAB does not exist in the file.

Number to be used with -b, -c and -f options:

In all the above examples, we have declared single integers like 2,4 for -b, -c and -f options. But we can also use the below system :

  • x: Single number like we used in all examples
  • x-: From xth bye, character or field till end of line
  • x-y: From xth byte, character or field till yth
  • -y: From first byte, character or field till yth
# cut -d" " -f2- test
is test file
data
asdgfghtr
data
# cut -d" " -f2-3 test
is test
data
asdgfghtr
data
# cut -d" " -f-1 test
this
raw
asdgfghtr
data

Few examples of cut command :

To get a list of users from /etc/passwd file, we will use delimiter as : and cut out the first field.

# cut -d: -f1 /etc/passwd
root
bin
daemon
adm
lp
------ output clipped -----

cut command can be feed with data from the pipe as well. In that case last [file] parameter shouldn’t be defined. Command will read input from pipe and process data accordingly. For example, we are grep ing user with uid 0 and then getting their usernames using cut like below:

# cat /etc/passwd |grep :0: | cut -d: -f1
root
sync
shutdown
halt
operator

Getting userid and group id from /etc/passwd file along with their usernames.

# cat /etc/passwd |cut -d: -f1-4
root:x:0:0
bin:x:1:1
daemon:x:2:2
adm:x:3:4
lp:x:4:7
sync:x:5:0

How to change sender’s email id in EMS HPUX

EMS doesn’t allow us to edit the sender email address. All events are always sent out with sender id as root@hostname. Here is a small script to change it.

Requirement :

Normally in the Event monitoring system ( EMS ) on HPUX send an email with sender id as root@hostname. Many organization’s email servers don’t allow such an email address in the sender field. We need generic email id in sender field when EMS shoots an alert email something like notification@xyz.com

Workaround :

There is no provision to change this email id anywhere in HPUX or EMS configurations. You can use the below workaround which works perfectly without any issues.

Step 1 :

Make sure you have a valid email address (like notification@xyz.com) for your logged-in account which works. Send a test email from the server to verify using below command

# echo test |/usr/sbin/sendmail -v receiver_id@xyz.com
receiver_id@xyz.com... Connecting to smtpserver.xyz.com via relay...
220 smtpserver.xyz.com ESMTP Postfix
>>> EHLO xyz.com
250-smtpserver.xyz.com
250-PIPELINING
250-SIZE 25600000
250-VRFY
250-ETRN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
>>> MAIL From:<root@xyz.com> SIZE=5
250 2.1.0 Ok
>>> RCPT To:<receiver_id@xyz.com>
>>> DATA
250 2.1.5 Ok
354 End data with <CR><LF>.<CR><LF>
>>> .
250 2.0.0 Ok: queued as 46466822F2
receiver_id@xyz.com... Sent (Ok: queued as 46466822F2)
Closing connection to smtpserver.xyz.com
>>> QUIT
221 2.0.0 Bye

Step 2 :

Setup crontab for above logged in the account (for which email tested) which will execute the EMS log scanner script every 30 minutes. As per your convenience, you can even schedule it to run every 10 mins or even lower.

00,30 * * * * /scripts/ems_monitor.sh

Step 3:

The script code is as below.

# Script to scan EMS log file and email alert if any
# Author : Shrikant Lavhate
#! /bin/bash
if [ -f "https://z5.kerneltalks.com/logs/event_monitor.log" ]
then
:
else
cp -p /var/opt/resmon/log/event.log /logs/event_monitor.log
fi
diff /logs/event_monitor.log /var/opt/resmon/log/event.log /logs/logfile_difference
if [ -s "/logs/logfile_difference" ]
then
cat /logs/logfile_difference | grep '^'|cut -c 2- | mailx -s "EMS monitor alert from `hostname`" receiver_id@xyz.com
fi
cp -p /var/opt/resmon/log/event.log /logs/event_monitor.log

Step 4:

Now you can test the script by generating test events in EMS. Generate test event with send_test_event command.

# send_test_event -v -a disk_em

Finding resource name associated with monitor disk_em.

Found resource name /storage/events/disks/default
associated with monitor disk_em.

Creating test file /var/stm/config/tools/monitor/disk_em.test
for monitor disk_em.

Making test file /var/stm/config/tools/monitor/disk_em.test
for monitor disk_em
indicate send test event for all resources.

Performing resls on resource name /storage/events/disks/default
for monitor disk_em to cause generation of test event.
Contacting Registrar on aprss006

NAME:   /storage/events/disks/default
DESCRIPTION:    Disk Event Monitor

This resource monitors events for stand-alone disk drives.  Event 
monitoring requests are created using the Monitoring Request 
Manager.  Monitoring requests to detect changes in device status are 
created using the Peripheral Status Monitor (psmmon(1m)) and Event 
Monitoring Service (EMS). 

For more information see the monitor man page, (disk_em(1m)).

TYPE:   /storage/events/disks/default is a Resource Class.

There are 2 resources configured below /storage/events/disks/default:
Resource Class
        /storage/events/disks/default/64000_0xfa00_0x0
        /storage/events/disks/default/64000_0xfa00_0x35

You will receive test events from admin@hostname email id which is normal. Now run above script and you will receive the same email with sender id as notification@xyz.com !!

I have tested this script and it works flawlessly. Please leave comments below if it’s helpful to you too.

Get list of desired LUN id from powermt output

Small script to get LUN id from powermt output when supplied with a list of disks. It’s a tedious job to extract LUN id from the output when you have a list of disks to wok upon.

Requirement :

You have a list of disk names from OS end and you need to get their respective LUN ids from powermt output.

This requires manual work of searching each disk name in output and then copying its respective LUN id. Typically these three lines you are interested in powermt output.

Pseudo name=emcpoweraa
Symmetrix ID=000549754319
Logical device ID=03C4

If you have a list of disks to search its a tedious task. Because you have to search each and every disk name in the output.

Solution :

Get the output of powermt command in a file

# powermt display dev=all > powermt.old

Get all disk names in one file e.g. test.txt
Run a for loop which will get LUN id of each disk described in the file. In this loop, we are taking each disk and searching it in the above file. Then we are extracting 2 below lines from disk name (since 2nd line below disk name contains LUN id). And then extracting LUN id from it with some data filtering.

# for i in `cat test`
do
cat powermt.old |grep -A 2 $i|grep Logical|awk '{print $3}'|cut -d= -f2
done

You will be presented with the list of LUN ids for respective disks in the test.txt file! You can even echo disk name before LUN id by inserting echo $i just above cat command in the above code.

Vice versa:

Get disk names by giving LUN ids in text.txt file. Its same logic, the only difference is we will be extracting above 2 lines rather than below ones. Rest all procedure remains the same.

# for i in `cat test`
do
cat powermt.old |grep -B 2 $i|grep Pseudo|awk '{print $2}'|cut -d= -f2
done