通过 SSH 将远程端口映射到本地,或将本地端口映射到远程服务器
#!/usr/bin/env bash
set -e
HELP=""
MODE="L"
SOURCE_PORT=""
TARGET_PORT=""
for ARG in "$@"; do
case "$ARG" in
-h | --help)
shift
HELP="true"
;;
-l | --local)
shift
if [ $# -ge 1 ] && [[ "${1}" != -* ]]; then
SOURCE_PORT="${1}"
fi
;;
-m | --mode)
shift
if [ $# -ge 1 ] && [[ "${1}" != -* ]]; then
if [[ "${1}" = "R" || "${1}" = "r" ]]; then
MODE="R"
fi
fi
;;
-r | --remote)
shift
if [ $# -ge 1 ] && [[ "${1}" != -* ]]; then
TARGET_PORT="${1}"
fi
;;
*)
shift
;;
esac
done
if [[ -n "${HELP}" ]]; then
echo "lbscp -m R/L -l SOURCE_PORT -m TARGET_PORT"
exit
fi
if [[ -z "$SOURCE_PORT" || -z "$TARGET_PORT" ]]; then
echo "请指定本地端口和远程端口"
exit
fi
# 将远程端口映射到本地(远程端口转发):
# ssh -L [本地端口]:[目标主机]:[目标端口] [用户名]@[远程主机]
# 将本地端口映射到远程(本地端口转发):
# ssh -R [远程端口]:localhost:[本地端口] [用户名]@[远程主机]
KEY_PATH="$HOME/.ssh/keys/id_ed25519"
SERVER_INFO="root@192.168.3.33"
if [[ "$MODE" = "R" ]]; then
echo "将本地端口 ${SOURCE_PORT} 映射到远程端口 ${TARGET_PORT}"
# shellcheck disable=SC2086
ssh -R "${TARGET_PORT}":127.0.0.1:"${SOURCE_PORT}" -N -i $KEY_PATH -p 2022 $SERVER_INFO
else
echo "将远程端口 ${TARGET_PORT} 映射到本地端口 ${SOURCE_PORT}"
# shellcheck disable=SC2086
ssh -L "${SOURCE_PORT}":127.0.0.1:"${TARGET_PORT}" -N -i $KEY_PATH -p 2022 $SERVER_INFO
fi