BASH
Execute Remote Commands via SSH in Bash
Automate tasks on remote servers by securely executing commands over SSH directly from your Bash scripts, perfect for web server management and deployment.
#!/bin/bash
REMOTE_USER="webadmin"
REMOTE_HOST="your_server.com" # Replace with your actual server hostname or IP
REMOTE_WEB_ROOT="/var/www/html/myapp"
# --- Method 1: Execute a single command and check its exit status ---
echo "
--- Checking remote directory listing ---"
ssh "$REMOTE_USER@$REMOTE_HOST" "ls -la $REMOTE_WEB_ROOT"
if [ $? -eq 0 ]; then
echo "Remote 'ls' command executed successfully."
else
echo "Error: Remote 'ls' command failed. Check SSH connection/permissions."
fi
# --- Method 2: Execute multiple commands as a single string ---
echo "
--- Creating a remote test file and listing it ---"
ssh "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_WEB_ROOT && echo 'Hello from remote script' > remote_test_file.txt && ls remote_test_file.txt"
# --- Method 3: Execute a local script block remotely using a here-document ---
echo "
--- Running a more complex remote task (e.g., checking service status) ---"
ssh "$REMOTE_USER@$REMOTE_HOST" << 'EOF'
echo "Executing complex block on $(hostname)"
cd "$REMOTE_WEB_ROOT" || { echo "Error: Cannot change directory to $REMOTE_WEB_ROOT"; exit 1; }
DATE_STR=$(date +%Y%m%d_%H%M%S)
echo "Timestamp: $DATE_STR" >> remote_log.txt
echo "Checking web server status..."
systemctl is-active --quiet apache2 && echo "Apache is running." || echo "Apache is NOT running."
# Clean up the test file created earlier
rm -f remote_test_file.txt
echo "Remote cleanup complete."
EOF
# --- Method 4: Piping a local script into SSH ---
echo "
--- Running a local script on remote (piped) ---"
echo '#!/bin/bash
REMOTE_SCRIPT_VAR="Piped Variable"
echo "Remote script executed. Value: $REMOTE_SCRIPT_VAR"
' | ssh "$REMOTE_USER@$REMOTE_HOST" 'bash -s'
echo "
All remote operations attempted."
# Remember to set up SSH keys for passwordless authentication for automation.
How it works: This snippet illustrates various techniques for executing commands on a remote server via SSH directly from a Bash script. It covers running single commands, chaining multiple commands in a string, and executing multi-line script blocks using a 'here-document' for more complex tasks. It also demonstrates how to check the exit status of remote commands for error handling. This is a fundamental pattern for automating deployments, server maintenance, or retrieving information from remote web servers.