I'm trying to create a very simple PCAP file (1 UDP message).
Tried using dpkt (pcap.Writer), no luck, and the documentation is scarce.
Can anyone post a working example?
(or any other alternative - I'm not bound to dpkt)
You may use Scapy.
https://scapy.readthedocs.io/en/latest/installation.html
If using Python 3:
pip3 install scapy
Then in Python:
from scapy.all import wrpcap, Ether, IP, UDP
packet = Ether() / IP(dst="1.2.3.4") / UDP(dport=123)
wrpcap('foo.pcap', [packet])
you need to write the packet into a libpcap format
Global Header + Packet Header + Packet Data + Packet Header + Packet Data
this link should help you
http://www.codeproject.com/Tips/612847/Generate-a-quick-and-easy-custom-pcap-file-using-P
construct's cap (broken link) shows how to use construct for this. Construct also has a rudimentary ip stack (broken link) example. The nice thing about Construct is that it is symmetrical, i.e. you can put data into it, convert it to a set of Python objects and you can then dump out the objects to create the original data blob again.
You can try the code below :
#!/usr/bin/env python3
import sys
import struct
import os
import argparse
from scapy.all import sniff, sendp, hexdump, linehexdump, get_if_list, get_if_hwaddr
from scapy.all import Packet, IPOption
from scapy.all import ShortField, IntField, LongField, BitField, FieldListField, FieldLenField
from scapy.all import IP, TCP, UDP, Raw
from scapy.layers.inet import _IPOption_HDR
from scapy.all import raw
from scapy.all import bytes_hex
import hashlib
import pcapng.blocks as blocks
from pcapng import FileWriter
counter = 1
def get_if():
ifs=get_if_list()
iface=None
for i in get_if_list():
if "enp1s0f1" in i:
iface=i
break;
if not iface:
print("Cannot find eth0 interface")
exit(1)
return iface
def main():
global counter
ifaces = [i for i in os.listdir('/sys/class/net/') ]
iface = get_if()
print(("sniffing on %s" % iface))
sys.stdout.flush()
writer = FileWriter(args.outfile, shb)
orig_packets = sniff(filter='tcp and port 5201',iface = iface)
for packet in orig_packets:
spb = shb.new_member(blocks.SimplePacket)
spb.packet_data = bytes(packet)
writer.write_block(spb)
print("C=",counter)
counter=counter+1
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("outfile", type=argparse.FileType("wb"))
args = parser.parse_args()
shb = blocks.SectionHeader(
options={
"shb_hardware": "artificial",
"shb_os": "python",
"shb_userappl": "python-pcapng",
})
idb = shb.new_member(
blocks.InterfaceDescription,
link_type=1,
options={
"if_description": "Hand-rolled",
"if_os": "Python",
"if_filter": [(0, b"tcp port 5201 and host 192.168.1.3")],
},)
main()
Related
`#!/usr/bin/env python
from scapy.all import *
from threading import Thread
def icmp_spoof(pkt):
if pkt.haslayer(ICMP) and pkt[IP].src == "10.9.0.1":
src_ip = pkt[IP].dst
dst_ip = pkt[IP].src
seq_num = pkt[ICMP].seq
id_num = pkt[ICMP].id
icmp_reply = IP(src=src_ip, dst=dst_ip)/ICMP(type='echo-reply', id=id_num, seq=seq_num)/Raw(load=pkt[Raw].load)
send(icmp_reply, verbose=0)
def sniff_icmp():
sniff(filter="icmp and src host 10.9.0.1", prn=icmp_spoof)
if __name__ == '__main__':
t = Thread(target=sniff_icmp)
t.start()`
this program is spoofing the packets but it is not printing the sniffed packets what chan could be made in order to print the sniffed packets
This image shows the ICMP packets spoofed
This is how I want this packet info printed
I am trying to capture gameplay over my computer and wants the live captured gameplay to be sent to my cloud instance for the purpose of object detection.
I have tried the following code.It works well locally but when I tunnel it using ngrok I am getting
getaddress error.
Is there any other way which I can send the video frames at good FPS over the internet to my cloud instance for performing deep learning processing on it?
client.py
import cv2
import io
import socket
import struct
import time
import pickle
import zlib
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#client_socket.connect(('localhost', 8485))
#Tring to connect to the hosted address obtained after using ngrok http 8485 command.
client_socket.connect(('https://fc766cc3.ngrok.io',0))
connection = client_socket.makefile('wb')
cam = cv2.VideoCapture(0)
cam.set(3, 320);
cam.set(4, 240);
img_counter = 0
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
while True:
ret, frame = cam.read()
result, frame = cv2.imencode('.jpg', frame, encode_param)
# data = zlib.compress(pickle.dumps(frame, 0))
data = pickle.dumps(frame, 0)
size = len(data)
print("{}: {}".format(img_counter, size))
client_socket.sendall(struct.pack(">L", size) + data)
img_counter += 1
cam.release()
server.py
import socket
import sys
import cv2
import pickle
import numpy as np
import struct ## new
import zlib
HOST='localhost'
PORT=8485
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('Socket created')
s.bind((HOST,PORT))
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn,addr=s.accept()
data = b""
payload_size = struct.calcsize(">L")
print("payload_size: {}".format(payload_size))
while True:
while len(data) < payload_size:
print("Recv: {}".format(len(data)))
data += conn.recv(4096)
print("Done Recv: {}".format(len(data)))
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack(">L", packed_msg_size)[0]
print("msg_size: {}".format(msg_size))
while len(data) < msg_size:
data += conn.recv(4096)
frame_data = data[:msg_size]
data = data[msg_size:]
frame=pickle.loads(frame_data, fix_imports=True, encoding="bytes")
frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
cv2.imshow('ImageWindow',frame)
cv2.waitKey(1)
FIRST OF ALL
You have generated the wrong Link for the client to connect to i.e
#Tring to connect to the hosted address obtained after using ngrok http 8485 command.
client_socket.connect(('https://fc766cc3.ngrok.io',0))
You neeed to use TCP instead of HTTP when using NGROK . Because the Http is used when you are hosting a web app on your server . so the client can go over to any browser paste your provided link and port and connect to your website.
And you used port 0 , I maybe wrong but i dont think portzr 0 is useable
and NGROK does not provide you port 0.
AND SECOND :
Even if you do get a TCP link NGROK does not allow Screen sharing over their Free server . You are able to send small messages or files but Screen Sharing is not possible .
i need to send a packet using scapy to a dns server i made, and for some reason the server doesnt get the packet
this is the dns server
-- coding: utf-8 --
from scapy.all import *
def le_check(p):
return (DNS in p and p[0][DNSQR].qtype == 1 and p[0][UDP].dport==53)
def main():
data_base = {'www.google.com': ('172.217.23.164','173.194.79.104','173.194.79.99')}
p1=sniff(count=1, lfilter=le_check)
x=p1[0][DNSQR].qname
if x in data_base:
list=data_base[x]
else:
list= "no such name"
print p1[0][DNSQR].qname
print list
send(IP(dst=p1[0][IP].src)/UDP(sport=53, dport=53)/Raw(list))
if __name__ == '__main__':
main()
code from scapy
sendp(IP(dst=MY_IP)/UDP(sport=24601,dport=53)/DNS(qdcount=1,rd=1)/DNSQR(qname="www.google.com",qtype=1))
I have some problem with unpickling data recived from logger. Given udp_server:
import pickle
import logging
import logging.handlers
import socketserver
import struct
class MyUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print("{} wrote:".format(self.client_address[0]))
print(self.unPickle(data)) # here is problem
socket.sendto(data.upper(), self.client_address)
def unPickle(self, data):
return pickle.loads(data)
class LogRecordSocketReceiver(socketserver.UDPServer):
allow_reuse_address = True
def __init__(self, host='localhost',
port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
handler=MyUDPHandler):
socketserver.UDPServer.__init__(self, (host, port), handler)
self.abort = 0
self.timeout = 1
self.logname = None
def serve_until_stopped(self):
import select
abort = 0
while not abort:
rd, wr, ex = select.select([self.socket.fileno()],
[], [],
self.timeout)
if rd:
self.handle_request()
abort = self.abort
if __name__ == "__main__":
tcpserver = LogRecordSocketReceiver()
print('About to start UDP server...')
tcpserver.serve_until_stopped()
And udp_log_sender:
import logging, logging.handlers
rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
udp_handler = logging.handlers.DatagramHandler("localhost", logging.handlers.DEFAULT_TCP_LOGGING_PORT)
rootLogger.addHandler(udp_handler)
logging.info('Jackdaws love my big sphinx of quartz.')
When the server recives logging message and want to run unPickle the EOFError is thrown. What could cause such behaviour?
do not strip binary data
omit the first 4 bytes (i.e. use data[4:]) as they contain length of the dumped object
I didn't find this information in logging module documentation - sometimes one has go to the source (or just google harder).
I am new at programming and am trying to communicate with my vehicle with an OBD II device. Serial to USB. I've done what I want it to do but I get the command I entered to print out. How do I just get the information from the device?
Heres my code. I am using Python 3.2.3
import serial
import time
import string
import io
import os
import sys
ser = serial.Serial("/dev/ttyUSB1")
ser.baudrate = 38400
s = input('Enter AT command --> ')
print ('AT command = ' + s)
ser.write(bytes(s + '\r\n', encoding = 'utf-8'))
ser.timeout = 1
response = ser.read(999).decode('utf-8')
print(response)
ser.close()
And here is what prints out when I enter the command 'atrv'.
>>>
Enter AT command --> atrv
AT command = atrv
atrv
0.1V
>>>
How do I prevent the 'atrv' above the 0.1V from printing out?
Send ATE0 to the ELM-device.
This disables the echo, so atrv won't be send back to you!
Have a look into this: http://elmelectronics.com/DSheets/ELM327DS.pdf , collection of lots of AT commands, could be helpful!
on a raspberry PI i had to modify the code to:
import serial
import time
import string
import io
import os
import sys
ser = serial.Serial("/dev/rfcomm0")
ser.baudrate = 115200
s = input('Enter AT command --> ')
print ('AT command = ' + s)
ser.flushInput();
ser.write(bytes(s + '\r\n', encoding = 'utf-8'))
ser.flush();
ser.timeout = 1
response = ser.read(999).decode('utf-8')
print(response)
ser.close()