3.0 KiB
Running On Multiple Servers
Automate script execution across multiple remote servers. Instead of manual copying and logging in, learn to run Bash scripts on many machines with a single command.
Prerequisites
You'll need a few remote Linux servers with SSH access. Gather their IP addresses or hostnames and list them in a file named servers.txt, one per line.
Create servers.txt:
touch servers.txt
Open servers.txt and add your server details:
your_server_ip_1
your_server_ip_2
your_server_ip_3
The Script for Remote Execution
We'll use a simple Bash script that performs basic server checks: memory, CPU, TCP connections, and kernel version. Create a file named remote_check.sh and add the following content:
touch remote_check.sh
Open remote_check.sh and add:
#!/usr/bin/env bash
##
# Server status script:
# - 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
Execute on Remote Servers
With remote_check.sh and servers.txt ready, run the following single command. This loop iterates through each server, using SSH to execute the script without local file transfer or manual logins.
for server in $(cat servers.txt); do ssh your_user@"${server}" 'bash -s' < ./remote_check.sh; done
Breakdown:
for server in $(cat servers.txt): Reads each IP/hostname fromservers.txtinto theservervariable.ssh your_user@"${server}": Connects to the remote server via SSH asyour_user.'bash -s': Executes a Bash shell on the remote server, reading commands from standard input.< ./remote_check.sh: Redirects the localremote_check.shscript's content to the remote Bash shell's standard input.
Each server will then execute the script, printing its status checks directly to your local terminal.
Conclusion
This method efficiently executes Bash scripts across multiple remote servers. It avoids manual file transfers and individual logins, proving scalable for more complex scripts and larger environments. For extensive, state-managed automation, dedicated tools are often recommended.
{notice} This content was inspired by a piece by softwareshinobi on Dev Team Six.