How to get the memory and cpu usage of a remote server? - linux

My intent is to log into several servers and print out their memory & cpu usage one by one. I wrote the follow scripts
START=1
END=5
for i in {$START..$END}
do
echo "myserver$i"
ssh myserver$i
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }'
top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}'
logout
done
But it doesn't work. Who can give a solution to this? Thanks a lot!

Look carefully at your code.
After the SSH command, you are on the remote server, in an SSH shell. And obviously your script now wants you to talk (via keyboard) to the remote server. When it is finished, e.g. if you hit ctrl-c or ctrl-d, then the next commands like "free" and "top" are running on your local machine.
You have to tell ssh with a kind of "-exec" argument that it should execute free and top on the remote server :D
I'm sure you figure it out yourself how to do that, have fun.

There is one useful command for CPU/mem usage - top.
To get the result, run this command.
CPU Usage - top -b -n 1 | grep Cpu
Mem Usage - top -b -n 1 | grep 'KiB Mem'

After searching online and combining a few answers from other questions on stackflow. I get the following solution.
Solution
On your local computer, you might want to have the following bash script, named, say, usage_ssh
START=1
END=3
date
for i in $(seq $START $END)
do
printf '=%.0s' {1..50};
printf '\n'
echo myservery$i
ssh myserver$i -o LogLevel=QUIET -t "~/bin/usage"
done
printf '=%.0s' {1..50};
printf '\n'
printf 'CPU Load: \n'
printf 'First Field\tprocesses per processor\n'
printf 'Second Filed\tidling percentage in last 5 minutes\n'
printf '\n'
printf '\n'
On your remote server, you should have the following bash script named usage. This script should be located in ~/bin.
free -m | awk 'NR==2{printf "Memory Usage\t%s/%sMB\t\t%.2f%\n", $3, $2, $3/$2*100}';
top -n 1 | grep load | awk '{printf "CPU Load\t%.2f\t\t\t%.2f\n", $(NF-2), $(NF-1)}';
Explanation
The idea is that You will call the use ssh -t <your command> to run executable on your remote file and get the output on the screen of your local computer.
Output
Sat Mar 28 10:32:34 CDT 2020
==================================================
myserver1
Memory Usage 47418/48254MB 98.27%
CPU Load 0.01 0.02
==================================================
myserver2
Memory Usage 47421/48254MB 98.27%
CPU Load 0.01 0.02
==================================================
myserver3
Memory Usage 4300/84541MB 5.09%
CPU Load 0.02 0.02
==================================================
CPU Load:
First Field processes per processor
Second Filed idling percentage in last 5 minutes

Related

How "free" command is not working when creating shell script

I created bash script to find out cpu and other memory/cpu of different servers.
USER=name
DEST=\result.txt
FILE=\servers.txt
GetTotalCores="nproc --all"
GetMemoryDetails=" df -h | awk 'NR==2{print \$2}'"
GetMemoryDetails2=" df -h | awk 'NR==2{print \$2}'"
GetDetails="free -h"
for i in `cat $FILE`;
do
echo -n "."q
D= "$(ssh name#$i.com $GetDetails)"
A="$(ssh name#$i.com $GetTotalCores)"
B="$(ssh name#$i.com $GetMemoryDetails)"
C="$(ssh name#$i.com $GetMemoryDetails2)"
echo "${i} CPU: ${A} MEMORY: ${B} ${C} RAM: ${D} >" >> ${DEST}
done
exit 0
When running the script everything is executed correctly exept "free command"
The result I am getting:
script.sh: line 27: total used free shared buff/cache available
Mem: 24669784 9181092 229024 1432604 15259668 13685616
Swap: 4063228 501760 3561468: No such file or directory
And nothing is printed into the destination file
I tried warapping it with different quotes but result is the same
Your script contains many oddities, but the main problem is that you are opening so many remote connections just to get a small nugget of information. It will be a lot more efficient to articulate the whole report remotely.
Also, redirect the output after done just once; this is a very minor efficiency improvement if the output file is small, but also very easy to make.
user="name"
while read -r server; do
# echo -n "."q
ssh "$name"#"$server.com" <<\____HERE |
nproc --all
df -h | awk 'NR==2{print $2}'
# do you really need to run this command twice?
free -h
____HERE
awk -v i="$server" 'NR==1 { cpu=$0 }
NR==2 { mem=$0 }
NR==3 { printf "%s CPU: %s MEMORY: %s %s RAM: %s >\n",
server, cpu, mem, mem, $0 }'
done<servers.txt >result.txt

Linux finding the mean of the memory usage of last hour

i am trying to write a script that finds the mean of the memory usage of last hour and if it's above %60, mails to someone thats relevant.
I am trying this for days and i am completely lost. On the other hand i can't get any updates for my Ubuntu so i can't try someting like atop. I need this to work on other computers as well.
As far as i know ;
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }'
I am trying to use something like this in my code. Any help would appreciated.
Thanks.
EDIT
So i've built my scripts basics. But in this script i am getting the current ram usage.
#!/bin/sh
used=$(free -m | grep '^Mem' | awk '{print $3}')
total=$(free -m | grep '^Mem' | awk '{print $2}')
perct=$((($used*100)/$total))
echo "$perct%"
if [ $perct -gt 60 ] ; then
echo "Ram usage: $perct is above 60%" | mail -s "Critical Ram Usage" "example#example.com"
fi
#end
From this point , what can i do to improve my code ?

Custom Splash Screen on Login RHEL

I was wondering if it was possible to display a splash screen when you log into an account in a RHEL server? not via /etc/motd as that is global but to an specific user.
Ideally I would like to show uptime and services running when a service account is logged in.
Kind regards,
R,
Check manual page for sshd_config. There is Banner option and you can customize it per-user.
Also motd can be dynamic. Check this answer on ServerFault:
However, it's possible to execute a shell script at login time that will have the same result. This is usually achieved by adapting the /etc/profile script that is executed each time a user logs in. A useful practice is to put the command you want to be executed in a script named /etc/motd.sh and call this script from /etc/profile, usually at about the end of it.
You can modify the target user's .Bash_profile and put inside of it the commands to show stuffs like cpuinfo meminfo...
Here's an example.
let upSeconds="$(/usr/bin/cut -d. -f1 /proc/uptime)"
let secs=$((${upSeconds}%60))
let mins=$((${upSeconds}/60%60))
let hours=$((${upSeconds}/3600%24))
let days=$((${upSeconds}/86400))
UPTIME=`printf "%d days, %02dh%02dm%02ds" "$days" "$hours" "$mins" "$secs"`
echo "`date +"%A, %e %B %Y, %r"`
`uname -srmo`
Uptime.............: ${UPTIME}
Memory.............: `cat /proc/meminfo | grep MemFree | awk {'print $2'}`kB (Free) / `cat /proc/meminfo | grep MemTotal | awk {'print $2'}`kB (Total)
Load Averages......: ${one}, ${five}, ${fifteen} (1, 5, 15 min)
Running Processes..: `ps ax | wc -l | tr -d " "`
IP Addresses.......: `/sbin/ifconfig eth0 | /bin/grep "inet addr" | /usr/bin/cut -d ":" -f 2 | /usr/bin/cut -d " " -f 1`"
this example will show you something like this:
Friday, 15 April 2016, 04:47:41 PM
Linux 2.6.18-128.el5 x86_64 GNU/Linux
Uptime.............: 2 days, 02h05m06s
Memory.............: 1805240kB (Free) / 4037732kB (Total)
Load Averages......: 0.77, 0.74, 0.89 (1, 5, 15 min)
Running Processes..: 230
IP Addresses.......: X.X.X.X
ENJOY!

bash script for memory and cpu usage [duplicate]

This question already has answers here:
How do I get the total CPU usage of an application from /proc/pid/stat?
(6 answers)
Closed 7 years ago.
I need to write script which returns file with information about cpu and memory usage of specified process through given time period.
When I use ps -p pid I only get usage of one cpu core, and when I use top I get binary file as output. I tried with next :
while :;
top -n 1 -p pid | awk '{ print $9" "$10 }'
sleep 10;
done
Information the kernel offers for your process is in the /proc filesystem. Primarily you would need to parse these two files to get the pertinent data for your script
/proc/(pid)/status
/proc/(pid)/stat
This thread describes getting this CPU data in detail so I wont here.
The problem I think you'll find is CPU usage for a process is not broken down into the various cores available on your system, but rather summarized into a number that approaches 100% * (number of cores). The closest to this is the "last processor used" column of top (option f, J), though this hardly addresses your problem. A profiling tool like the one in this thread is likely the final answer.
I don't know your environment or requrements; however a solution could be running only the process isolated on a machine, then collecting each cores CPU usage at the system level loosely representing the process demand.
Try this:
$PID=24748; while true; do CPU=$(ps H -q $PID -eo "pid %cpu %mem" | grep $PID | cut -d " " -f 3 | sed -e 's/$/\+/' | tr -d "\n" | sed -e 's/+$/\n/' | bc) && MEM=$(ps H -q $PID -eo "pid %cpu %mem" | grep $PID | cut -d " " -f 4 | head -n 1) && echo $PID $CPU $MEM && sleep 3; done
It basically just adds up the CPU % usage of each thread with bc, takes the memory usage (as a whole), and prints them, of a specified PID.

Junk characters being printed with tee command

Script I'm utilizing is below:
#!/bin/bash
lla=$(top -n 1 | grep "load average" | awk '{print $13,$14,$15}')
mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
now=`date`
cur_time=$(echo $now | awk '{print $4}')
for i in {1..60}
do
echo "System Performance Statistics at: "$cur_time | tee -a hp.txt
echo "Linux Load Average: "$lla | tee -a hp.txt
echo "Memory Usage: "$mem_usage | tee -a hp.txt
echo "" | tee -a hp.txt
sleep 3
done
Results:
System Performance Statistics at: 19:00:29
Linux Load Average: 0.13, 0.11, 0.14^[(B^[[m^[[39;49m^[[K
Memory Usage: 82.7672
Standard out isn't showing any garbage characters at all. What do I need to change?
Added -b to top command and it works.
From man top:
-b :Batch-mode operation
Starts top in Batch mode, which could be useful for sending output
from top to other programs or to a file. In this mode, top will not
accept input and runs until the iterations limit you've set with the
`-n' command-line option or until killed.

Resources