Created
July 13, 2011 10:14
-
-
Save tehmaze/1080039 to your computer and use it in GitHub Desktop.
zsh/bash "command not found" handler that will use ssh if $1 resolves
This file contains 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
# | |
# _______ | |
# ____________ _______ _\__ /_________ ___ _____ | |
# | _ _ \ _ | ____\ _ / | |/ _ \ | |
# | / / / / | | | /___/ _ | | / / | |
# |___/___/ /___/____|________|___ | |_| |___|_____/ | |
# \__/ |___| | |
# | |
# | |
# Put this in your ~/.zshrc or ~/.bashrc: | |
# source ~/.zsh/ssh | |
# | |
# (c) 2011 Wijnand Modderman-Lenstra <maze@pyth0n.org> | |
# MIT License | |
# | |
is_ip() { | |
IP="$1" | |
python - "${IP}" <<EOF | |
import socket | |
import sys | |
# Check IPv6 | |
if socket.has_ipv6: | |
try: | |
socket.inet_pton(socket.AF_INET6, sys.argv[1]) | |
sys.exit(0) | |
except socket.error: | |
pass | |
# Check IPv4 | |
try: | |
socket.inet_pton(socket.AF_INET, sys.argv[1]) | |
sys.exit(0) | |
except socket.error: | |
sys.exit(1) | |
EOF | |
return $? | |
} | |
try_connect_ssh() { | |
# If only one argument is supplied and $1 resolves into a hostname, | |
# connect there using ssh | |
if [[ $# -gt 0 ]]; then | |
RESOLVES=$(host -W 2 $1 2>/dev/null | grep -v NXDOMAIN) | |
if [ -z "${RESOLVES}" ]; then | |
if is_ip "$1"; then | |
RESOLVES="$1" | |
fi | |
fi | |
if [ $? -eq 0 -a -n "${RESOLVES}" ]; then | |
ssh "$@" | |
# Tell zsh we did handle the command | |
return 0 | |
fi | |
fi | |
. | |
# Tell zsh we didn't handle the command | |
return 1 | |
} | |
case "${SHELL}" in | |
*/zsh) | |
command_not_found_handler() { | |
try_connect_ssh "$@" | |
return $? | |
} | |
;; | |
*/bash) | |
command_not_found_handle() { | |
try_connect_ssh "$@" | |
return $? | |
} | |
;; | |
esac |
Updated the file so that you can also use IP addresses:
shell% 127.0.0.1
Password:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated the file so you can also use stuff like:
shell% <hostname> -l root