Skip to content

Instantly share code, notes, and snippets.

@nv1t
Created June 18, 2012 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nv1t/2948627 to your computer and use it in GitHub Desktop.
Save nv1t/2948627 to your computer and use it in GitHub Desktop.
MagTek MagnetStrip Reader
#!/usr/bin/python
import sys
import usb.core
import usb.util
VENDOR_ID = 0x0801
PRODUCT_ID = 0x0002
DATA_SIZE = 337
# find the MagTek reader
device = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
if device is None:
sys.exit("Could not find MagTek USB HID Swipe Reader.")
# make sure the hiddev kernel driver is not active
if device.is_kernel_driver_active(0):
try:
device.detach_kernel_driver(0)
except usb.core.USBError as e:
sys.exit("Could not detatch kernel driver: %s" % str(e))
# set configuration
try:
device.set_configuration()
device.reset()
except usb.core.USBError as e:
sys.exit("Could not set configuration: %s" % str(e))
endpoint = device[0][(0,0)][0]
# wait for swipe
data = []
swiped = False
print("Please swipe your card...")
while 1:
try:
data += device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
if not swiped:
print("Reading...")
swiped = True
if len(data) == DATA_SIZE:
break
except usb.core.USBError as e:
if e.args == ('Operation timed out',) and swiped:
if len(data) < DATA_SIZE:
print("Bad swipe, try again. (%d bytes)" % len(data))
print("Data: %s" % ''.join(map(chr, data)))
data = []
swiped = False
continue
else:
break # we got it!
# now we have the binary data from the MagReader!
enc_formats = ('ISO/ABA', 'AAMVA', 'CADL', 'Blank', 'Other', 'Undetermined', 'None')
print("Card Encoding Type: %s" % enc_formats[data[6]])
print("Track 1 Decode Status: %r" % bool(not data[0]))
print("Track 1 Data Length: %d bytes" % data[3])
print("Track 1 Data: %s" % ''.join(map(chr, data[7:116])))
print("Track 2 Decode Status: %r" % bool(not data[1]))
print("Track 2 Data Length: %d bytes" % data[4])
print("Track 2 Data: %s" % ':'.join(map(str, data[117:226])))
print("Track 3 Decode Status: %r" % bool(not data[2]))
print("Track 3 Data Length: %d bytes" % data[5])
print("Track 3 Data: %s" % ''.join(map(chr, data[227:336])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment