Skip to content

Commit e47e636

Browse files
committed
Portscanner, host and list of ports
Code was taken from Violent Python book
1 parent 768c9f9 commit e47e636

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

portscanner.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Script Name : portscanner.py
2+
# Author : Craig Richards
3+
# Created : 20 May 2013
4+
# Last Modified :
5+
# Version : 1.0
6+
7+
# Modifications :
8+
9+
# Description : Port Scanner, you just pass the host and the ports
10+
11+
import optparse # Import the module
12+
from socket import * # Import the module
13+
from threading import * # Import the module
14+
15+
screenLock = Semaphore(value=1) # Prevent other threads from preceeding
16+
17+
def connScan(tgtHost, tgtPort): # Start of the function
18+
try:
19+
connSkt = socket(AF_INET, SOCK_STREAM) # Open a socket
20+
connSkt.connect((tgtHost, tgtPort))
21+
connSkt.send('')
22+
results=connSkt.recv(100)
23+
screenLock.acquire() # Acquire the lock
24+
print '[+] %d/tcp open'% tgtPort
25+
print '[+] ' + str(results)
26+
except:
27+
screenLock.acquire()
28+
print '[-] %d/tcp closed '% tgtPort
29+
finally:
30+
screenLock.release()
31+
connSkt.close()
32+
33+
def portScan(tgtHost, tgtPorts): # Start of the function
34+
try:
35+
tgtIP = gethostbyname(tgtHost) # Get the IP from the hostname
36+
except:
37+
print "[-] Cannot resolve '%s': Unknown host"%tgtHost
38+
return
39+
try:
40+
tgtName = gethostbyaddr(tgtIP) # Get hostname from IP
41+
print '\n[+] Scan Results for: ' +tgtName[0]
42+
except:
43+
print '\n[+] Scan Results for: ' + tgtIP
44+
setdefaulttimeout(1)
45+
for tgtPort in tgtPorts: # Scan host and ports
46+
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
47+
t.start()
48+
49+
def main():
50+
parser = optparse.OptionParser('usage %prog -H'+' <target host> -p <target port>')
51+
parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
52+
parser.add_option('-p', dest='tgtPort',type='string', help='specify target port[s] seperated by a comma')
53+
(options, args) = parser.parse_args()
54+
tgtHost = options.tgtHost
55+
tgtPorts = str(options.tgtPort).split(',')
56+
if (tgtHost == None) | (tgtPorts[0] == None):
57+
print parser.usage
58+
exit(0)
59+
portScan(tgtHost, tgtPorts)
60+
if __name__ == '__main__':
61+
main()

0 commit comments

Comments
 (0)