1

I need to write a script to find total memory and total swap of several linux server (2000+). I have one trusted server from where I can login to all these 2000 servers without a password.

When I run this script, it should give output like this:

Server         total memory        swap
redhat1   
redhat2
redhat3
...
redhat2000

How can I achieve this?

2 Answers 2

5

The /proc/meminfo file contains the information you're after. It's pretty easy to parse too.

This will get you the RAM and swap (in that order, unit is kB on all systems I know):

awk '/^(MemTotal|SwapTotal)/{print $2}' /proc/meminfo

To format it, you could do something like:

printf "%s\t%d\t%d\n" $(hostname) \
                      $(awk '/^(MemTotal|SwapTotal)/{print $2}' /proc/meminfo)

To combine that with ssh, do something like:

for host in your_list_of_servers ; do
  printf "%s\t%d\t%d\n" $host \
                   $(ssh $host "awk '/^(MemTotal|SwapTotal)/{print \$2}' /proc/meminfo")
done
3
  • this will help during logging to each server and execute it. Commented Feb 28, 2013 at 6:48
  • this would help if I am executing in each server Here i have to do in 2000 server, it would be like logging to each server and execute command. [root@master /]# ssh redhat1 'printf "%s\t%d\t%d\n" $(hostname) $(awk '/^(MemTotal|SwapTotal)/{print $2}' /proc/meminfo)' bash: syntax error near unexpected token `(' Commented Feb 28, 2013 at 6:52
  • Updated with an example of how you could do it in a loop. Commented Feb 28, 2013 at 7:54
1

First You need to setup password less log-in, you can refer this page .

After that you can use below script as per your requirement.

#!/bin/bash
# store username:ip combo here separated by a whitespace
_pair="[email protected] [email protected] [email protected]"

for e in $_pair
do
        # extract user and ips for each $e in $_pair
        IFS='@'
        set -- $e
        _user="$1"
        _ip="$2"

        sleep 2
        echo "Connecting to server '${_ip}' via SSH..."
        ssh ${_user}@${_ip} "free -m | awk -v h=$HOSTNAME '(/Mem/||/Swap/){printf("%s\t%s%d\t",h,$1,$2)}'; echo -e"
done
3
  • output is in this way redhat1 Mem: 7855M redhat1 Swap: 3371M can you tell me how to get in this way redhat1 7855M 3371M Commented Feb 28, 2013 at 7:07
  • output is in this way redhat1 Mem: 7855M redhat1 Swap: 3371M can you tell me how to get in this way redhat1 7855M 3371M Commented Feb 28, 2013 at 7:10
  • @ashwini I have Updated as per your requirement Please check it now. Commented Feb 28, 2013 at 9:20

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.