Skip to content

Commit

Permalink
Black format (#29)
Browse files Browse the repository at this point in the history
* Add Format step to the makefile

* Automatic code format with Black -t py27
  • Loading branch information
NexSabre authored May 27, 2021
1 parent a4614b7 commit 1a1f0c4
Show file tree
Hide file tree
Showing 24 changed files with 468 additions and 224 deletions.
7 changes: 6 additions & 1 deletion makefile
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
all: clean build publish
all: clean format build publish

clean:
@echo "Cleaning..."
rm -rf build dist scapy_helper.egg-info
@echo "Cleaning... Done"

format:
@echo "Formatting..."
python -m black -t py27 .
@echo "Formatting... Done"

build:
@echo "Building..."
python setup.py sdist bdist_wheel --universal
Expand Down
3 changes: 1 addition & 2 deletions scapy_helper/chexdump.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def chexdump(packet, dump=False, to_list=False):
:param to_list: True if you want a list of hex instead of a string
:return: None or Str or List
"""

def _add_0x_before(p):
return ["0x%s" % x for x in p]

Expand All @@ -22,5 +23,3 @@ def _add_0x_before(p):
else:
return ", ".join(_add_0x_before(processed_packet))
print(", ".join(_add_0x_before(processed_packet)))


1 change: 1 addition & 0 deletions scapy_helper/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def table_diff(self, index=False):
:param index: Default=False, If True show position under the differ position
:return: bool: Return True if packets are NOT EQUAL
"""

def prepare_data(first, second):
if "=" in first and "=" in second:
column_a = first.split("=")
Expand Down
2 changes: 2 additions & 0 deletions scapy_helper/helpers/depracated.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ def deprecated(func, *args, **kwargs):
:param kwargs:
:return:
"""

def wrapper():
print("WARN:: Deprecated %s" % func.__name__)
func(*args, **kwargs)

return wrapper
14 changes: 5 additions & 9 deletions scapy_helper/helpers/mac.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ def int2mac(integer, upper=False):
:param upper: True if you want get address with uppercase
:return: String mac address in format AA:BB:CC:DD:EE:FF
"""

def format_int():
return zip(*[iter('{:012x}'.format(integer))] * 2)
return zip(*[iter("{:012x}".format(integer))] * 2)

if type(integer).__name__ not in ("int", "long"):
# hack: since in the python3, long is not supported
raise TypeError("Value %s is not a number" % integer)

mac = ':'.join(['{}{}'.format(a, b)
for a, b in format_int()])
mac = ":".join(["{}{}".format(a, b) for a, b in format_int()])
if upper:
return mac.upper()
return mac
Expand All @@ -32,12 +32,8 @@ def mac2int(string):
if not isinstance(string, str):
raise TypeError("Value %s is not a type of string" % string)

potential_mac = re.match('^((?:(?:[0-9a-f]{2}):){5}[0-9a-f]{2})$',
string.lower())
potential_mac = re.match("^((?:(?:[0-9a-f]{2}):){5}[0-9a-f]{2})$", string.lower())
if not potential_mac:
raise ValueError("Invalid mac address %s" % string)

return int(potential_mac
.group()
.replace(":", "")
.replace(".", ""), 16)
return int(potential_mac.group().replace(":", "").replace(".", ""), 16)
2 changes: 1 addition & 1 deletion scapy_helper/helpers/to_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


def to_list(packet, extend=False):
return [_layer2dict(packet.getlayer(x)) for x in range(len(packet.layers()))]
return [_layer2dict(packet.getlayer(x)) for x in range(len(packet.layers()))]
6 changes: 2 additions & 4 deletions scapy_helper/helpers/utils.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
__values = (int, float, str, bytes, bool,
list, tuple, set,
dict)
__values = (int, float, str, bytes, bool, list, tuple, set, dict)


def _layer2dict(frame):
temp_dict = {}

if not getattr(frame, 'fields_desc', None):
if not getattr(frame, "fields_desc", None):
return
for _field in frame.fields_desc:
value = getattr(frame, _field.name)
Expand Down
17 changes: 8 additions & 9 deletions scapy_helper/hexdump.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ def to_char(string):
return chr(j)

def split(obj, num):
return [obj[start:start + num]
for start in range(0, len(obj), num)
if obj[start:start + num]]
return [
obj[start : start + num]
for start in range(0, len(obj), num)
if obj[start : start + num]
]

def __process_hexdump(ppacket):
row = []
Expand All @@ -24,8 +26,7 @@ def __process_hexdump(ppacket):
if len(line) < 16:
line += [" " for _ in range(16 - len(line))]

row.append("%03x0 %s %s" %
(i, ' '.join(line), ''.join(console_char)))
row.append("%03x0 %s %s" % (i, " ".join(line), "".join(console_char)))
return row

def __alternative_process_hexdump(ppacket):
Expand All @@ -35,8 +36,7 @@ def __alternative_process_hexdump(ppacket):
if len(line) < 16:
line += [" " for _ in range(16 - len(line))]

row.append("%03x0 %s %s" %
(i, ' '.join(line), ''.join(console_char)))
row.append("%03x0 %s %s" % (i, " ".join(line), "".join(console_char)))
return row

def __third_process_hexdump(ppacket):
Expand All @@ -45,8 +45,7 @@ def __third_process_hexdump(ppacket):
console_char = [to_char(x) for x in line]
if len(line) < 16:
line += "".join([" " for _ in range(16 - len(line))])
row.append("%03x0 %s %s" %
(i, ' '.join(line), ''.join(console_char)))
row.append("%03x0 %s %s" % (i, " ".join(line), "".join(console_char)))
return row

try:
Expand Down
55 changes: 39 additions & 16 deletions scapy_helper/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ def isbytesarray():
if len(b) == 1:
return get_hex(obj).split()
return b

import sys

if sys.version_info > (3, 5):
# TODO very naive hack, but should be ok as temporary fix
if isinstance(obj, bytes):
Expand All @@ -80,10 +82,11 @@ def get_hex(frame, uppercase=False):
Return a string object of Hex representation of the Scapy's framework
:param frame: Scapy's Packet Object
:param uppercase: bool: If True letters be UPPERCASE
:return: str: Hex
:return: str: Hex
"""
if sys.version_info.major == 2:
import binascii

str_hex = binascii.b2a_hex(bytes(frame))
else:
try:
Expand All @@ -95,8 +98,8 @@ def get_hex(frame, uppercase=False):
if e % 2:
j.append(str_hex[e - 1] + str_hex[e])
if uppercase:
return ' '.join(j).upper()
return ' '.join(j).lower()
return " ".join(j).upper()
return " ".join(j).lower()


def show_hex(frame, uppercase=False):
Expand All @@ -119,7 +122,7 @@ def _create_diff_indexes_list(indexes, max_len):
else:
new_list.append("| position")

return ' '.join(new_list)
return " ".join(new_list)


def __process_char(char):
Expand All @@ -141,13 +144,23 @@ def show_diff(first, second, index=False, extend=False, empty_char="XX"):
if element == " ":
row[idx] = empty_char

print("%s | len: %sB" % (' '.join(first_row), first_row_len_bytes))
print("%s | len: %sB" % (' '.join(second_row), second_row_len_bytes))
print("%s | len: %sB" % (" ".join(first_row), first_row_len_bytes))
print("%s | len: %sB" % (" ".join(second_row), second_row_len_bytes))
if index and indexes_of_diff:
str_bar = " " * first_row_len_bytes if first_row_len_bytes > second_row_len_bytes else \
" " * second_row_len_bytes
print("%s|\n%s" % (str_bar, _create_diff_indexes_list(indexes_of_diff, max((first_row_len_bytes,
second_row_len_bytes)))))
str_bar = (
" " * first_row_len_bytes
if first_row_len_bytes > second_row_len_bytes
else " " * second_row_len_bytes
)
print(
"%s|\n%s"
% (
str_bar,
_create_diff_indexes_list(
indexes_of_diff, max((first_row_len_bytes, second_row_len_bytes))
),
)
)

if extend:
more_info = []
Expand Down Expand Up @@ -179,13 +192,23 @@ def show_diff_full(first, second, index=True, extend=False, empty_char="XX"):
if element == " ":
row[idx] = empty_char

print("%s | len: %sB" % (' '.join(first_row), first_row_len_bytes))
print("%s | len: %sB" % (' '.join(second_row), second_row_len_bytes))
print("%s | len: %sB" % (" ".join(first_row), first_row_len_bytes))
print("%s | len: %sB" % (" ".join(second_row), second_row_len_bytes))
if index and indexes_of_diff:
str_bar = " " * first_row_len_bytes if first_row_len_bytes > second_row_len_bytes else \
" " * second_row_len_bytes
print("%s|\n%s" % (str_bar, _create_diff_indexes_list(indexes_of_diff, max((first_row_len_bytes,
second_row_len_bytes)))))
str_bar = (
" " * first_row_len_bytes
if first_row_len_bytes > second_row_len_bytes
else " " * second_row_len_bytes
)
print(
"%s|\n%s"
% (
str_bar,
_create_diff_indexes_list(
indexes_of_diff, max((first_row_len_bytes, second_row_len_bytes))
),
)
)

if extend:
more_info = []
Expand Down
9 changes: 6 additions & 3 deletions scapy_helper/test_case_extensions/packet_assert.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,14 @@ def assertHexDifferentAt(first, second, positions, message):
failure(first, second, message)

if isinstance(positions, int):
if len(differences_at_position) != 1 or (positions not in differences_at_position):
if len(differences_at_position) != 1 or (
positions not in differences_at_position
):
show_diff(first, second, index=True)
failure(first, second, message)
elif isinstance(positions, (list, tuple)):
if not set(positions).issubset(set(differences_at_position)) or set(positions) < set(
differences_at_position):
if not set(positions).issubset(set(differences_at_position)) or set(
positions
) < set(differences_at_position):
show_diff(first, second, index=True)
failure(first, second, message)
12 changes: 8 additions & 4 deletions scapy_helper/utils/hhstrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ def hhstrip(*args, **kwargs):
one_line_hex = hstrip(raw=False)
if one_line_hex:
print(one_line_hex)
print("More information about packet @ PacketHelper.com\nhttps://www.packethelper.com/hex/{}".format(
one_line_hex.replace(" ", "")
))
print(
"More information about packet @ PacketHelper.com\nhttps://www.packethelper.com/hex/{}".format(
one_line_hex.replace(" ", "")
)
)
except Exception as e:
print(e)
print("Copy correctly hexdump and try again or go to https://www.packethelper.com")
print(
"Copy correctly hexdump and try again or go to https://www.packethelper.com"
)


if __name__ == "__main__":
Expand Down
18 changes: 12 additions & 6 deletions scapy_helper/utils/hstrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,16 @@ def hstrip(raw=True, hexdump=None):
:return: String
"""
if not hexdump:
striped_value = [x.split() for x in pyperclip.paste().split("\n") if x.strip() != ""]
striped_value = [
x.split() for x in pyperclip.paste().split("\n") if x.strip() != ""
]
else:
striped_value = [x.split() for x in hexdump.split("\n") if x.strip() != ""]

if getenv("SH_DEBUG", False):
striped_value = [x.split() for x in HEXDUMP_VALUE.split("\n") if x.strip() != ""]
striped_value = [
x.split() for x in HEXDUMP_VALUE.split("\n") if x.strip() != ""
]

try:
index_to_start = int(striped_value[0].index("0000"))
Expand All @@ -36,18 +40,20 @@ def hstrip(raw=True, hexdump=None):

_list = []
for x in striped_value:
_list.append(x[index_to_start + 1:index_to_start + 17])
_list.append(x[index_to_start + 1 : index_to_start + 17])
else:
if len(_list[-1]) < 18:
_list[-1] = _list[-1][:-1] # remove last element if the list is shorter than 18
_list[-1] = _list[-1][
:-1
] # remove last element if the list is shorter than 18

oneliner = ' '.join([' '.join(x) for x in _list])
oneliner = " ".join([" ".join(x) for x in _list])
if not hexdump:
pyperclip.copy(oneliner) # copy to the clipboard

if not raw:
return oneliner
return '\n'.join([' '.join(x) for x in _list])
return "\n".join([" ".join(x) for x in _list])


if __name__ == "__main__":
Expand Down
8 changes: 4 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@
"Programming Language :: Python :: 3.9",
"Topic :: Software Development :: Libraries :: Python Modules",
],
license='MIT',
license="MIT",
install_requires=["tabulate~=0.8.7", "pyperclip==1.8.2"],
entry_points={
'console_scripts': [
'hstrip = scapy_helper.utils.hstrip:hstrip',
'hhstrip = scapy_helper.utils.hhstrip:hhstrip'
"console_scripts": [
"hstrip = scapy_helper.utils.hstrip:hstrip",
"hhstrip = scapy_helper.utils.hhstrip:hhstrip",
],
},
)
16 changes: 3 additions & 13 deletions test/helpers/test_ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,10 @@ def setUp(self):
self.ip = "192.168.0.1"

def test_ip2int(self):
self.assertEqual(
ip2int(self.ip),
self.integer,
"Values should be equal"
)
self.assertEqual(ip2int(self.ip), self.integer, "Values should be equal")

def test_int2ip(self):
self.assertEqual(
int2ip(self.integer),
self.ip,
"Values should be equal"
)
self.assertEqual(int2ip(self.integer), self.ip, "Values should be equal")

def test_int2ip_for_zero(self):
self.assertEqual(
int2ip(0), "0.0.0.0", "Values should be equal"
)
self.assertEqual(int2ip(0), "0.0.0.0", "Values should be equal")
Loading

0 comments on commit 1a1f0c4

Please sign in to comment.