Accessing the data field in a pcap dump file in python - python

I am using the following code:
import pyshark
cap = pyshark.FileCapture('/home/my_location/python_parse/my_file.pcap')
count = 0;
for caps in cap:
print caps.pretty_print();
print "Count is " + str(count)
count+=1;
My pcapfile is located here https://1drv.ms/u/s!Aj1_HY10QdBTa5zNMcZadSK3qAM
If someone has any alternative hosting site, I am ready to put it up at that location also.
I am unable to access the data field using pyshark. When I open up the pcap file in wireshark , I can see the data in this field:
Can anyone offer any suggestion?

You can use the usb_capdata field of the DATA layer.
import pyshark
caps = pyshark.FileCapture('/home/my_location/python_pars/my_file.pcap')
print caps[10].layers[1].usb_capdata
Will output the same as wireshark :
'80:08:0b:82:00:00:85:97:8a:86:00:00'

Related

Python Scapy wireless scan and match a mac address stored in text file

I have some code that will scan for wireless packets and displays the mac address from each of them. What i would like to do is have a text file of mac addresses and for the code to alert me with a message when one of the addresses in the file is picked up on the wireless scan. I can not think of a way to implement this, here is the code for the wiresless scan and below is an example of the text file.
import sys
from scapy.all import *
devices = set()
def PacketHandler(pkt):
if pkt.haslayer(Dot11):
dot11_layer = pkt.getlayer(Dot11)
if dot11_layer.addr2 and (dot11_layer.addr2 not in devices):
devices.add(dot11_layer.addr2)
print dot11_layer.addr2
sniff(iface = sys.argv[1], count = int(sys.argv[2]), prn = PacketHandler)
here is example of the text file.
00:11:22:33:44:55
AA:BB:CC:DD:EE:FF
Create a function that reads from a .txt and store each line (matching a MAC address) in a list.
def getListMac() -> list: # you can put the path for your .txt file as argument
with open('MAClist.txt', 'r+') as file:
res = [x.rstrip('\n') for x in file.readlines()]
return res
And then check in your packetHandler function if the mac if in this list.
Here you have two choice :
Call getListMac() at the start of your program, store it in a global variable. Go for this if your .txt file won't change after launching your program.
MACLIST = getListMac()
...
# in your PacketHandler function
if mac in MACLIST:
print("mac found!") #or whatever your want to do
Call the function each time a packet is sniffed. Go for this option if the list of MAC addresses frequently changes and you need it updated when your program is running. Be careful with it as this will slow your program, especially if your list is very long.
# in your PacketHandler function:
if mac in getListMac():
print("mac found!") # or whatever your want to do
Finally, i will finish this post by advising you to use a real DBMS, which will be much more efficient than reading a txt file. ;)
EDIT
To answer your comment :
Modify the getListMac function in order to store the information in a dictionnary.
Here is an exemple assuming you use " - " as separator between MAC - Time - Username
def getListMac() -> dict: # you can put the path for your .txt file as argument
with open('MAClist.txt', 'r+') as file:
res = {x.rstrip('\n').split(" - ")[0]: x.rstrip('\n').split(" - ")[2] for x in file.readlines()}
return res
Access the data in the dictionary like this:
if MAC in MACLIST:
print(f"MAC found -> {MAC}, Username -> {MACLIST[MAC]}")

scapy PcapReader cut short

I'm trying to rewrite a pcap file with different IP and IPv6 addresses. But after I extract a packt by PcapReader and change its IP adresses, the packets in the output pcap file is cut short (that is to say the payload of the packet is lost).
Here's the example code:
from scapy.all import PcapReader
from scapy.all import PcapWriter
def test():
f = "input.pcap"
writers = PcapWriter("output.pcap")
with PcapReader(f) as pcap_reader:
for pkt in pcap_reader:
# somehow change the IP address
writers.write(pkt=pkt)
test()
When I open the .pcap file with WireShark, it shows "The capture file appears to have been cut short in the middle of a packet".
Is there any solution in scapy to maintain the payload or is there any other python packets to recommand?
here I did not change anything and the results are like this:
input file:
enter image description here
output file:
enter image description here
I think the problem must be in the code you use to modify the packet (and which you did not show) or that your source file already had short packets (i.e. snaplen less than packet len). The following code works for me without problems:
from scapy.all import PcapReader,PcapWriter,IP
writer = PcapWriter('output.pcap')
for pkt in PcapReader('input.pcap'):
# somehow change the IP address
pkt[IP].dst = '1.2.3.4'
pkt[IP].src = '5.6.7.8'
writer.write(pkt=pkt)

I need a super-duper simple CGI Python photo upload

I've looked through tons of answers but the truth is, I only know super basic python and I really need help. I don't know the os module or anything like that and I can't use PHP (not that I know it anyway, but it's not permitted) and I need something so easy that I can understand it.
Basically, I need a CGI upload (I don't need the HTML form, I've got that much down) that will take the photo and save it. That's it. I don't need any fancy place for it to save, I just need the file to be properly uploaded from the form.
I've got various versions of this function and I can't get them working because I don't understand them so PLEASE HELP!!!
import cgi
def savefile (filename, photodoc):
form=cgi.FieldStorage()
name=form[filename]
period=name.split(.)
if period[1]=="jpeg" or period[1]=="jpg" or period[1]=="png":
idk what to do
else:
make an error message
This cgi program will "take the photo and save it. That's it."
#!/usr/bin/python2.7
import cgi
field=cgi.FieldStorage()['fieldname']
open(field.filename, 'wb').write(field.value)
Among the things it doesn't do are error checking and security checking, and specifying in what directory the files should be saved.
Duplicate question but here's what you need:
Depending if windows or linux, first set to binary mode:
try:
import msvcrt
msvcrt.setmode (0, os.O_BINARY)
msvcrt.setmode (1, os.O_BINARY)
except ImportError:
pass
Then:
form = cgi.FieldStorage()
name = form[filename]
period = name.split('.') #You need the quotes around the period
if period[1]=='jpeg' or period[1] == 'jpg' or period[1] =='png':
if upload.filename:
name = os.path.basename(upload.filename)
out = open(YOUR_FILEPATH_HERE + name, 'wb', 1000)
message = "The file '" + name + "' was uploaded successfully"
while True:
packet = upload.file.read(1000)
if not packet:
break
out.write(packet)
out.close()
else:
print 'Error'
Some sources:
How to use Python/CGI for file uploading
http://code.activestate.com/recipes/273844-minimal-http-upload-cgi/

Trying to extract json data, geting expected string or buffer

So I'm experimenting with json abit and this is the code I've got this far,
import json
from utorrent.client import UTorrentClient
uTorrent = UTorrentClient("xxxx", "xxxx", "xxxx")
data = uTorrent.list()
torrents = json.loads(data)["torrents"]
for torrent in torrents:
print item[0] # hash
print item[2] # name
print item[21] # status
print item[26] # folder
The typical json output can be viewed here. But im getting an "expected string or buffer" error. Anyone with any pointers?
The point with above code is to print out each hash/name.. for each torrent found in the list provided by uTorrent
Did you try using load instead of loads? I was having the same problem and I realized there's a difference.

Python requests fails to get webpages

I am using Python3 and the package requests to fetch HTML data.
I have tried running the line
r = requests.get('https://github.com/timeline.json')
, which is the example on their tutorial, to no avail. However, when I run
request = requests.get('http://www.math.ksu.edu/events/grad_conf_2013/')
it works fine. I am getting errors such as
AttributeError: 'MockRequest' object has no attribute 'unverifiable'
Error in sys.excepthook:
I am thinking the errors have something to do with the type of webpage I am attempting to get, since the html page that is working is just basic html that I wrote.
I am very new to requests and Python in general. I am also new to stackoverflow.
As a little example, here is a little tool which I developed in order to fetch data from a website, in this case IP and show it:
# Import the requests module
# TODO: Make sure to install it first
import requests
# Get the raw information from the website
r = requests.get('http://whatismyipaddress.com')
raw_page_source_list = r.text
text = ''
# Join the whole list into a single string in order
# to simplify things
text = text.join(raw_page_source_list)
# Get the exact starting position of the IP address string
ip_text_pos = text.find('IP Information') + 62
# Now extract the IP address and store it
ip_address = text[ip_text_pos : ip_text_pos + 12]
# print 'Your IP address is: %s' % ip_address
# or, for Python 3 ... #
# print('Your IP address is: %s' % ip_address)

Categories