]> arthur.barton.de Git - ax-zsh.git/blob - default_plugins/ssh/ssh.zshrc
ssh: Add "verbose" option to ssh-autoadd function
[ax-zsh.git] / default_plugins / ssh / ssh.zshrc
1 # AX-ZSH: Alex' Modular ZSH Configuration
2 # ssh.zshrc: Setup (Open-) SSH
3
4 # Make sure that "ssh(1)" is installed
5 (( $+commands[ssh] )) || return
6
7 # Load SSH keys into the SSH agent, when one is running and doesn't have
8 # any keys already. Not having an SSH agent running at all is ok as well and
9 # results in an "success" exit code (0) as well.
10 ssh-autoadd() {
11         [[ -z "$SSH_AUTH_SOCK" ]] && return 0
12         ssh-add -l >/dev/null && return 0
13         [[ $? -eq 2 ]] && return 2
14         [[ "$1" = "-v" ]] && echo "SSH agent is running, but has no identities."
15         ssh-add
16 }
17
18 _ax_ssh_prompt() {
19         [[ -n "$SSH_CLIENT" ]] || return 1
20         return 0
21 }
22
23 ax_logname_prompt_functions=($ax_logname_prompt_functions _ax_ssh_prompt)
24 ax_hostname_prompt_functions=($ax_hostname_prompt_functions _ax_ssh_prompt)
25
26 # Validate SSH_AUTH_SOCK: Inside of screen(1) sessions for example, the socket
27 # file becomes invalid when the session has been disconnected.
28 [[ ! -r "$SSH_AUTH_SOCK" ]] && unset SSH_AUTH_SOCK
29
30 # Save SSH environment when available:
31 if [[ -n "$SSH_AUTH_SOCK" && -d "$XDG_RUNTIME_DIR" ]]; then
32         # Save current environment when no state exists or is invalid.
33         if [[ -r "$XDG_RUNTIME_DIR/ssh-env.sh" ]]; then
34                 (
35                         source "$XDG_RUNTIME_DIR/ssh-env.sh"
36                         if [[ -z "$SSH_AUTH_SOCK" || ! -r "$SSH_AUTH_SOCK" ]]; then
37                                 # Content is invalid, remove state file!
38                                 rm -f "$XDG_RUNTIME_DIR/ssh-env.sh"
39                         fi
40                 )
41         fi
42         if [[ ! -r "$XDG_RUNTIME_DIR/ssh-env.sh" ]]; then
43                 # No state file exists, create a new one:
44                 echo "SSH_AUTH_SOCK=\"$SSH_AUTH_SOCK\"" >"$XDG_RUNTIME_DIR/ssh-env.sh"
45                 echo "export SSH_AUTH_SOCK" >>"$XDG_RUNTIME_DIR/ssh-env.sh"
46         fi
47 fi
48
49 # Restore SSH environment when not set but available:
50 if [[ -z "$SSH_AUTH_SOCK" && -r "$XDG_RUNTIME_DIR/ssh-env.sh" ]]; then
51         # Try to recover known good environment ...
52         source "$XDG_RUNTIME_DIR/ssh-env.sh"
53         if [[ ! -r "$SSH_AUTH_SOCK" ]]; then
54                 # Clean up!
55                 unset SSH_AUTH_SOCK
56                 rm -f "$XDG_RUNTIME_DIR/ssh-env.sh"
57         fi
58 fi