|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright 2024 Red Hat Inc. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 | +# not use this file except in compliance with the License. You may obtain |
| 7 | +# a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 14 | +# License for the specific language governing permissions and limitations |
| 15 | +# under the License. |
| 16 | + |
| 17 | +from pyroute2 import IPRoute |
| 18 | + |
| 19 | +ip = IPRoute() |
| 20 | + |
| 21 | +ifaces = {} |
| 22 | + |
| 23 | +for link in ip.get_links(): |
| 24 | + attrs = {k: v for k, v in link['attrs']} |
| 25 | + ifaces[link['index']] = attrs['IFLA_IFNAME'] |
| 26 | + |
| 27 | +for addr in ip.get_addr(): |
| 28 | + attrs = {k: v for k, v in addr['attrs']} |
| 29 | + print(f"addr {attrs['IFA_ADDRESS']}/{addr['prefixlen']} " |
| 30 | + f"dev {ifaces[addr['index']]}") |
| 31 | + |
| 32 | +for route in ip.get_routes(): |
| 33 | + attrs = {k: v for k, v in route['attrs']} |
| 34 | + if attrs['RTA_TABLE'] != 254: |
| 35 | + continue |
| 36 | + suffix = f"/{route['dst_len']}" if route['dst_len'] else "" |
| 37 | + route_str = f"route {attrs.get('RTA_DST', 'default')}{suffix} " |
| 38 | + if attrs.get('RTA_GATEWAY'): |
| 39 | + route_str += f"via {attrs.get('RTA_GATEWAY')} " |
| 40 | + route_str += f"dev {ifaces[attrs['RTA_OIF']]} " |
| 41 | + if attrs.get('RTA_PREFSRC'): |
| 42 | + suffix = f"/{route['src_len']}" if route['src_len'] else "" |
| 43 | + route_str += f"prefsrc {attrs.get('RTA_PREFSRC')}{suffix} " |
| 44 | + |
| 45 | + print(route_str) |
0 commit comments