Making Sense of The Infinite

Unlocking Infinite Possibilities Through Curiosity

Run Remote Commands with SSH and Certificate Authentication on Linux / macOS Terminal

1. Ensure SSH Key-Based Authentication Is Set Up

Before proceeding, make sure you have SSH key-based authentication set up between your local machine and the remote server:

  1. Generate SSH Key Pair (if not already done): On your local machine, generate a new SSH key pair (private and public key):
ssh-keygen -t rsa -b 4096 -C "[email protected]"
ShellScript

By default, this creates the keys in ~/.ssh/id_rsa (private key) and ~/.ssh/id_rsa.pub (public key).

  • 2. Copy the Public Key to the Remote Server: Copy the public key (id_rsa.pub) to the remote server’s ~/.ssh/authorized_keys file.

You can use ssh-copy-id:

ssh-copy-id -i ~/.ssh/id_rsa.pub user@remote_host
ShellScript

Or, manually append the public key to the ~/.ssh/authorized_keys file on the remote server.

2. SSH Command to Execute Script Remotely

Once SSH key-based authentication is set up, you can log into the server and execute a script remotely by using the following script:

Make sure to replace username, IP Address, and other placeholders with your actual values.

To save the script as a local_execute.sh file locally:

#!/bin/bash

# Configuration
PRIVATE_KEY="/path/to/private_key"       # Path to the private key
REMOTE_USER="username"                  # Remote host username
REMOTE_HOST="remote_host_or_ip"         # Remote host address or IP
REMOTE_PORT="22"                        # SSH port (default is 22, change if necessary)
REMOTE_SCRIPT="/path/to/remote_script.sh" # Path to the remote script
LOG_FILE="/tmp/remote_execution.log"    # Path to the local log file

# Connect to the remote host and execute the script
echo "Connecting to the remote host on port $REMOTE_PORT and executing the script..."
ssh -i "$PRIVATE_KEY" -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" "bash $REMOTE_SCRIPT" > "$LOG_FILE" 2>&1

# Check the exit status
if [ $? -eq 0 ]; then
    echo "Script executed successfully. Exiting..."
else
    echo "Script execution failed. Check the log file for details: $LOG_FILE"
fi

# Terminate the terminal session
echo "Closing terminal session..."
exit
Bash

Make the script executable: After saving the file, you need to give it executable permissions. In the terminal, run:

chmod +x ./local_execute.sh
ShellScript

Run the script: To execute the script locally, you can run:

./local_execute.sh
ShellScript

This will execute the script on your local machine, which will connect to the remote server via SSH using the provided private key and run the specified script.

Last revised on

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *