LLI Wiki — My Digital Knowledge Base

Run a Bash script on remote servers over SSH

Check memory, CPU, TCP connections and kernel on a list of Linux servers using ssh and bash -s.

Run a local Bash health-check script on several remote Linux servers over SSH, without copying the script to them.

The check script

remote_check.sh prints memory usage, CPU load, the number of TCP connections and the kernel version.

#!/bin/bash

##
# BASH script that checks the following:
#   - Memory usage
#   - CPU load
#   - Number of TCP connections
#   - Kernel version
##

server_name=$(hostname)

function memory_check() {
    echo "#######"
    echo "The current memory usage on ${server_name} is: "
    free -h
    echo "#######"
}

function cpu_check() {
    echo "#######"
    echo "The current CPU load on ${server_name} is: "
    echo ""
    uptime
    echo "#######"
}

function tcp_check() {
    echo "#######"
    echo "Total TCP connections on ${server_name}: "
    echo ""
    cat /proc/net/tcp | wc -l
    echo "#######"
}

function kernel_check() {
    echo "#######"
    echo "The exact Kernel version on ${server_name} is: "
    echo ""
    uname -r
    echo "#######"
}

function all_checks() {
    memory_check
    cpu_check
    tcp_check
    kernel_check
}

all_checks

The loop

main.sh reads the server names from servers.txt (one per line) and feeds the script to a remote shell through standard input (bash -s), so nothing is stored on the target.

for server in $(cat servers.txt) ; do ssh root@${server} 'bash -s' < ./remote_check.sh ; done

Notes

Mastodon LLIMastodon SocialFosstodon