test / scripts /ssh-agent-autostart.sh
GGSheng's picture
feat: deploy Gemma 4 to hf space
08c964e verified
#!/bin/bash
# SSH Agent Auto-start Script
# Automatically starts ssh-agent and adds SSH keys from /root/.ssh/
# This script should be sourced from .bashrc or .profile
# Function to auto-start ssh-agent and add keys
__auto_start_ssh_agent() {
# Check if ssh-agent is already running
if [ -n "$SSH_AGENT_PID" ] && kill -0 "$SSH_AGENT_PID" 2>/dev/null; then
# ssh-agent is running, check if keys are loaded
loaded_keys=$(ssh-add -l 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$loaded_keys" ]; then
# Keys are already loaded
return 0
fi
fi
# Check for existing ssh-agent environment
if [ -f ~/.ssh-agent-env ]; then
source ~/.ssh-agent-env > /dev/null 2>&1
if [ -n "$SSH_AGENT_PID" ] && kill -0 "$SSH_AGENT_PID" 2>/dev/null; then
# Agent is running, check keys
loaded_keys=$(ssh-add -l 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$loaded_keys" ]; then
return 0
fi
fi
fi
# Start new ssh-agent
echo "Starting ssh-agent..."
eval "$(ssh-agent -s)" > /dev/null 2>&1
# Save environment variables for reuse
echo "export SSH_AGENT_PID=$SSH_AGENT_PID" > ~/.ssh-agent-env
echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK" >> ~/.ssh-agent-env
# Add all private keys from /root/.ssh/
if [ -d /root/.ssh ]; then
key_added=false
for keyfile in /root/.ssh/id_*; do
# Skip public keys (.pub) and known_hosts
if [[ "$keyfile" == *.pub ]] || [[ "$keyfile" == *known_hosts* ]]; then
continue
fi
# Check if it's a valid private key file
if [ -f "$keyfile" ]; then
# Check file permissions (should be 600)
perms=$(stat -c %a "$keyfile" 2>/dev/null || stat -f %Lp "$keyfile" 2>/dev/null)
if [ "$perms" != "600" ]; then
echo "Warning: Fixing permissions for $keyfile"
chmod 600 "$keyfile"
fi
# Try to add the key
echo "Adding SSH key: $keyfile"
if ssh-add "$keyfile" 2>/dev/null; then
key_added=true
echo "Successfully added: $(basename "$keyfile")"
else
echo "Note: Could not add $keyfile (may require passphrase)"
fi
fi
done
if [ "$key_added" = true ]; then
echo "SSH agent started and keys loaded successfully."
ssh-add -l
else
echo "No SSH keys were added. Place your private keys in /root/.ssh/"
fi
else
echo "Warning: /root/.ssh/ directory does not exist"
fi
}
# Run the auto-start function
__auto_start_ssh_agent
# Cleanup function name
unset -f __auto_start_ssh_agent