-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnic.py
74 lines (55 loc) · 2.06 KB
/
nic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import re
import subprocess
from scapy.all import get_if_hwaddr, sniff, sendp
class NetworkInterface(object):
def __init__(self, name: str):
try:
self.name = name
self.channel = None
self.hwaddr = get_if_hwaddr(name)
except Exception as x:
raise type(x)(f'Invalid network interface: {name}')
# Set NIC to monitor mode
def set_monitor(self, state: bool):
mode = 'monitor' if state else 'managed'
try:
cp = subprocess.run(
['ip', 'link', 'set', self.name, 'down'],
stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL
)
if cp.returncode:
raise RuntimeError
cp = subprocess.run(
['iwconfig', self.name, 'mode', mode],
stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL
)
if cp.returncode:
raise RuntimeError
cp = subprocess.run(
['ip', 'link', 'set', self.name, 'up'],
stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL
)
if cp.returncode:
raise RuntimeError
except Exception as x:
raise type(x)(f'Failed to set {self.name} to {mode} mode')
# Set the NIC's channel
def set_channel(self, channel: int):
if channel not in range(1, 15):
raise ValueError(f'Invalid channel: {channel}')
try:
cp = subprocess.run(
['iwconfig', self.name, 'channel', str(channel)],
stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL
)
if cp.returncode:
raise RuntimeError
except Exception as x:
raise type(x)(f'Failed to set {self.name} on channel {channel}')
self.channel = channel
# Receive (sniff) packets
def recv(self, **kwargs):
sniff(iface = self.name, **kwargs)
# Send packets
def send(self, pkt, **kwargs):
sendp(pkt, iface = self.name, **kwargs)