Last active
February 21, 2021 13:04
-
-
Save adipriyantobpn/87519ec6c9df8d1ca76aadfcd973e945 to your computer and use it in GitHub Desktop.
Autostart SSH-agent and autoload private keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Autostart SSH-agent and autoload all private keys in ~/.ssh directory | |
# | |
# How to use: | |
# - Place this scripts in ~/.bashrc | |
# - If ssh-agent is not filled by any private keys, passphrase prompts will show up for each private keys | |
# | |
# register ssh key | |
env=~/.ssh/agent.env | |
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; } | |
agent_start () { | |
(umask 077; ssh-agent >| "$env") | |
. "$env" >| /dev/null ; } | |
agent_load_env | |
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running | |
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?) | |
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then | |
agent_start | |
# this will load all private keys in ~/.ssh directory if agent not running | |
find ~/.ssh/ -type f -exec grep -l "PRIVATE" {} \; | xargs ssh-add &> /dev/null | |
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then | |
# this will load all private keys in ~/.ssh directory if agent is not filled with any private key | |
find ~/.ssh/ -type f -exec grep -l "PRIVATE" {} \; | xargs ssh-add &> /dev/null | |
fi | |
unset env | |
# shortcut for accessing server1 via SSH | |
function sshsvr1() { | |
( ssh user@server1.example.com -p 2222 ) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Use dedicated private key only for certain host | |
# | |
# How to use: | |
# - Place this scrips in ~/.ssh/config | |
# - Everytime you access certain host via SSH, its dedicated private key will be used | |
# | |
# Example: | |
# $ ssh user@server1.example.com -p 2222 | |
# | |
# Global SSH configurations here will be applied to all hosts | |
IdentityFile ~/.ssh/github_rsa | |
IdentityFile ~/.ssh/server1_rsa | |
IdentityFile ~/.ssh/server2_rsa | |
Host github | |
IdentityFile ~/.ssh/github_rsa | |
Host server1.example.com | |
IdentityFile ~/.ssh/server1_rsa | |
Host server2.example.com | |
IdentityFile ~/.ssh/server2_rsa |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you provide a format of ~/.ssh/agent.env file?