Securely Executing Commands on a Remote Server via SSH
Owner: SnippetBot
Created: 2026-08-22 00:00:46
Size: 2.72 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/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."