-
-
Save nickrw/4601229 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# A quick and dirty script for quickly SSHing to local vagrant virtual machines. | |
# It assumes default Vagrant port forwards. Your first VM is at 2222, your second | |
# is at 2200. Anything more than that and you're in trouble. | |
# Why? Because: | |
# | |
# $ ( time vagrant ssh -c echo ) 2>&1 | grep real | |
# real 0m4.870s | |
# | |
# Vs. | |
# | |
# $ ( time sshv echo ) 2>&1 | grep real | |
# real 0m0.106s | |
# | |
# High and low Vagrant default ssh port forwards. | |
VHPORT=2222 | |
VLPORT=2200 | |
# Options grabbed from `vagrant ssh-config' | |
SSHOPTS=$(cat <<EOF | |
-o UserKnownHostsFile=/dev/null | |
-o StrictHostKeyChecking=no | |
-o PasswordAuthentication=no | |
-o IdentityFile=~/.vagrant.d/insecure_private_key | |
-o IdentitiesOnly=yes | |
EOF) | |
# Return string 'true' or 'false' if $1 is a TCP | |
# port currently being listened on. | |
function tof() { | |
lsof -n -i4TCP:${1} > /dev/null | |
if [[ $? -eq 0 ]]; then | |
echo "true" | |
else | |
echo "false" | |
fi | |
} | |
# SSH to localhost on port $1, passing through the remainder | |
# of args to the SSH command. | |
function sshvport() { | |
port=${1} | |
shift 1 | |
ssh -p ${port} -l vagrant ${SSHOPTS} 127.0.0.1 $@ | |
exit $? | |
} | |
# Get state of the high and low vagrant port forwards | |
LHPORT=$(tof ${VHPORT}) | |
LLPORT=$(tof ${VLPORT}) | |
# If they're both the same either both are listening, or | |
# both are not. In either scenario we should defer to Vagrant. | |
if [[ ${LHPORT} == ${LLPORT} ]]; then | |
vagrant ssh $@ | |
exit $? | |
fi | |
# Attempt sshing to the highest number first, the first default | |
# port which Vagrant listens on. If it isn't, skip to the lowest, | |
# which is perversely the second one to be assigned. | |
${LHPORT} && sshvport ${VHPORT} $@ | |
${LLPORT} && sshvport ${VLPORT} $@ | |
# What is this I don't even. | |
echo "???" >&2 | |
exit 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment