sshroot: handle unknown args correctly
[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 function usage
12 {
13     echo "Usage: $0 [-H hostname] [-k keysuffix] [-l lifetime] command"
14     echo
15     echo "Available commands:"
16     echo "    add"
17     echo "    list"
18     echo "    destroy"
19     echo "    shell"
20     echo "    ssh [args]"
21     echo "    [cmd]"
22 }
23
24 while getopts ":H:k:l:h" opt; do
25     case "$opt" in
26     H)  hostopt="$OPTARG";;
27     k)  keysuffix="$OPTARG";;
28     l)  lifetime="$OPTARG";;
29     h)  usage; exit 0;;
30     \?) usage >&2; exit 1;;
31     esac
32 done
33 shift $(($OPTIND - 1))
34
35 keys="$HOME/.ssh/id_rsa_$keysuffix"
36 keychain_host="$hostopt-$keysuffix"
37
38 function with-keys
39 {
40     unset SSH_AUTH_SOCK SSH_AGENT_PID
41     eval $(keychain --timeout "$lifetime" --eval --host "$keychain_host" $keys)
42     export SSHROOT=1
43     exec "$@"
44 }
45
46 function with-agent
47 {
48     unset SSH_AUTH_SOCK SSH_AGENT_PID
49     eval $(keychain --timeout "$lifetime" --eval --host "$keychain_host")
50     export SSHROOT=1
51     echo with-agent: Running: "$@"
52     exec "$@"
53 }
54
55 command="$1"
56 shift
57
58 case "$command" in
59     init)
60         echo "Loading default keys (lifetime $lifetime)..."
61         with-agent ssh-add -t "${lifetime}m" "$@" $keys
62         ;;
63     add)
64         echo "Loading keys (lifetime $lifetime):" "$@"
65         with-agent ssh-add -t "${lifetime}m" "$@"
66         ;;
67     list)
68         with-agent ssh-add -l
69         ;;
70     destroy)
71         with-agent ssh-add -D
72         ;;
73     shell)
74         with-keys "$SHELL" "$@"
75         ;;
76     ssh)
77         #with-keys ssh -l root "$@"
78         with-keys ssh "$@"
79         ;;
80     *)
81         if [ -z "$command" ]; then
82             usage >&2
83         else
84             echo Executing: "$command" "$@"
85             with-agent "$command" "$@"
86         fi
87         ;;
88 esac