Python Scripts « Security related discussions, articles, and tutorials

Mac OSX nmap nse script search

OK,

I was tired of listing the directory manually everytime I wanted to use a nmap nse scrip on my mac. Therefore, I wrote this simple script to either display all nmap nse script or search for a string and list the relevant scripts. Call me lazy but I am all about saving time and increasing efficiency. I also love the challenge =)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/python

""" Nmap Script search, this script displays all nmap scripts, or searches for a
string within the title of the nmap script"""


import sys,subprocess,os

# to see if nmap is installed and the script directory is in default directories

usage = """
nmap nse search script coded by bostonlink @ pentest-labs.org
example1: ./nse_search.py -l
example2: ./nse_search.py -s smb"""


help = """
Nmap nse search script options

-l = lists all nmap nse scripts within the /nmap/scripts directory

-s [search string] = searches all nse scripts and prints ones that matches the search string\n"""


if len(sys.argv) <= 1:
    print usage
    print help
    sys.exit(0)

cwd = os.getcwd()
script_path = '/usr/local/share/nmap/scripts/'

def chg_dir():
    if cwd != script_path:
        os.chdir('/usr/local/share/nmap/scripts/')
        print '\nChanged CWD to default nmap script directory\n'

def list_all():
    cmd1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
    lista = cmd1.stdout.read()
    cmd1.wait()
    print lista

def list_search():
    if len(sys.argv) <= 2:
        print usage
        print help
        sys.exit(0)
    else:
        search_string = sys.argv[2]
        cmd1 = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
        lista = cmd1.stdout.read()
        cmd1.wait()
        lista1 = lista.strip().split()
        for i in lista1:
            if search_string in i:
                print i

if sys.argv[1] == '-l':
    chg_dir()
    list_all()

if sys.argv[1] == '-s':
    chg_dir()
    list_search()

Note: same path in a Ubuntu Linux environment

you can use wget to download the script http://pentest-labs.org/downloads/nse_search.py

No Comments »

Quick Website Link puller script

I know it has been a while but what can I say I have been busy =)

Anyway, I scripted a quick link puller script that parses a website source code and prints all links within the code to the terminal. I found it useful so I thought I would share it with you all. I know there are some other programs out there that probably do the same thing, but hey I like the challenge of thinking through the scripting process and miking my scripts work. Hope you all enjoy.

ex: ./link_puller.py http://pentest-labs.org

Script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/python

"""URL Puller - pulls the source and parses links from a specified website"""

import urllib2,sys

usage = '''
link_puller.py coded by: bostonlink @ pentest-labs.org
example: ./link_puller.py http://pentest-labs.org
'''


if len(sys.argv) != 2:
    print(usage)
    sys.exit(0)

url_html = urllib2.urlopen(sys.argv[1])
html_read = url_html.read()

for url in html_read.split():
    if 'http://' in url:
        if 'href=' in url:
            urls = url.lstrip('href=').split('>')
            for i in urls:
                if 'http://' in i:
                    print(i.lstrip("'\"").rstrip("'\""))
    else:
        continue
No Comments »

Updated exploit_db_search_v2.py

Ok,

I just cleaned up the code a bit and made some very minor changes now all links will link to the v2 version of the script. Too see the changes click the link provided below.

http://pentest-labs.org/downloads/exploit_db_search_v2.py

Have fun.. Happy Hacking!

-bostonlink

No Comments »

Shodan Python API module install in Backtrack 4 R2

So, if you read my post below on my script that searches the exploit-db.com database for exploits for anything, there was a problem installing the shodan module in BT4 R2.  With a late night and a few beers in hand I went at this problem and got the shodan python module working.  I believe that it is due to the versions of python in BT4 R2 they are 2.4 and 2.5, where 2.5 is the default interpreter that is executed when running a script or just the IDE, python 2.6 does not have this issue at least on my macbook pro.  Below are the steps I took to get the shodan module sucessfully working on BT 4 R2.

first we install the ‘python-simplejson’ module that the sodan api.py is dependent on and download the shodan module’s source
[code]
apt-get install python-simplejson
wget http://pypi.python.org/packages/source/s/shodan/shodan-0.2.tar.gz
gzip -d shodan-0.2.tar.gz
tar xvf shodan-0.2.tar
cd shodan-0.2/shodan
nano api.py
[/code]

Now if we try to run the ‘setup.py install’ the module will error out and not install, so we have to edit the api.py file and change a couple of lines for it to install. the first line we need to edit is the first line of the file where it states ‘ from json import dumps,loads’ to ‘import simplejson as json’ then we go down to line 59 of the file and where it says ‘data = loads(data)’ change this too ‘data = json.loads(data)’ now save and exit the api.py file, and run the following commands:

[code]
cd ..
python setup.py install
[/code]
Now it successfully installs with no errors, and we have the shodan python api working.

-bostonlink

No Comments »

Exploit-db search python script

I just coded a nice little script while messing around with the shodan python library. It allows you to search for a string, list all exploits that were found, show a specific exploit (code), download a specific exploit, and change the search string. This is version 1 I just coded in a couple of hours to make sure everything works fine before posting to my blog. If you have any requests to add feel free to email me or add them yourself =).  I hope people find this useful I sure will.  I did code it on my Macbook pro due to the easy_install method of the shdan library returned errors in BT R2, not sure exactly why and didn’t bother looking further into it yet.  Just a heads up you will need to signup at http://www.shodanhq.com/ to get the API key which is needed to run this script.  The script is as follows, you can also download it from:
http://pentest-labs.org/downloads/exploit_db_search_v2.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/python

"""Searches exploit-db exploit database"""
# coded by: bostonlink @ pentest-labs.org
# thanks to shodanhq and exploit-db
# usage: ./exploit_db_search.py

import sys,shodan,urllib2

usage = '''\nexploit_db_search.py coded by: bostonlink @ pentest-labs.org
     usage: ./exploit_db_search.py [search_string]
          example: ./exploit_db_search.py php
'''


SHODAN_API_KEY = 'Enter Your Shodan API key here'
api = shodan.WebAPI(SHODAN_API_KEY)

if len(sys.argv) < 2 or len(sys.argv) > 3:
    print(usage)
    sys.exit(0)

# initial exploit-db search search
search_query = sys.argv[1]
results = api.exploitdb.search(search_query)

if len(results) > 0:
    print("Searching................\n")
    print("Search Executed Successfully")
    print("There are %s Exploits Found that relate to %s" % (results['total'],search_query))
    print("See Menu below for options")

# menu options
def menu():
    print('\nMenu Options\n')
    print('1 - list all exploits found')
    print('2 - select the type of exploits to display')
    print('3 - select a exploit to view')
    print('4 - write exploit to a file in the CWD')
    print('5 - change search string')
    print('6 - exit')
    global selection
    selection = raw_input('\nSelect an option from above: ')

menu()
# menu options end

# if statements
while True:

    if selection == '1':
        print('\nexploit id: description\n')
        for exploit in results['matches']:
            print('%s: %s' % (exploit['id'],exploit['description']))

    if selection == '2':
        print('exploit types : remote, webapps, dos, local, shellcode')
        exploit_type = raw_input('enter the type of exploit: ')
        print('\ndisplaying %s exploits\n' % exploit_type)
        for exploit in results['matches']:
            if exploit_type == exploit['type']:
                print('%s: %s' % (exploit['id'],exploit['description']))

    if selection == '3':
        exploit_id = raw_input('\nenter the exploit id to be displayed: ')
        for exploit in results['matches']:
            if exploit_id == str(exploit['id']):
                exploit_file = api.exploitdb.download(exploit['id'])
                print 'Filename: %s' % exploit_file['filename']
                print 'Content-type: %s' % exploit_file['content-type']
                print exploit_file['data']

    if selection == '4':
        exploit_id = raw_input('\nenter exploit id: ')
        for exploit in results['matches']:
            if exploit_id == str(exploit['id']):
                exploit_dl = api.exploitdb.download(exploit['id'])
                output = open(exploit_dl['filename'], 'w')
                output.write(exploit_dl['data'])
                output.close()

    if selection == '5':
        new_search = raw_input('enter new search string: ')
        results = api.exploitdb.search(new_search)
        print("Searching................\n")
        print("Search Executed Successfully")
        print("There are %s Exploits Found that relate to %s" % (results['total'],new_search))
        print("See Menu below for options")

    if selection == '6':
        print('Happy Hacking!')
        sys.exit(0)

    menu()

if you are going to use this code use the link above and wget, this is because of the wordwrap within my blog posts.

-bostonlink

No Comments »

Simple time saving dns info script

Simple dns info script which tells the user the nameservers, MX records, and attempts zone transfers on all nameservers. Check it out.
Click here to view and download the script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python

# a script that uses the host command to lookup various dns information of a target
# coded by: bostonlink

import sys,subprocess
usage = """\ndns_script.py coded by bostonlink @ pentestlabs.org\n
Usage: ./dns_script.py domainname
Example: ./dns_script.py google.com\n"""


if len(sys.argv) != 2:
    print(usage)
    sys.exit(0)

target = sys.argv[1]
print("\n" + "*" * 60)
print("%s nameservers" % sys.argv[1])
print("*" * 60 + "\n")

pro1 = subprocess.Popen(["host","-t","ns",target], stdout=subprocess.PIPE)
ns = pro1.stdout.read()
pro1.wait()
print(ns)

print("\n" + "*" * 60)
print("%s mailservers" % sys.argv[1])
print("*" * 60 + "\n")

pro2 = subprocess.Popen(["host","-t","mx",target], stdout=subprocess.PIPE)
mx = pro2.stdout.read()
pro2.wait()
print(mx)

ns_list = ns.strip().split()
for nameserver in ns_list:
    if nameserver.endswith("."):
        zone_tr = nameserver.rstrip(".")
        print("\n" + "*" * 60)
        print("%s zone transfer against %s" % (sys.argv[1],zone_tr))
        print("*" * 60 + "\n")
        pro3 = subprocess.Popen(["host","-l",target,zone_tr], stdout=subprocess.PIPE)
        ztrans = pro3.stdout.read()
        pro3.wait()
        print(ztrans)
    else:
        continue

print("\nScript completed")

Example:

root@bt:~/my stuff/scripts/python_dev# ./dns_script_2.py google.com

************************************************************
google.com nameservers
************************************************************

google.com name server ns1.google.com.
google.com name server ns2.google.com.
google.com name server ns4.google.com.
google.com name server ns3.google.com.

************************************************************
google.com mailservers
************************************************************

google.com mail is handled by 200 google.com.s9a2.psmtp.com.
google.com mail is handled by 100 google.com.s9a1.psmtp.com.
google.com mail is handled by 300 google.com.s9b1.psmtp.com.
google.com mail is handled by 400 google.com.s9b2.psmtp.com.

************************************************************
google.com zone transfer against ns1.google.com
************************************************************

; Transfer failed.
Using domain server:
Name: ns1.google.com
Address: 216.239.32.10#53
Aliases:

Host google.com.localdomain not found: 5(REFUSED)
; Transfer failed.

************************************************************
google.com zone transfer against ns2.google.com
************************************************************

snip……….

-bostonlink

No Comments »

Nmap python script – defines targeted ports

To start I was doing some nmap scans of my own network of course =) and I was looking for multiple targeted ports on my network.  I got real tired of typing and even arrowing up and changing the IP address ranges while conducting my scans.  So I figured why not turn this into a python exercise. I quickly coded a python script with my targeted ports I was looking for, also I made the ip address range a command line option as well as the nmap file output name a command line option.  This script saves me a lot of time while scanning. See the code below. Click here to view and download the script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python

# Targeted nmap scan script with 20 targeted ports defined

import subprocess,os,sys

author = "\n./targeted_nmap coded by bostonlink\n"
usage = """./targeted_nmap.py ip file_output_name
example: ./targeted_nmap.py 1.2.3.4 int_pentest\n"""

if len(sys.argv) != 3:
    print(author)
    print("check the arguments - script needs IP range or address and file name defined see usage and example below")
    print(usage)
    sys.exit(0)

subprocess.Popen("nmap -sS -PN %s -p T:21-23,25,80,110,135-139,443,445,3389,4444,8080,50000,10000 --reason -oA %s" % (sys.argv[1],sys.argv[2]), shell=True).wait()
print("\nNmap scan has finished see output files within the directory you ran this script in")
print("brought to you by: bostonlink - pentest-labs.org\n")

Hope you enjoy!

-bostonlink

No Comments »

Quick HTTP Header grabbing script

Just a quick script I came up with when I had to grab multiple url http headers. The script prints output to the terminal as well as writes an output file in the CWD you run the script from. The list of urls needs to have full http:// syntax and one url per line. Click here to view and download the script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python

# Simple program which opens a file of urls, retrives their headers and prints them to tty and writes to a file

import urllib2
import sys

usage = '''
Port 80 Headers - Multiple site list
Author: bostonlink
Usage:  ./80headers.py url_list'
Notes: Use a custom list of urls, each url should be on a new line.
eg:
http://google.com
http:yahoo.com
if there is an empty new line at the end of the file, the script will terminate when the '\n' newline is passed to it.
'''


if (len(sys.argv)!=2):
    print(usage)
    sys.exit(0)

usrfile = open(sys.argv[1], 'r')
outfile = open('output.txt', 'w')
outfile.close()

urls = usrfile.readlines()

for url in urls:
    if url == '\n':
        break
    else:
        url.rstrip()
        header = urllib2.urlopen(url).info()
        print('=' * 60)
        print(url)
        print('-' * 60)
        print(header)
        print('=' * 60)
        print('')
        f = open('output.txt', 'a')
        f.write(('=' * 60) + '\n' )
        f.write(url)
        f.write(('-' * 60) + '\n')
        f.write(str(header))
        f.close()

usrfile.close()
No Comments »