Skip to content

Instantly share code, notes, and snippets.

@reginaldojunior
Created February 21, 2024 14:08
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 reginaldojunior/4f9a44f883a869244bcaf41add71c3e9 to your computer and use it in GitHub Desktop.
Save reginaldojunior/4f9a44f883a869244bcaf41add71c3e9 to your computer and use it in GitHub Desktop.
syscan.py
from typing import Collection, List
from random import randint, shuffle
from scapy.layers.inet import IP, TCP
from scapy.sendrecv import sr
SEQ_MAX = 2**32 - 1
EPHEMERAL_RANGE = (2**14 + 2**15, 2**16 - 1) # According to the IANA
SYN_FLAG = "S"
SYN_ACK_FLAG = SYN_FLAG + "A"
ALL_PORTS = range(EPHEMERAL_RANGE[1] + 1)
DEFAULT_TIMEOUT = 3
def new_scan_packets(address: str, ports: Collection[int]) -> List[TCP]:
ip_layer = IP(dst=address)
return [ip_layer / TCP(sport=randint(*EPHEMERAL_RANGE), dport=port, seq=randint(0, SEQ_MAX - 1), flags=SYN_FLAG)
for port in ports]
def port_scan(address: str, ports: Collection[int], shuffled: bool = True, **kwargs) -> List[int]:
"""
Scans the ports in the given collection and finds which are accepting connections.
Returns a list of ports that were found to be open.
kwargs are passed directly to sr to support options like "delay" and "timeout".
"""
kwargs.setdefault("timeout", DEFAULT_TIMEOUT) # Because the scan could hang indefinitely otherwise
syns = new_scan_packets(address, ports)
if shuffled:
shuffle(syns)
answered, _ = sr(syns, verbose=False, **kwargs)
return sorted(stimulus[TCP].dport
for stimulus, response in answered
if response[TCP].flags.flagrepr() == SYN_ACK_FLAG)
print(port_scan('142.250.218.227', (80, 8080, 8000)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment