Forum Archive

How can I install Scapy?

pythonista72

Hi,

just read about 2.0 release, great! :-)

But one question. How can I install something like Scapy?
http://www.secdev.org/projects/scapy/

It's a complete package with many files...

Thank you for your help!

Gerzer

Try using the pip command in StaSh. I guarantee that you will find yourself using StaSh in the future for other tasks as well.

Webmaster4o

I use this appex scripts for downloading things into pythonista:

import urllib2, appex, time, zipfile, os
a=time.time()
if appex.is_running_extension():
    url = appex.get_url()
    print url
    e=0
else:
    import clipboard, editor
    url = clipboard.get()
    e=1

response = urllib2.urlopen(url)
file = response.read()

name = url.split('/')[-1]
home = os.path.expanduser('~/Documents/')
output = open(home+name, 'w')
output.write(file)
output.close()

print 'Downloaded '+name+' to /Documents/'+name+' in '+str(time.time()-a)+' seconds'

if zipfile.is_zipfile(home+name):
    print 'Extracting zip...'
    zipfile.ZipFile(home+name).extractall(home)
    os.remove(home+name)
if e:
    editor.reload_files()

Go to the scapy website, download the zip. Once you see it in Safari like this:

Click "Open in…", select pythonista, then run my script. Returning to pythonista, you should see a folder scapy-2.3.1. Go into this, and move the scapy subdirectory into site-packages

Gerzer

@Webmaster4o Is that the right screenshot? :)

Gerzer

@Webmaster4o Nevermind, I see you changed it.

Webmaster4o

Fixed ;) Those were my math grades :)

miwagner1

You script didn't work for me. This one did however and basically works as the open in replacement :)

# coding: utf-8
# Olaf, Dec 2015, Pythonista 1.6 beta

'''Appex GetFromURL
Pythonista app extension for use on share sheet of other apps to import file from URL into Pythonista
The file is saved at HOME/DESTINATION without user interaction (no 'save as' dialog) unless duplicate'''

from __future__ import print_function
try:
    import appex, console, contextlib, itertools, os, os.path, sys, time, urllib, urlparse
except ImportError:
    assert False, 'This script needs the appex module in Pythonista version > 1.5'

HOME, DESTINATION = 'Documents', 'FromURL' # you can change DESTINATION to any name of your liking

@contextlib.contextmanager
def callfunctionafterwardswithsec(function):
    '''Context-manager that calls function with duration of with block (sec) after termination

    >>> def pr_sec(sec): print('Duration {:3.2} sec'.format(sec))
    >>> with callfunctionafterwardswithsec(pr_sec): pass
    Duration 0.0 sec'''

    start = time.clock()
    yield
    end = time.clock()
    function(end - start)

def left_subpath_upto(path, sentinel):
    '''Left part (subpath) of path upto and including sentinel

    >>> print(left_subpath_upto('a/b/c', 'b'))
    a/b'''

    while path:
        head, tail = os.path.split(path)
        if tail == sentinel:
            break
        path = head
    return path

def iter_pad(length, arg0, *args):
    '''Iterator to pad arguments (at least 1) to specified length by repetition of final argument

    >>> print(''.join(iter_pad(3, 'a', 'b')))
    abb'''

    args = (arg0,) + args
    return itertools.islice(itertools.chain(args, itertools.repeat(args[-1])), length)

def parse_into_paths(input_url, HOME=HOME, DESTINATION=DESTINATION):
    '''Parse input URL into paths tuple for further processing

    >>> parse_into_paths('http://test.org/x.py', DESTINATION='TEST') # doctest: +ELLIPSIS
    ('x.py', 'http://test.org', 'Documents/TEST', '/private/var/.../TEST', '/priv.../TEST/x.py', True)'''

    url_tuple = urlparse.urlparse(input_url)
    scheme, netloc, basename = url_tuple.scheme, url_tuple.netloc, os.path.basename(url_tuple.path)
    input_short = urlparse.urlunparse(iter_pad(len(url_tuple), scheme, netloc, ''))
    output_short = os.path.join(HOME, DESTINATION)
    output_dir = os.path.join(left_subpath_upto(sys.argv[0], HOME), DESTINATION)
    output_path = os.path.join(output_dir, basename)
    is_Python = os.path.splitext(basename)[1].lower() == '.py'
    return basename, input_short, output_short, output_dir, output_path, is_Python

def copy_url(input_url):
    '''Write a copy of the file at input_url to HOME/DESTINATION
    if the destination directory doesn't exist, it is created
    if the destination file already exists, the user can cancel or overwrite
    if it is a Python file, a comment line is added to log the origin'''

    basename, input_short, output_short, output_dir, output_path, is_Python = parse_into_paths(input_url)

    if not os.path.exists(output_dir):
        os.mkdir(output_dir)
        console.hud_alert('Created destination directory {}'.format(output_short))
    if os.path.exists(output_path):
        try:
            console.alert('Duplicate file',
                          '{} already exists in {}'.format(basename, output_short),
                          'Overwrite') # or Cancel
        except KeyboardInterrupt:
            return

    with contextlib.closing(urllib.urlopen(input_url)) as input:
        data = input.read()
        console.hud_alert('Got {} ({} chars) from {}'.format(basename, len(data), input_short))
    with open(output_path, 'wb') as output:
        if is_Python:
            datetime = time.strftime('%a %d-%b-%Y %H:%M:%S', time.gmtime())
            output.write('# Retrieved from {} on {}\n\n'.format(input_url, datetime))
        output.write(data)
        console.hud_alert('Wrote {} to {}'.format(basename, output_short))

def main():
    '''App extension logic, with unit tests if run within Pythonista'''

    if appex.is_running_extension():
        if appex.get_url():
            copy_url(appex.get_url())
            appex.finish()
        else:
            console.hud_alert('No input URL found', 'error')
    else:
        console.hud_alert('This script must be run from the sharing extension', 'error')
        import doctest
        doctest.testmod()

if __name__ == '__main__':
    main()
ihf

Does Scapy actually run under Pythonista?

Webmaster4o

@ihf yes, it imports without error.

Webmaster4o

@miwagner1 I updated it, that might fix your issue?

miwagner1

Ya fixing the path to have Pythonista generate, os.path.expanduser did it. now lets hope apple won't make him pull the extension as its letting me do all sorts of cool stuff.

ihf

Just for fun, I downloaded scapy 2.3.1, unzipped it, and moved it to site-packages. If I then try to run main.py, I get errors in console regarding IPv6 support disabled in Python. That's probably OK but then the program stops at line 278 with NameError:name 'LOOPBACK_NAME' is not defined. How did you get this to run?

Webmaster4o

I didn't actually test it, I just imported. Import worked for me, though.

inzel

I am getting the same NameError:name 'LOOPBACK_NAME' is not defined error that @ihf came across a year ago. Does anyone know how to get around that? I would really like to be able to use scapy. Thanks!

abcabc

Look at this link. I have not tried it.
https://github.com/secdev/scapy/issues/401

inzel

I came across this before but didnt make test the change because Im on an iPad running stash. Ill give it a shot and see what happens. Thanks!

inzel

I added this to the ../windows/__init.py__ file and there was no change. I then added it to the __init.py__ file in the arch folder and that changed the error from LOOPBACK_NAME to consts...

stash: : No module named consts

Any other ideas? Thanks in advance

ccc

I posted a GitHub issue... https://github.com/secdev/scapy/issues/598

inzel

@ccc Thank you!

abcabc

Pythonista does not support modules like subprocess. Hence I think that you may not be able to run this on pythonista.

I am able to install it but it gives error while running (not able to start the interactive session).

inzel

@abcabc Interesting. So how are people actually using scapy then? Just running it from a script? Seems odd that there is no interactive shell to test on..

ccc

@inzel Can you please respond to https://github.com/secdev/scapy/issues/598 by posting a full stack trace there?

yolelechamp64

@abcabc Not at all, that was an old windows bug...

yolelechamp64

@inzel Scapy is a very complete program. There are tons of usages:
- using the scapy shell (based on the python code.interact shell)
- directly from a script (it's easily importable)

It does not support IOS devices, neither pythonista. It works on Mac though...

Indeed the code integration is quite complex: for instance we need to detect the networking routes on the device, using a different way for every OS (we have a custom support for linux, windows, Mac...), as it's not supported in Python.

If we want to support IOS, there will be a lot of edits to do.

I would like to know if we will be able to support python on IOS one day, so if someone could answer those questions if would be great:
- Does pythonista supports RAW sockets ?
- Are there different networking interfaces ? Are they all detectable/accessable ?
- Does pythonista/IOS supports IPv6 ?
- Is it still impossible to get the device's MAC ? (pretty sure it was so in the past)

Thanks for reading.

minus

I don’t think this is feasible with iOS. I tried running

socket.socket(s.AF_INET,s.SOCK_RAW,s.IPPROTO_ICMP)

as part of an experimental host scanner and got operation not permitted. It might work on a rooted device but I’m not going to do that.

Cheers

AmirRoohi2K

Hey guys im new to this, can someone please make a very simple way of installing scapy, that would be awsome
thank you very much

JonB

It is all quite simple. Scapy requires libpcap or equivalent. While libpcap.dylib exists on iOS, you cannot access any devices (operation not permitted), therefore, you cannot use scapy on iOS.

This is due to Apple restrictions ..likely it could be made to work on a jailbroken device