Python Linux route table lookup

2024/9/27 19:18:05

I posted Python find first network hop about trying to find the first hop and the more I thought about it, the easier it seemed like it would be a process the routing table in python. I'm not a programmer, I don't know what I'm doing. :p

This is what I came up with, the first issue I noticed is the loopback interface doesn't show up in the /proc/net/route file- so evaluating 127.0.0.0/8 will give you the default route... for my application, that doesn't matter.

Anything else major I'm overlooking? Is parsing ip route get <ip> still a better idea?

import re
import struct
import socket'''Read all the routes into a list. Most specific first.# eth0  000219AC        04001EAC        0003    0       0       0       00FFFFFF ...
'''
def _RtTable():_rt = []rt_m = re.compile('^[a-z0-9]*\W([0-9A-F]{8})\W([0-9A-F]{8})[\W0-9]*([0-9A-F]{8})')rt = open('/proc/net/route', 'r')for line in rt.read().split('\n'):if rt_m.match(line):_rt.append(rt_m.findall(line)[0])rt.close()return _rt'''Create a temp ip (tip) that is the entered ip with the host section striped off.  Matching to routers in order, the first match should be the most specific.If we get 0.0.0.0 as the next hop, the network is likely(?) directly attached- the entered IP is the next (only) hop
'''
def FindGw(ip):int_ip = struct.unpack("I", socket.inet_aton(ip))[0]for entry in _RtTable():tip = int_ip & int(entry[2], 16)if tip == int(entry[0], 16):gw_s = socket.inet_ntoa(struct.pack("I", int(entry[1], 16)))if gw_s == '0.0.0.0':return ipelse:return gw_sif __name__ == '__main__':import sysprint FindGw(sys.argv[1])
Answer

In the man page of proc file system it is given that.

   /proc/netvarious net pseudo-files, all of which give the status of some part ofthe networking layer.  These files contain ASCII structures and  are,there‐fore, readable with cat(1).However, the standard netstat(8) suite provides much cleaner access to these files.

Just rely on the tools designed for those purposes. Use netstat, traceroute or any other standard tool. Wrap those commands cleanly using subprocess module and get the information for what you are looking for.

https://en.xdnf.cn/q/71422.html

Related Q&A

How to compare frequencies/sampling rates in pandas?

is there a way to say that 13Min is > 59S and <2H using the frequency notation in pandas?

Why do I get expected an indented block when I try to run my Python script? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Closed 5 years ago.Edit the question to include desired behavior, a specific problem or error, and t…

python run command as normal user in a root script

I have a python script that is launched as root, I cant change it. I would like to know if its possible to exectute certain lines of this script (or all the script) as normal user (I dont need to be ro…

Compare values of two arrays in python

How can i check if item in b is in a and the found match item in a should not be use in the next matching? Currently this code will match both 2 in b.a = [3,2,5,4] b = [2,4,2]for i in b:if i in a:prin…

How to count the number of digits in numbers in different bases?

Im working with numbers in different bases (base-10, base-8, base-16, etc). Im trying to count the number of characters in each number. ExampleNumber: ABCDEF Number of digits: 6I know about the method …

Pandas KeyError using pivot

Im new to Python and I would like to use Python to replicate a common excel task. If such a question has already been answered, please let me know. Ive been unable to find it. I have the following p…

Not found: Container localhost does not exist when I load model with tensorflow and flask

I am a newbie research Deeplearning. I load a saved model with tensorflow and made a API with flask but I get error Container localhost does not exist. when I predict, please help me fix it. Thank you.…

Python: simplifying nested FOR loop?

I am wondering if there is a way to simplify the nested loop below. The difficulty is that the iterator for each loop depends on things from the previous loops. Here is the code:# Find the number of co…

NLTK Data installation issues

I am trying to install NLTK Data on Mac OSX 10.9 . The download directory to be set, as mentioned in NLTK 3.0 documentation, is /usr/share/nltk_data for central installation. But for this path, I get …

Why does the simplest requests_mock example fail with pytest?

I have a peculiar problem with requests_mock. I want to use it with pytest to test my API wrapper library.Ive tried to use the first example in the requests_mock docs, except I put it in a test_mock()-…