Df -k output format


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers Df -k output format
# 1  
Old 08-03-2013
Df -k output format

I’m trying to create a shell script to get the server stats of 100 servers and load the details into a table.

Initially I’m creating a parameter file which has the list of all the servers, then I ‘m connecting these servers through ssh and run df –k. ssh keys are already setup.

Issues I’m facing is that I’m not able to associate server name to the result, I want server name added as a column to the df –k output.
Also the output format cannot be loaded into a table as there is no delimiter or tab or space properly formatted to load. I have tried sed & various other options but no luck.


Code:
#!/bin/ksh
PARMFILE=/opt/sdw/scripts/db_scripts/server_stats.txt
 
value=$(<server_list1.txt)
echo "$value"
sourceservers=`grep =/opt/sdw/scripts/db_scripts/server_stats.txt |cut -d= -f2`
 
#Input array passed as parameter file to the script
set -A array_value $value
vLen=${#array_value[@]}
echo $vLen
 
for(( j=0; j<$vLen; j++))
do
#echo "${array_value[$j]}"
#ssh -q "${array_value[$j]}"; df -k
ssh -q "${array_value[$j]}" 'df -h' >> df.out
ssh -q "${array_value[$j]}" df -h | column -t  >> df1.out
ssh -q "${array_value[$j]}" df -k | tr -s " " | sed 's/ /, /g' | sed '1 s/, / /g' | column -t >> df3.out
 [[ ! $? = 0 ]] && echo Failure, errno $?, cannot connect to host "${array_value[$j]}" >> sshfailed.list
done

Output

Code:
Filesystem                                             Size  Used  Avail  Use%
Mounted                  on
/dev/mapper/vg00-lvol3                                 1.5G  434M  923M   32%

Desired output

Code:
Filesystem,                                Size,       Used ,  Avail,    Use%,   Mounted  on, Servername
/dev/mapper/vg00-lvol3,      1.5G,     434M,  923M,   32%,      /                        br724


Last edited by Don Cragun; 08-03-2013 at 05:00 PM.. Reason: Remove dozens of FONT and SIZE tags; add CODE tags.
# 2  
Old 08-04-2013
First off: i am more or less on my vacation and writing this on a Windows-machine, lacking a *NIX-system to test my words against. Please bear with me that i will give you untested instead of working code therefore and forgive me some errors or typos my failing memory and lack of testing equipment might produce.

Another thing: you haven't mentioned the system you are working on. Guessing from the output of "df" you are on some Linux-system, but then this guess might as well be wrong. I will try to accomodate a Linux-system with the following until you say otherwise.

Quote:
Originally Posted by anita81
Issues I'm facing is that I'm not able to associate server name to the result, I want server name added as a column to the df -k output.
Also the output format cannot be loaded into a table as there is no delimiter or tab or space properly formatted to load. I have tried sed & various other options but no luck.


Code:
#!/bin/ksh
PARMFILE=/opt/sdw/scripts/db_scripts/server_stats.txt
 
value=$(<server_list1.txt)
echo "$value"
sourceservers=`grep =/opt/sdw/scripts/db_scripts/server_stats.txt |cut -d= -f2`
 
#Input array passed as parameter file to the script
set -A array_value $value
vLen=${#array_value[@]}
echo $vLen
 
for(( j=0; j<$vLen; j++))
do
#echo "${array_value[$j]}"
#ssh -q "${array_value[$j]}"; df -k
ssh -q "${array_value[$j]}" 'df -h' >> df.out
ssh -q "${array_value[$j]}" df -h | column -t  >> df1.out
ssh -q "${array_value[$j]}" df -k | tr -s " " | sed 's/ /, /g' | sed '1 s/, / /g' | column -t >> df3.out
 [[ ! $? = 0 ]] && echo Failure, errno $?, cannot connect to host "${array_value[$j]}" >> sshfailed.list
done

Let us start with the way you read the server names and process them. It is not wrong to read the names into an array like you do but it is not a very "shell-like" way either. It is inherently dangerous too, because, depending on the version of the Korn shell you are using, your arrays might be (too) limited in possible array elements. ksh88 (the default shell on AIX systems, for instance) allows only for 1024 array elements, so if your server list grows your array might be unable to hold it. Set up a small loop fed by the server list as input file. I have added a little error handling, because it is good style to let a script state the reason it can't go on instead of just just breaking.

Further, i have added a little refinement to your input file with the list of server names. It pays to have the possibility to add comments to such a file as a way to document the reason why some entries are there or quick-remove one by "outcommenting" it:

[code]
Code:
#!/bin/ksh
PARMFILE=/opt/sdw/scripts/db_scripts/server_stats.txt
sourceservers=`grep =/opt/sdw/scripts/db_scripts/server_stats.txt |cut -d= -f2`          # i do not understand what this does

typeset fInput=""
typeset chServer=""
 
if [ ! -r "$1" ] ; then            # exit if input file with server list is not readable
     print -u2 "ERROR: cannot read input file $1, exiting."
     exit 2
fi
fInput="$1"

sed 's/#.*$//;s/^ *//;s/ *$//;/^$/d' "$fInput" |\
while read chServer ; do
     print - "processing $chServer"
done

exit 0

Call this script like: ./script /path/to/server_list_file, where the input file could look like this. Comment rules are like in scripts:

Code:
# server list file version 1
# last change: <today> by: <me>
# -------------------------------------------------------------

server1.network.com      # the initial one
server2.network.com      # the second one

# these added by request of X. Y.
server3.network.com
server4.network.com
# server5.network.com # do not need that one

If this produces the desired result (a list of the server names) we are going to replace the "print"-statement with a more elaborate processing. You said you will have exchanged the keys prior to running this script but it is better not to depend on this. Add a little error-handling for the case that the communication between the two systems is failing somehow - broken network, system down, not exchanged keys, whatever. When you query 100 systems almost every time the one or other will not respond for one or the other reason. The way you wrote it:

Code:
ssh -q "${array_value[$j]}" df -k | tr -s " " | sed 's/ /, /g' | sed '1 s/, / /g' | column -t >> df3.out
 [[ ! $? = 0 ]] && echo Failure, errno $?, cannot connect to host "${array_value[$j]}" >> sshfailed.list

would not work. First, because you are testing against the exit code of a pipeline (which is the exit code of the last command), not that of "ssh". (I doubt you have set the "-o pipefail" setting in "ksh"). Further, because the special variable "$?" is set anew upon completion of every command. After (successfully) executing "[[ ! $? = 0 ]]" it will be set to "0" and therefore "..errno $?, cannot..." will hold no usable data, even if it would have held it before (which is unlikely).

This is version two of the script. In case you might wonder about my variable naming: i am using sort-of hungarian style notation prefixes to indicate the type - "ch" for "char" (string), "i" for "integer", "f" for "file" (a path name), etc., to keep track of my variable types. I suggest to read up upon "print -u<n>" in the man page for ksh to understand the following, as it is (alas!) not common knowledge:

[code]
Code:
#!/bin/ksh
PARMFILE=/opt/sdw/scripts/db_scripts/server_stats.txt
sourceservers=`grep =/opt/sdw/scripts/db_scripts/server_stats.txt |cut -d= -f2`          # i do not understand what this does

typeset fInput=""
typeset chServer=""
typeset fLog="/path/to/some/logfile"

if [ ! -r "$1" ] ; then            # exit if input file with server list is not readable
     print -u2 "ERROR: cannot read input file $1, exiting."
     exit 2
fi
fInput="$1"
exec 3>"$fLog"                   # set up logging to logfile

sed 's/#.*$//;s/^ *//;s/ *$//;/^$/d' "$fInput" |\
while read chServer ; do
     if ping -qc 1 "$chServer" ; then
          if ssh -qTo BatchMode yes "$chServer" date ; then
               ssh -qTo BatchMode yes "$chServer" 'df -kP'
          else
               print -u3 "Warning: $chServer refuses ssh-communication."
          fi
     else
          print -u3 "Warning: $chServer cannot be reached via network."
     fi 
done

exec 3>&-                        # close the logfile
exit 0

Notice that i got rid of the "-h" flag of "df", as it produces the line breaks which make parsing the output harder. Instead i added the "-P" flag for POSIX-compatibility, so that output over different systems are better comparable and parsing the output is made easier.

Right now we dump the output of our command to the screen unrefined. As soon as you are satisfied with the results we give it some finishing touches by pocessing it a bit. We remove the headers (we need them only once if at all) and put the host name in front. This way it is easily possible to sort for hosts or grep for lines from one host and the resulting output can easily be parsed. Script version 3:

[code]
Code:
#!/bin/ksh
PARMFILE=/opt/sdw/scripts/db_scripts/server_stats.txt
sourceservers=`grep =/opt/sdw/scripts/db_scripts/server_stats.txt |cut -d= -f2`          # i do not understand what this does

typeset fInput=""
typeset chServer=""
typeset fLog="/path/to/some/logfile"

if [ ! -r "$1" ] ; then            # exit if input file with server list is not readable
     print -u2 "ERROR: cannot read input file $1, exiting."
     exit 2
fi
fInput="$1"
exec 3>"$fLog"                   # set up logging to logfile

sed 's/#.*$//;s/^ *//;s/ *$//;/^$/d' "$fInput" |\
while read chServer ; do
     if ping -qc 1 "$chServer" ; then
          if ssh -qTo BatchMode yes "$chServer" date ; then
               ssh -qTo BatchMode yes "$chServer" 'df -kP' |\
               sed '1d; s/^/'"$chServer"': /'
          else
               print -u3 "Warning: $chServer refuses ssh-communication."
          fi
     else
          print -u3 "Warning: $chServer cannot be reached via network."
     fi 
done

exec 3>&-                        # close the logfile
exit 0

Once satisfied call the script with

Code:
./script /path/to/server.list > /path/to/outfile

to save the output to a file.

It is easily possible to add more functionality to the script: suggestions would include a configurable option file and better command line handling. See the "getopts" man page for details. The server list file format could be refined to include certain user accounts to use, etc.. Also the error reporting is sketchy at best. I prefer a layered approach with two logfiles (severe errors and warnings) in my scripts and log start- and end-times of runs, process-IDs, etc., so that it is easy to find out which script instance has started to go wrong and why.

Anyway, i hope to have shed some light on how to improve your script and that you find my comments useful.

I hope this helps.

bakunin
This User Gave Thanks to bakunin For This Post:
# 3  
Old 08-04-2013
Thank you

Thank you, you helped me to understand and improve the way script should be written
 
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Format output

Hello Team, I have the following details in a txt file (please note the spaces and tabs) C1 C2 C3 ------------------ --------------- ------------- abc, xyz 2 8 pqr 2 ... (9 Replies)
Discussion started by: H squared
9 Replies

2. Shell Programming and Scripting

Format with output

I have written some scripts that resulted in the table below (Column1 is ITEM, Column2 is Group, Column3 is Category and Column4 is Quantity) but I want the output in another format: Input: K123 X CATA 3 K123 Y CATA 4 K123 Z CATA 2 K123 X CATB 5 K123 Y CATB 2 K123 Z CATB 2 B65 M CATB... (7 Replies)
Discussion started by: aydj
7 Replies

3. Shell Programming and Scripting

Script to generate Excel file or to SQL output data to Excel format/tabular format

Hi , i am generating some data by firing sql query with connecting to the database by my solaris box. The below one should be the header line of my excel ,here its coming in separate row. TO_CHAR(C. CURR_EMP_NO ---------- --------------- LST_NM... (6 Replies)
Discussion started by: dani1234
6 Replies

4. UNIX for Dummies Questions & Answers

Format Output

Hello Learned People, Good evening. I have absolutely no idea as how to do this & I admit that I do not know anything in unix. I must learn this one of these days. Im a help desk incharge today & someone gave me this file to be formatted & I have a file like this. vi NewFile.txt 232... (8 Replies)
Discussion started by: RTAN
8 Replies

5. Shell Programming and Scripting

Dynamic output file generation using a input text file with predefined output format

Hi, I have two files , one file with data file with attributes that need to be sent to another file to generate a predefined format. Example: File.txt AP|{SSHA}VEEg42CNCghUnGhCVg== APVG3|{SSHA}XK|"password" AP3|{SSHA}XK|"This is test" .... etc --------- test.sh has... (1 Reply)
Discussion started by: hudson03051nh
1 Replies

6. UNIX for Advanced & Expert Users

format df -k output

i am running df -k command on aix machine. i got the output like this. i need to store into file and send that file into microsoft excel.i need to allign properly. Filesystem 512 blocks Free % Used Iused %Iused Mounted on /dev/hd4 262144 126488 52% ... (9 Replies)
Discussion started by: wintercoat
9 Replies

7. Shell Programming and Scripting

Help in Getting specified output format

Hi all, I have input text file of this format objectclass:endeavor pid:12345 postalAddress:379 PROSPECT ST street:STE B l:TORRINGTON st:CT postalCode:067905238 telephoneNumber:9999999999... (2 Replies)
Discussion started by: pintoo
2 Replies

8. Shell Programming and Scripting

How to format output

Dear all, I have written a program which access database and displays the values returned by the query . There are 10 columns to be displayed in one row. But am ending with 5 lines displayed on 1st line and the next 5 in the 2nd line. Ex : 21608 10-20-2007 148 Al's Appliance... (7 Replies)
Discussion started by: uday542
7 Replies

9. Shell Programming and Scripting

capturing output from top and format output

Hi all, I'd like to capture the output from the 'top' command to monitor my CPU and Mem utilisation.Currently my command isecho date `top -b -n1 | grep -e Cpu -e Mem` I get the output in 3 separate lines.Tue Feb 24 15:00:03 Cpu(s): 3.4% us, 8.5% sy .. .. Mem: 1011480k total, 226928k used, ....... (4 Replies)
Discussion started by: new2ss
4 Replies

10. UNIX for Dummies Questions & Answers

ls output format

below is the output is ls -l -rw-r--r-- 1 tonyt staff 3212 Apr 17 1999 file1 -rw-r--r-- 1 tonyt staff 4541 Mar 3 21:08 file2 why the date format is not the same? (6 Replies)
Discussion started by: tonyt
6 Replies
Login or Register to Ask a Question