A few piped Linux commands and short scripts

Here’s a couple of bash and Perl scripts, and piped Linux commands that I’ve found to be useful. Let me know if you are having trouble with any of these. Your mileage may vary depending on your version of bash and Perl.

Current CPU Usage in percent (bash):

You can get the same info from other tools like htop and mpstat, but they might not be installed by default.

# Linux
top -bn 10 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | awk '{cpu_use = $2 + $4 + $6 ; printf("%.2f\n", cpu_use)}'
# Solaris
top -bn 10 -d 0.01 | grep 'CPU states' | awk -F ' |%' '{cpu_use = $7 + $11 ; printf("%.2f\n", cpu_use)}'


Current RAM Usage in percent (bash):

# Linux
free -m | awk 'FNR == 2 { ratio = $3 / $2 ; ram_use = ratio * 100 ; printf("%.2f\n", ram_use)}'
# Solaris
top -bn 10 -d 0.01 | grep 'Memory' | awk -F \" |G\" '{used = $2 - $6 ; ram_use = (used / $2) * 100 ; printf("%.2f\n", ram_use)}'


System Usage (perl):

#!/usr/bin/perl
my $linuxCPUpct = "top -bn 10 -d 0.01 | grep '^Cpu.s.' | tail -n 1" ;  # CPU usage
my $linuxRAMpct = "free -m | grep 'Mem:'" ;  	# RAM usage
my $linuxROOTpct = "df -hl / | grep '/'" ;  	# / disk usage
my $linuxHOMEpct = "df -hl /home | grep 'home'" ;  # /home disk usage

my $cpu_res = "" ; my $ram_res = "" ; my $root_res = "" ; my $home_res = "" ;

my @CPU_parse = split ( ',', `$linuxCPUpct` ) ;
my @RAM_parse = split ( ' ', `$linuxRAMpct` );
my $linuxROOT = (`$linuxROOTpct` =~ /(\d+)%/img)[0] ;
my $linuxHOME = (`$linuxHOMEpct` =~ /(\d+)%/img)[0] ;

$ram_res = sprintf("%.2f", $RAM_parse[2] / $RAM_parse[1] * 100.0 ) ;
$cpu_res = sprintf("%.2f", substr($CPU_parse[3], 0, -3)) ;
$root_res = sprintf("%.2f", $linuxROOT) ;
$home_res = sprintf("%.2f", $linuxHOME) ;

print ("CPU Usage: $cpu_res\n") ;
print ("RAM Usage: $ram_res\n") ;
print ("/ Usage: $root_res\n") ;
print ("/home Usage: $home_res\n") ;


Reset Password expiry script (bash):

Perhaps not the best idea security wise, but it’s handy when you’re lazy.

#!/bin/sh
pwd_age=$(grep "username:" /etc/shadow | cut -d: -f 3)
echo $pwd_age;
now=$(( $(date +%s) / 3600 / 24 ))
echo $now;
age_at_expiry_date=$(( $now + 90 - $pwd_age))
echo $age_at_expiry_date;
chage username -M $age_at_expiry_date


Multi-Ping script (bash):

Self-explanatory. Pass the IPs as arguments to mping.

#!/bin/sh
# mping: Multiple ping
# Script to ping multiple units. Each unit is pinged 4 times.

args=$#;
arrArgs=("$@");
i=0;

for args
do
        ping -c 4 ${arrArgs[$i]}
        ((i++))
        echo -e "\n"
done

And a few words of wisdom…

minority-reportr-erasmus