Add various sshroot options
[user/alex/software/my-snippets.git] / sshroot
1 #!/bin/bash
2
3 # lifetime, in minutes
4 lifetime=15
5 keysuffix=root
6
7 hostopt=""
8 [ -z "$hostopt" ] && hostopt="${HOSTNAME}"
9 [ -z "$hostopt" ] && hostopt=`uname -n 2>/dev/null || echo unknown`
10
11 while getopts "H:k:l:" opt; do
12     case "$opt" in
13     H)  hostopt="$OPTARG";;
14     k)  keysuffix="$OPTARG";;
15     l)  lifetime="$OPTARG";;
16     \?) die "$0 [-H hostname] [-k keysuffix] [-l lifetime]"
17     esac
18 done
19 shift $(($OPTIND - 1))
20
21 keys="$HOME/.ssh/id_rsa_$keysuffix"
22 keychain_host="$hostopt-$keysuffix"
23
24 function with-keys
25 {
26     unset SSH_AUTH_SOCK SSH_AGENT_PID
27     eval $(keychain --timeout "$lifetime" --eval --host "$keychain_host" $keys)
28     export SSHROOT=1
29     exec "$@"
30 }
31
32 function with-agent
33 {
34     unset SSH_AUTH_SOCK SSH_AGENT_PID
35     eval $(keychain --timeout "$lifetime" --eval --host "$keychain_host")
36     export SSHROOT=1
37     echo with-agent: Running: "$@"
38     exec "$@"
39 }
40
41 command="$1"
42 shift
43
44 case "$command" in
45     init)
46         echo "Loading default keys (lifetime $lifetime)..."
47         with-agent ssh-add -t "${lifetime}m" "$@" $keys
48         ;;
49     add)
50         echo "Loading keys (lifetime $lifetime):" "$@"
51         with-agent ssh-add -t "${lifetime}m" "$@"
52         ;;
53     list)
54         with-agent ssh-add -l
55         ;;
56     destroy)
57         with-agent ssh-add -D
58         ;;
59     shell)
60         with-keys "$SHELL" "$@"
61         ;;
62     ssh)
63         #with-keys ssh -l root "$@"
64         with-keys ssh "$@"
65         ;;
66     *)
67         if [ -z "$command" ]; then
68             echo "Usage: $0 init" >&2
69             echo "       $0 add" >&2
70             echo "       $0 list" >&2
71             echo "       $0 destroy" >&2
72             echo "       $0 shell" >&2
73             echo "       $0 ssh [args]" >&2
74             echo "       $0 [cmd]" >&2
75         else
76             echo Executing: "$command" "$@"
77             with-agent "$command" "$@"
78         fi
79         ;;
80 esac