Skip to content

Instantly share code, notes, and snippets.

@danhigham
Created September 17, 2025 05:45
Show Gist options
  • Select an option

  • Save danhigham/561f49141cfa4dc0778225fa2e825c41 to your computer and use it in GitHub Desktop.

Select an option

Save danhigham/561f49141cfa4dc0778225fa2e825c41 to your computer and use it in GitHub Desktop.
Connect to multiple machines in sync
#!/usr/bin/expect -f
# This script automates the 'remote-con' login process.
# Check for a hostname argument.
if {$argc != 1} {
puts "Usage: $argv0 <hostname>"
exit 1
}
set hostname [lindex $argv 0]
# Set a timeout for expect commands (in seconds).
set timeout 20
# Start the remote-con process.
spawn remote-con $hostname
# 1. Expect the confirmation prompt and send "y".
expect "accept the connection for 30 minutes?"
send "y\r"
# 2. Expect the passphrase output and the subsequent prompt.
# This regex captures the passphrase from the line just before
# the "passphrase:" prompt.
expect -re "(\[a-zA-Z0-9_.-]+)\r\n.*passphrase:"
# The captured passphrase is now in the 'expect_out(1,string)' variable.
set captured_passphrase $expect_out(1,string)
# 3. Send the captured passphrase back to the prompt.
send "$captured_passphrase\r"
# 4. Hand over control of the connection to you.
# The script is done, and you now have a live shell.
interact
#!/bin/bash
# A script to connect to multiple hosts using an automated expect script.
# --- IMPORTANT ---
# Set the path to your expect script here.
# Both scripts should be in the same directory or a directory in your $PATH.
EXPECT_SCRIPT="auto-con.exp"
# Check if the expect script is available and executable.
if ! command -v "$EXPECT_SCRIPT" &> /dev/null; then
echo "Error: Expect script '$EXPECT_SCRIPT' not found in your PATH or not executable."
echo "Please ensure both scripts are in a directory listed in your \$PATH (e.g., /usr/local/bin)."
exit 1
fi
# Check if at least one host is provided.
if [ "$#" -eq 0 ]; then
echo "Usage: $0 <ssh_alias1> [ssh_alias2] [ssh_alias3] ..."
exit 1
fi
SESSION_NAME="remote-broadcast-$$"
first_host="$1"
shift
# The command to run is now the expect script with the host as an argument.
COMMAND_TO_RUN="$EXPECT_SCRIPT $first_host"
echo "Starting tmux session '$SESSION_NAME' and connecting to $first_host..."
tmux new-session -d -s "$SESSION_NAME" "$COMMAND_TO_RUN"
for host in "$@"; do
COMMAND_TO_RUN="$EXPECT_SCRIPT $host"
echo "Connecting to $host..."
tmux split-window -t "$SESSION_NAME"
tmux send-keys -t "$SESSION_NAME" "$COMMAND_TO_RUN" C-m
done
tmux select-layout -t "$SESSION_NAME" tiled
tmux set-window-option -t "$SESSION_NAME" synchronize-panes on
echo "Attaching to session. Use 'Ctrl+b' then ':set synchronize-panes off' to disable cloning."
tmux attach-session -t "$SESSION_NAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment