#!/bin/bash # --- Configuration --- REMOTE_USER="webadmin" # Replace with your remote SSH user REMOTE_HOST="your-server.example.com" # Replace with your server hostname or IP SSH_KEY_PATH="${HOME}/.ssh/id_rsa" # Path to your private SSH key COMMAND_TO_RUN="uptime && df -h /var/www" # Command(s) to execute on the remote server LOG_FILE="/var/log/remote_exec.log" set -e set -u set -o pipefail log() { local type="$1" local message="$2" echo "$(date '+%Y-%m-%d %H:%M:%S') [REMOTE_EXEC] [${type}] ${message}" | tee -a "${LOG_FILE}" } error_exit() { log "ERROR" "Script failed at line ${BASH_LINENO[0]} while executing: '${BASH_COMMAND}'" exit 1 } trap 'error_exit' ERR # --- Main Logic --- log "INFO" "Attempting to execute commands on remote host ${REMOTE_USER}@${REMOTE_HOST}." # Check if SSH key exists if [ ! -f "${SSH_KEY_PATH}" ]; then log "FATAL" "SSH private key not found at ${SSH_KEY_PATH}. Please ensure it exists and has correct permissions." exit 1 fi # SSH command with strict host key checking and key authentication # -o BatchMode=yes prevents password prompts (useful for automation) # -o StrictHostKeyChecking=no is NOT recommended for production, use 'yes' or specify known_hosts # For first connection, you might need to run 'ssh user@host' manually to accept the host key. # Alternatively, pre-add the host key to ~/.ssh/known_hosts SSH_OPTIONS="-i \"${SSH_KEY_PATH}\" -o BatchMode=yes -o ConnectTimeout=10" # For production, consider StrictHostKeyChecking=yes and UserKnownHostsFile if needed # SSH_OPTIONS+="-o StrictHostKeyChecking=yes -o UserKnownHostsFile=/path/to/known_hosts" log "INFO" "Executing: ssh ${REMOTE_USER}@${REMOTE_HOST} ${SSH_OPTIONS} \"${COMMAND_TO_RUN}" " # Execute the command on the remote server # We use 'bash -s' to send commands over stdin for complex scripts, # but for simple commands, direct execution is fine. # Here, directly executing the command string. ssh "${REMOTE_USER}@${REMOTE_HOST}" ${SSH_OPTIONS} "${COMMAND_TO_RUN}" # Check the exit status of the SSH command SSH_EXIT_STATUS=$? if [ ${SSH_EXIT_STATUS} -eq 0 ]; then log "INFO" "Remote command execution successful." else log "ERROR" "Remote command execution failed with exit status ${SSH_EXIT_STATUS}." exit 1 fi # Example: Copy a file to the remote server using scp LOCAL_FILE="./local_config.txt" REMOTE_PATH="/tmp/remote_config.txt" if [ -f "${LOCAL_FILE}" ]; then log "INFO" "Copying '${LOCAL_FILE}' to '${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}' using scp." scp ${SSH_OPTIONS} "${LOCAL_FILE}" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}" log "INFO" "File copied successfully via scp." else log "WARN" "Local file '${LOCAL_FILE}' not found, skipping scp." fi log "INFO" "Remote command execution script finished."