Skip to content

Instantly share code, notes, and snippets.

@mrakitin
Last active October 20, 2020 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrakitin/839a143f89557856874279afc6646d86 to your computer and use it in GitHub Desktop.
Save mrakitin/839a143f89557856874279afc6646d86 to your computer and use it in GitHub Desktop.
Switch ssh proxy configuration via a bash function
switch_proxy() {
allowed_values=("o", "i")
cfg_file="$HOME/.ssh/config"
tmp_file="${cfg_file}_tmp"
ssh_base="ssh"
# ProxyCommand ssh -q -W %h:22 issh
current_pattern="ProxyCommand ssh -q -W %h:22 .${ssh_base}"
current_proxy=$(grep -e "${current_pattern}" ${cfg_file} | head -1 | tail -1 | awk '{print $NF}')
current_proxy_symbol=$(echo ${current_proxy} | cut -c1)
if [[ ! "${allowed_values[@]}" =~ "${current_proxy_symbol}" ]]; then
echo "Symbol '${current_proxy_symbol}' is not allowed."
echo "Allowed values: ${allowed_values[@]}"
return
fi
if [ -n "$1" ]; then
new_proxy_symbol="${1:0:1}"
if [[ ! "${allowed_values[@]}" =~ "${new_proxy_symbol}" ]]; then
echo "Symbol '${new_proxy_symbol}' is not allowed."
echo "Allowed values: ${allowed_values[@]}"
return
fi
else
if [ "${current_proxy_symbol}" == "o" ]; then
new_proxy_symbol="i"
elif [ "${current_proxy_symbol}" == "i" ]; then
new_proxy_symbol="o"
fi
fi
new_proxy="${new_proxy_symbol}${ssh_base}"
new_pattern=$(echo ${current_pattern} | sed 's/\./'"${new_proxy_symbol}"'/')
echo " Old proxy : ${current_proxy}"
echo " New proxy : ${new_proxy}"
sed 's;'"$current_pattern"';'"$new_pattern"';g' ${cfg_file} > ${tmp_file}
mv ${tmp_file} ${cfg_file}
verify=$(grep -e "${current_pattern}" ${cfg_file} | head -1 | tail -1 | sed 's/^ *//g')
echo " Verification : ${verify}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment