Skip to content

Instantly share code, notes, and snippets.

@k4yt3x
Last active August 11, 2020 13:05
Show Gist options
  • Save k4yt3x/ef570345478762bca1c297042a07b31f to your computer and use it in GitHub Desktop.
Save k4yt3x/ef570345478762bca1c297042a07b31f to your computer and use it in GitHub Desktop.
ipr: A shell alias that will simplify your "ip route" output

ipr

Description

ipr is a shell function that will display the distilled informaiton from the ip r command.

Screenshots

image

Usage

ipr  # display IPv4 routes
ip4r  # display IPv4 routes
ip6r  # display IPv6 routes

Code

Add this into your shell configuration file (e.g., ~/.bashrc or ~/.zshrc).

# ipr prints distilled output of the "ip r" command
# version 1.1.0
alias ip4r="ipr -4"
alias ip6r="ipr -6"
function ipr() {
    python3 - $@ << EOF
import contextlib, json, subprocess, sys
e = ['ip', '-j', 'r']
e.insert(2, '-4') if len(sys.argv) >= 2 and sys.argv[1] == '-4' else None
e.insert(2, '-6') if len(sys.argv) >= 2 and sys.argv[1] == '-6' else None
s = subprocess.Popen(e, stdout=subprocess.PIPE)
j = s.communicate()[0]
sys.exit(s.returncode) if s.returncode != 0 else None
for r in json.loads(j):
    with contextlib.suppress(Exception):
        print(r['dst'])
        print('    Gateway: {}'.format(r['gateway'])) if r.get('gateway') else None
        print('    Device: {}'.format(r['dev'])) if r.get('dev') else None
        print('    Protocol: {}'.format(r['protocol'])) if r.get('protocol') else None
        print('    Metric: {}'.format(r['metric'])) if r.get('metric') else None
        print('    Source: {}'.format(r['prefsrc'])) if r.get('prefsrc') else None
EOF
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment