0

I am working on a virtual Machine by Oracle in Linux and my Linux version is 20.04 LTS and python version is 3.8. I have a python code which is used to capture live network traffic and save in a pcap file. The issue I am facing is that I want to run this code without any root or administrative or without sudo command.

test.py:

import time
from scapy.all import *
import uuid

# IP address to capture packets for
ip_address = "0.0.0.0"

start_time = time.time()
end_time = start_time + 10  # Capture for 10 seconds

# Create an empty list to store the packets
packets = []

def packet_callback(packet):
    if IP in packet:
        packets.append(packet)

# Create a capture filter to capture only packets from the specified IP address 
capture_filter = "ip host " + ip_address

sniff(prn=packet_callback, timeout=end_time-start_time, filter= capture_filter)

# Write all the packets to a single pcap file
filename = "/path_to_capture/capture_" + str(uuid.uuid1()) + ".pcap"
wrpcap(filename, packets)
print(len(packets))

I run my code in terminal by writing the following cmd:

sudo python3 test.py

By running this command, my code executes and capture the network traffic and save in a pcap file. But I want to execute my code without sudo or root privileges by writing a simple cmd:

python3 test.py

Kindly provide me the solution to resolve this issue.

  • what error do you get when you run it without sudo? – T Olaleye Jan 30 '23 at 05:19
  • sniff(prn=packet_callback, timeout=end_time-start_time, filter= capture_filter) File "/home/sqit/.local/lib/python3.8/site-packages/scapy/sendrecv.py", line 1263, in sniff sniffer._run(*args, **kwargs) PermissionError: [Errno 1] Operation not permitted – AHSAN YAZDANI Jan 30 '23 at 05:29
  • Sniffing in promiscuous mode requires elevated permissions. You might be able to setup a user group in the OS to allow sniffing but that is not a programming topic anymore. – Klaus D. Jan 30 '23 at 05:34
  • So, is there any solution to handle this problem? – AHSAN YAZDANI Jan 30 '23 at 05:37

1 Answers1

0

I think that you can use the 'setcap' command in linux.

I have a experience of only 'C' language.

See the below link. (I'm not sure about Python)

https://medium.com/@badbot/safe-packet-capture-python-without-sudo-b08c4c4e531