classify-users: determine type of Athena accounts
[user/alex/software/my-snippets.git] / sshroot
1 #!/bin/bash -e
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     vars=$(keychain --timeout "$lifetime" --eval --host "$keychain_host" $keys)
42     eval "$vars"
43     export SSHROOT=1
44     exec "$@"
45 }
46
47 function with-agent
48 {
49     unset SSH_AUTH_SOCK SSH_AGENT_PID
50     vars=$(keychain --timeout "$lifetime" --eval --host "$keychain_host")
51     eval "$vars"
52     export SSHROOT=1
53     echo with-agent: Running: "$@"
54     exec "$@"
55 }
56
57 command="$1"
58 shift
59
60 case "$command" in
61     init)
62         echo "Loading default keys (lifetime $lifetime)..."
63         with-agent ssh-add -t "${lifetime}m" "$@" $keys
64         ;;
65     add)
66         echo "Loading keys (lifetime $lifetime):" "$@"
67         with-agent ssh-add -t "${lifetime}m" "$@"
68         ;;
69     list)
70         with-agent ssh-add -l
71         ;;
72     destroy)
73         with-agent ssh-add -D
74         ;;
75     shell)
76         with-keys "$SHELL" "$@"
77         ;;
78     ssh)
79         #with-keys ssh -l root "$@"
80         with-keys ssh "$@"
81         ;;
82     *)
83         if [ -z "$command" ]; then
84             usage >&2
85         else
86             echo Executing: "$command" "$@"
87             with-agent "$command" "$@"
88         fi
89         ;;
90 esac