Selecting interface to sniff in Python using a variable

124 Views Asked by At

I need to create a sniff in python using the sniff command, to collect packets entering several interfaces.
When I do it specifying the interfaces with their names with the following command:

sniff(iface=["s1-cpu-eth1","s2-cpu-eth1","s3-cpu-eth1","s4-cpu-eth1"], prn=self.recv)

It works, but if I try to use a variable (this is needed because interfaces can change depending on the context and they can be obtained through a for loop populating a variable), such as:

if_to_sniff="\"s1-cpu-eth1\",\"s2-cpu-eth1\",\"s3-cpu-eth1\",\"s4-cpu-eth1\""

sniff(iface=[if_to_sniff], prn=self.recv)

It doesn't work. I actually tried several ways, but I always get an error saying that the device doesn't exist. How can I do this?

1

There are 1 best solutions below

0
Anentropic On
if_to_sniff="\"s1-cpu-eth1\",\"s2-cpu-eth1\",\"s3-cpu-eth1\",\"s4-cpu-eth1\""

This string looks like CSV format? In which case we can use Python's CSV reader to parse it for us:

import csv

if_to_sniff="\"s1-cpu-eth1\",\"s2-cpu-eth1\",\"s3-cpu-eth1\",\"s4-cpu-eth1\""

# csv.reader expects a file or a list of strings (like lines in csv file)
reader = csv.reader([if_to_sniff])

# get the first row from our 'csv'
# interfaces will be the 'columns' of that row
# (i.e. split into a list of sub strings)
interfaces = reader.__next__()

sniff(iface=interfaces, prn=self.recv)