From: Stephen Hemminger <stephen@networkplumber.org>
To: netdev@vger.kernel.org
Cc: Stephen Hemminger <stephen@networkplumber.org>
Subject: [PATCH iproute2-next 4/4] ip: rewrite routel in python
Date: Wed, 1 Sep 2021 13:47:01 -0700 [thread overview]
Message-ID: <20210901204701.19646-5-sthemmin@microsoft.com> (raw)
In-Reply-To: <20210901204701.19646-1-sthemmin@microsoft.com>
From: Stephen Hemminger <stephen@networkplumber.org>
Not sure if anyone uses the routel script. The script was
a combination of ip route, shell and awk doing command scraping.
It is now possible to do this much better using the JSON
output formats and python.
Rewriting also fixes the bug where the old script could not parse
the current output format. At the end was getting:
/usr/bin/routel: 48: shift: can't shift that many
The new script also has IPv6 as option.
Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
---
ip/routel | 124 +++++++++++++++++++++-------------------------
man/man8/routel.8 | 30 ++++++++---
2 files changed, 79 insertions(+), 75 deletions(-)
diff --git a/ip/routel b/ip/routel
index 7056886d0f94..09a901267fb3 100755
--- a/ip/routel
+++ b/ip/routel
@@ -1,72 +1,62 @@
-#!/bin/sh
+#! /usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
-
-#
-# Script created by: Stephen R. van den Berg <srb@cuci.nl>, 1999/04/18
-# Donated to the public domain.
-#
-# This script transforms the output of "ip" into more readable text.
-# "ip" is the Linux-advanced-routing configuration tool part of the
-# iproute package.
#
+# This is simple script to process JSON output from ip route
+# command and format it. Based on earlier shell script version.
+"""Script to parse ip route output into more readable text."""
+
+import sys
+import json
+import getopt
+import subprocess
+
+
+def usage():
+ '''Print usage and exit'''
+ print("Usage: {} [tablenr [raw ip args...]]".format(sys.argv[0]))
+ sys.exit(64)
+
+
+def main():
+ '''Process the arguments'''
+ family = 'inet'
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "h46f:", ["help", "family="])
+ except getopt.GetoptError as err:
+ print(err)
+ usage()
+
+ for opt, arg in opts:
+ if opt in ["-h", "--help"]:
+ usage()
+ elif opt == '-6':
+ family = 'inet6'
+ elif opt == "-4":
+ family = 'inet'
+ elif opt in ["-f", "--family"]:
+ family = arg
+ else:
+ assert False, "unhandled option"
+
+ if not args:
+ args = ['0']
+
+ cmd = ['ip', '-f', family, '-j', 'route', 'list', 'table'] + args
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ tbl = json.load(process.stdout)
+ if family == 'inet':
+ fmt = '{:15} {:15} {:15} {:8} {:8}{:<16} {}'
+ else:
+ fmt = '{:32} {:32} {:32} {:8} {:8}{:<16} {}'
+
+ # ip route json keys
+ keys = ['dst', 'gateway', 'prefsrc', 'protocol', 'scope', 'dev', 'table']
+ print(fmt.format(*map(lambda x: x.capitalize(), keys)))
-test "X-h" = "X$1" && echo "Usage: $0 [tablenr [raw ip args...]]" && exit 64
+ for record in tbl:
+ fields = [record[k] if k in record else '' for k in keys]
+ print(fmt.format(*fields))
-test -z "$*" && set 0
-ip route list table "$@" |
- while read network rest
- do set xx $rest
- shift
- proto=""
- via=""
- dev=""
- scope=""
- src=""
- table=""
- case $network in
- broadcast|local|unreachable) via=$network
- network=$1
- shift
- ;;
- esac
- while test $# != 0
- do
- case "$1" in
- proto|via|dev|scope|src|table)
- key=$1
- val=$2
- eval "$key='$val'"
- shift 2
- ;;
- dead|onlink|pervasive|offload|notify|linkdown|unresolved)
- shift
- ;;
- *)
- # avoid infinite loop on unknown keyword without value at line end
- shift
- shift
- ;;
- esac
- done
- echo "$network $via $src $proto $scope $dev $table"
- done | awk -F ' ' '
-BEGIN {
- format="%15s%-3s %15s %15s %8s %8s%7s %s\n";
- printf(format,"target","","gateway","source","proto","scope","dev","tbl");
- }
- { network=$1;
- mask="";
- if(match(network,"/"))
- { mask=" "substr(network,RSTART+1);
- network=substr(network,0,RSTART);
- }
- via=$2;
- src=$3;
- proto=$4;
- scope=$5;
- dev=$6;
- table=$7;
- printf(format,network,mask,via,src,proto,scope,dev,table);
- }
-'
+if __name__ == "__main__":
+ main()
diff --git a/man/man8/routel.8 b/man/man8/routel.8
index b32eeafcf69d..b1668e73615a 100644
--- a/man/man8/routel.8
+++ b/man/man8/routel.8
@@ -1,17 +1,31 @@
-.TH "ROUTEL" "8" "3 Jan, 2008" "iproute2" "Linux"
+.TH ROUTEL 8 "1 Sept, 2021" "iproute2" "Linux"
.SH "NAME"
-.LP
routel \- list routes with pretty output format
-.SH "SYNTAX"
-.LP
-routel [\fItablenr\fP [\fIraw ip args...\fP]]
+.SH SYNOPSIS
+.B routel
+.RI "[ " OPTIONS " ]"
+.RI "[ " tablenr
+[ \fIip route options...\fR ] ]
+.P
+.ti 8
+.IR OPTIONS " := {"
+\fB-h\fR | \fB--help\fR |
+[{\fB-f\fR | \fB--family\fR }
+{\fBinet\fR | \fBinet6\fR } |
+\fB-4\fR | \fB-6\fR }
+
.SH "DESCRIPTION"
.LP
-The routel script will list routes in a format that some might consider easier to interpret
-then the ip route list equivalent.
+The routel script will list routes in a format that some might consider
+easier to interpret then the
+.B ip
+route list equivalent.
+
.SH "AUTHORS"
.LP
-The routel script was written by Stephen R. van den Berg <srb@cuci.nl>, 1999/04/18 and donated to the public domain.
+Rewritten by Stephen Hemminger <stephen@networkplumber.org>.
+.br
+Original script by Stephen R. van den Berg <srb@cuci.nl>.
.br
This manual page was written by Andreas Henriksson <andreas@fatal.se>, for the Debian GNU/Linux system.
.SH "SEE ALSO"
--
2.30.2
next prev parent reply other threads:[~2021-09-01 20:47 UTC|newest]
Thread overview: 6+ messages / expand[flat|nested] mbox.gz Atom feed top
2021-09-01 20:46 [PATCH iproute2-next 0/4] Cleanup of ip scripts Stephen Hemminger
2021-09-01 20:46 ` [PATCH iproute2-next 1/4] ip: remove old rtpr script Stephen Hemminger
2021-09-01 20:46 ` [PATCH iproute2-next 2/4] ip: remove ifcfg script Stephen Hemminger
2021-09-01 20:47 ` [PATCH iproute2-next 3/4] ip: remove routef script Stephen Hemminger
2021-09-01 20:47 ` Stephen Hemminger [this message]
2021-09-06 22:33 ` [PATCH iproute2-next 0/4] Cleanup of ip scripts David Ahern
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20210901204701.19646-5-sthemmin@microsoft.com \
--to=stephen@networkplumber.org \
--cc=netdev@vger.kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).