Skip to content

Instantly share code, notes, and snippets.

@drkibitz
Created December 31, 2024 06:00
Show Gist options
  • Save drkibitz/eda741ab8d6311ce3692ee334bc03b02 to your computer and use it in GitHub Desktop.
Save drkibitz/eda741ab8d6311ce3692ee334bc03b02 to your computer and use it in GitHub Desktop.
Wrap `ssh-add -L` to use forwarded ssh identities without having to saving keys to the remote host (long term that is).
#!/bin/bash
# Check if an argument is provided
if [[ -z "$1" ]]; then
echo "Usage: $0 <forwarded-key-identifier> [ssh-arguments...]"
exit 1
fi
# Extract and remove the first argument (forwarded key identifier)
forwarded_key_identifier="$1"
shift
# Create a secure temporary file
tmpfile=$(mktemp)
trap 'rm -f "$tmpfile"' EXIT
chmod 600 "$tmpfile"
# Extract the correct key and save it to the temporary file
if ! ssh-add -L | grep -w "$forwarded_key_identifier" > "$tmpfile"; then
echo "Error: Failed to retrieve keys from SSH agent or no matching key for '$forwarded_key_identifier'."
exit 1
fi
# Execute SSH with the temporary file and any additional arguments
ssh -i "$tmpfile" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment