โ† scripts 5 min read

Automating SSH Connections with TMUX Sessions: A Comprehensive Guide

Efficiently managing multiple SSH connections can be a hassle, especially if you frequently access different servers. Combining SSH and TMUX allows you to streamline this process. This article presents a powerful bash script that automates TMUX session creation, connects to remote servers, and maintains reusable server credentials in a configuration file.

Why Use TMUX with SSH?

TMUX is a terminal multiplexer that lets you create, manage, and switch between multiple terminal sessions. Using TMUX with SSH provides several advantages:

Script Features

This script offers:

  1. Command-line Arguments: Specify session name, username, IP address, RSA key path, and password via flags.
  2. Password Management: Save and update passwords securely in the servers.txt file.
  3. Reusable Configuration: Save server credentials in a servers.txt file for future use.
  4. Interactive Setup: If a session name isn't found, it prompts for details and optionally adds them to the configuration.
  5. Error Handling: Verifies SSH connectivity before creating a TMUX session, providing detailed error messages if the connection fails.

How It Works

The script processes the following flags:

If the session name isnโ€™t found in servers.txt, the script prompts for the missing information, adds it to the configuration file if approved, and then establishes the SSH connection.

Installation and Usage

  1. Save the script below as tmux_ssh_manager.sh.
  2. Make it executable:
    chmod +x tmux_ssh_manager.sh
  3. Run the script:
    ./tmux_ssh_manager.sh --name=SESSION_NAME [--user=USERNAME] [--ip=IP_ADDRESS] [--key=KEY_PATH] [--password=PASS_HERE]

Example:

./tmux_ssh_manager.sh --name=PT-51 --user=admin --ip=10.10.1.105 --key=/path/to/key --password=mysecurepassword

To update a password for an existing session:

./tmux_ssh_manager.sh --name=PT-51 --update_password=newsecurepassword

To connect using existing information in servers.txt:

./tmux_ssh_manager.sh --name=PT-51

Error Handling

The script verifies SSH connectivity before creating a TMUX session. If the connection fails, it provides potential reasons such as invalid credentials, key mismatch, or network issues.

The Script

Below is the full script:

#!/bin/bash

# Path to the servers file
SERVERS_FILE="servers.txt"

# Function to display usage
usage() {
    echo "Usage: $0 --name=SESSION_NAME [--user=USERNAME] [--ip=IP_ADDRESS] [--key=KEY_PATH] [--password=PASS_HERE] [--update_password=PASS_HERE]"
    exit 1
}

# Parse arguments
SESSION_NAME=""
USERNAME=""
IP=""
RSA_KEY=""
PASSWORD=""
UPDATE_PASSWORD=""

for arg in "$@"; do
    case $arg in
        --name=*)
            SESSION_NAME="${arg#*=}"
            ;;
        --user=*)
            USERNAME="${arg#*=}"
            ;;
        --ip=*)
            IP="${arg#*=}"
            ;;
        --key=*)
            RSA_KEY="${arg#*=}"
            ;;
        --password=*)
            PASSWORD="${arg#*=}"
            ;;
        --update_password=*)
            UPDATE_PASSWORD="${arg#*=}"
            ;;
        *)
            echo "Unknown argument: $arg"
            usage
            ;;
    esac
done

# Validate mandatory argument
if [[ -z "$SESSION_NAME" ]]; then
    echo "Error: --name is required."
    usage
fi

# Function to escape special characters in user input
sanitize_input() {
    local input="$1"
    echo "$input" | sed 's/\([\"\`\\]\)/\\\1/g'
}

# Sanitize inputs
SESSION_NAME=$(sanitize_input "$SESSION_NAME")
USERNAME=$(sanitize_input "$USERNAME")
IP=$(sanitize_input "$IP")
RSA_KEY=$(sanitize_input "$RSA_KEY")
PASSWORD=$(sanitize_input "$PASSWORD")
UPDATE_PASSWORD=$(sanitize_input "$UPDATE_PASSWORD")

# Check if the servers file exists
if [[ ! -f "$SERVERS_FILE" ]]; then
    echo "Error: Servers file '$SERVERS_FILE' not found."
    exit 1
fi

# Search for the session in the servers file
SERVER_ENTRY=$(grep -E "^$SESSION_NAME " "$SERVERS_FILE")

if [[ -n "$UPDATE_PASSWORD" ]]; then
    if [[ -z "$SERVER_ENTRY" ]]; then
        echo "Error: No entry found for session '$SESSION_NAME' to update the password."
        exit 1
    fi
    sed -i "/^$SESSION_NAME /s/\([^ ]* \)\([^ ]* \)\([^ ]* \)\([^ ]*\)\$/\1\2\3$UPDATE_PASSWORD/" "$SERVERS_FILE"
    echo "Password updated for session '$SESSION_NAME'."
    exit 0
fi

if [[ -z "$SERVER_ENTRY" ]]; then
    echo "No entry found for session '$SESSION_NAME'."

    # If user or IP is missing, they must be provided interactively or via flags
    if [[ -z "$USERNAME" ]]; then
        read -p "Enter username: " USERNAME
    fi

    if [[ -z "$IP" ]]; then
        read -p "Enter IP address: " IP
    fi

    # Confirm addition to servers.txt
    read -p "Do you want to save this information to servers.txt for future use? (yes/no): " CONFIRM
    if [[ "$CONFIRM" =~ ^[Yy][Ee][Ss]$ ]]; then
        echo "$SESSION_NAME $USERNAME $IP $RSA_KEY $PASSWORD" >> "$SERVERS_FILE"
        echo "Entry added to servers.txt."
    fi
else
    # Extract details from the servers file
    USERNAME=$(echo "$SERVER_ENTRY" | awk '{print $2}')
    IP=$(echo "$SERVER_ENTRY" | awk '{print $3}')
    RSA_KEY=$(echo "$SERVER_ENTRY" | awk '{print $4}')
    PASSWORD=$(echo "$SERVER_ENTRY" | awk '{print $5}')
fi

# Build SSH command
SSH_CMD="ssh $USERNAME@$IP"
if [[ -n "$RSA_KEY" ]]; then
    SSH_CMD="ssh -i $RSA_KEY $USERNAME@$IP"
fi
if [[ -n "$PASSWORD" ]]; then
    SSH_CMD="sshpass -p $PASSWORD $SSH_CMD"
fi

# Test SSH connection before creating a TMUX session
echo "Testing SSH connection to $USERNAME@$IP..."
$SSH_CMD -o BatchMode=yes -o ConnectTimeout=5 exit
if [[ $? -ne 0 ]]; then
    echo "Error: Unable to connect to $USERNAME@$IP."
    echo "Possible reasons:"
    echo "  - Invalid username or password."
    echo "  - RSA key mismatch or missing permissions."
    echo "  - Network issues or unreachable server."
    exit 1
fi

# Create a TMUX session
TMUX_CMD="tmux new-session -d -s $SESSION_NAME \"$SSH_CMD\""

echo "Creating TMUX session named '$SESSION_NAME' and connecting to $USERNAME@$IP..."
eval $TMUX_CMD

if [[ $? -eq 0 ]]; then
    echo "TMUX session '$SESSION_NAME' created successfully."
    tmux attach-session -t $SESSION_NAME
else
    echo "Failed to create TMUX session."
    exit 1
fi