Skip to content

Instantly share code, notes, and snippets.

@olafurjohannsson
Created July 10, 2016 11:34
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 olafurjohannsson/20c39c38d4a5d4d4636427fb33e92671 to your computer and use it in GitHub Desktop.
Save olafurjohannsson/20c39c38d4a5d4d4636427fb33e92671 to your computer and use it in GitHub Desktop.
Scan TCP ports on a network with Python
# -*- coding: utf-8 -*-
"""
@author: Ólafur Aron Jóhannsson
@email: olafur@johannsson.co
"""
import optparse, nmap, re
from socket import *
from threading import *
# chillax the thread
screenLock = Semaphore(value=1)
# nmap lib
def nmapScan(tgtHost, tgtPort):
nmScan = nmap.PortScanner()
nmScan.scan(tgtHost, tgtPort)
state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
try:
name = gethostbyaddr(tgtHost)[0]
if name is not None:
print 'Scanning host: {0}'.format(name)
except:
pass
print '[*] {0} tcp/{1} {2}'.format(tgtHost, tgtPort, state)
def connScan(tgtHost, tgtPort):
try:
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
# garbage data
connSkt.send('vi')
results = connSkt.recv(128)
screenLock.acquire()
print '[+] %d/tcp open' % tgtPort
print '[+] ' + str(results)
except:
screenLock.acquire()
print '[-] %d/tcp closed ' % tgtPort
finally:
screenLock.release()
connSkt.close()
def portScan(tgtHost, tgtPorts):
try:
tgtIP = gethostbyname(tgtHost)
except:
print "[-] Cannot resolve '%s': Unknown host " % tgtHost
return
try:
tgtName = gethostbyaddr(tgtIP)
print '\n[+] Scan results for: ' + tgtName[0]
except:
print '\n[+] Scan results for: '+ tgtIP
setdefaulttimeout(1)
for tgtPort in tgtPorts:
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
t.start()
def main():
parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
#options
parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if (tgtHost == None) | (tgtPorts[0] == None):
print '[-] You must specify a target host and port[s]'
print parser.usage
exit(0)
# use nmap if we have a valid IP(add support to get hostaddr and use portScan as fallback)
reip = u'\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b'
ip = ''
if re.match(reip, tgtHost) is not None:
ip = tgtHost
else:
ip = gethostbyname(tgtHost)
# after nmap lib, portscan and connscan is kinda useless
for tgtPort in tgtPorts:
nmapScan(ip, tgtPort)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment