mirror of
https://github.com/DictXiong/dotfiles.git
synced 2024-11-24 14:07:01 +08:00
130 lines
2.8 KiB
Bash
Executable File
130 lines
2.8 KiB
Bash
Executable File
#!/bin/bash
|
|
# connect to iot services
|
|
THIS_DIR=$( cd "$( dirname "${BASH_SOURCE[0]:-${(%):-%x}}" )" && pwd )
|
|
source "$THIS_DIR/../tools/common.sh"
|
|
|
|
# get target settings
|
|
# provides:
|
|
SERVER=""
|
|
PORT="" # optional
|
|
USERNAME="" # optional
|
|
SSH_OPTIONS="" # optional
|
|
get_server_meta()
|
|
{
|
|
arg="$1"
|
|
# overwrite
|
|
if [[ "$arg" == *@* ]]; then
|
|
USERNAME=${arg%%@*}
|
|
arg=${arg#*@}
|
|
fi
|
|
if [[ "$arg" == *:* ]]; then
|
|
PORT=${arg##*:}
|
|
arg=${arg%:*}
|
|
fi
|
|
# presets
|
|
local domain=${arg##*.}
|
|
local host=${arg%.*}
|
|
if [[ -z "$domain" ]]; then
|
|
domain="ibd"
|
|
fi
|
|
if [[ "$host" == "$domain" ]]; then
|
|
domain="proxied"
|
|
fi
|
|
case $domain in
|
|
ibd|ebd )
|
|
SERVER=$host.$domain.ink
|
|
PORT=${PORT:-12022}
|
|
USERNAME=${USERNAME:-root}
|
|
;;
|
|
nasp )
|
|
SERVER=$host
|
|
PORT=${PORT:-12022}
|
|
USERNAME=${USERNAME:-dictxiong}
|
|
SSH_OPTIONS='-o ProxyJump="ssh@nasp.ob.ac.cn:36022"'
|
|
;;
|
|
proxied )
|
|
SERVER=proxy.beardic.cn
|
|
local tmp=$(sha256sum <<< "$host" | tr -cd "[:digit:]")
|
|
tmp=${tmp:0:4}
|
|
PORT=$((10#$tmp+36000))
|
|
USERNAME=root
|
|
;;
|
|
* )
|
|
fmt_warning "unknown domain: $domain. will try as server name"
|
|
SERVER="$arg"
|
|
esac
|
|
}
|
|
|
|
# ssh
|
|
run_ssh()
|
|
{
|
|
CMD="ssh ${PORT:+-p} $PORT $SSH_OPTIONS $USERNAME${USERNAME:+@}$SERVER"
|
|
fmt_note "-->" $CMD
|
|
if [[ "$DFS_DRY_RUN" == "1" ]]; then
|
|
echo $CMD
|
|
else
|
|
eval $CMD
|
|
fi
|
|
}
|
|
|
|
# sshl
|
|
run_sshl()
|
|
{
|
|
if [[ -z "$1" ]]; then
|
|
fmt_fatal "invalid remote address: $1"
|
|
fi
|
|
arg="$1"
|
|
if [[ "$arg" != *":"* ]]; then
|
|
# treat as a port number
|
|
arg=localhost:$arg
|
|
fi
|
|
while
|
|
local port=$(shuf -n 1 -i 49152-65535)
|
|
netstat -atun | grep -q "$port"
|
|
do
|
|
continue
|
|
done
|
|
CMD="ssh ${PORT:+-p} $PORT $SSH_OPTIONS -NC -L $port:$arg $USERNAME${USERNAME:+@}$SERVER"
|
|
fmt_note "-->" $CMD
|
|
fmt_note " > please access localhost:$port"
|
|
if [[ "$DFS_DRY_RUN" == "1" ]]; then
|
|
echo $CMD
|
|
else
|
|
eval $CMD
|
|
fi
|
|
}
|
|
|
|
# main
|
|
print_help()
|
|
{
|
|
fmt_info "usage: $0 <service> [command] [options]"
|
|
echo "available commands: ssh (default), sshl (ssh -L)"
|
|
}
|
|
|
|
router()
|
|
{
|
|
if [[ -z "$1" || "$1" == "-h" || "$1" == "--help" ]]; then
|
|
print_help
|
|
exit
|
|
fi
|
|
get_server_meta "$1"
|
|
case $2 in
|
|
-h|--help)
|
|
print_help
|
|
exit
|
|
;;
|
|
ssh|"" )
|
|
run_ssh
|
|
;;
|
|
sshl )
|
|
run_sshl "$3"
|
|
;;
|
|
* )
|
|
print_help
|
|
fmt_fatal "unknown command: $2"
|
|
;;
|
|
esac
|
|
}
|
|
|
|
router "${GOT_OPTS[@]}"
|