changeset 33:83d66786f576

add port scanner that was written in python.
author taiki
date Mon, 29 Dec 2014 18:43:56 +0900
parents 4bd7d676e608
children ccac5d8090f6
files port_scan.py
diffstat 1 files changed, 76 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/port_scan.py	Mon Dec 29 18:43:56 2014 +0900
@@ -0,0 +1,76 @@
+#!/usr/bin/python
+
+
+from optparse import OptionParser
+
+import socket
+
+def h2ip(host):
+    try: 
+        ip = socket.gethostbyname(host)
+        return ip
+    except:
+        return None
+
+def connect_to(host, port):
+    try:
+        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        s.connect((host,port))
+        return s
+    except:
+        s.close()
+        return None
+
+def bgrabber(sock):
+    try:
+        sock.send("port scan now!")
+        banner = sock.recv(1024)
+        return banner
+    except:
+        return None
+
+def scan(host, port):
+    sock = connect_to(host, port)
+    socket.setdefaulttimeout(5)
+    if sock:
+        print("++ Connect %s:\t%d" %(host, port))
+        banner = bgrabber(sock)
+        if banner:
+            print("++ Grab banner :\n\t%s" %banner)
+        else:
+            print("-- Can't grab the target banner")
+        sock.close()
+    else:
+        print("-- Not connect %s:\t%d" % (host, port))
+
+
+
+if __name__=="__main__":
+    parser=OptionParser()
+    parser.add_option("-t", "--target", dest="host", type="string",
+            help="enter host name", metavar="exemple.com")
+    parser.add_option("-p", "--port", dest="ports", type="string",
+            help="port you want to scan separated by comma", metavar="PORT")
+
+    (options, args) = parser.parse_args()
+
+    if options.host == None or options.ports == None:
+        parser.print_help()
+    else:
+        host = options.host
+        ports = (options.ports).split(",")
+    try:  
+        ports = list(filter(int, ports))
+        ip = h2ip(host)
+        if ip:
+            print("++ Running scan on %s"%host)
+            print("++ Target IP: %s"%ip)
+            for port in ports:
+                scan(host, int(port))
+        else:
+            print("-- Invalid host")
+    except:
+            print("Invalid port list (e.g: -p 21,22,53,..)")
+        
+        
+