Home Python in Cybersecurity - Port Scanner
Post
Cancel

Python in Cybersecurity - Port Scanner

Description

How to write adavanced port scanner in python

Video

Code

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
import socket
import re
from termcolor import colored
import optparse
from threading import *



def portscanner(host, port):
    try:
        socket.setdefaulttimeout(5)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        if sock.connect_ex((host,port)):
            print(colored("port %d closed" % port,'red'))
        else:
            print(colored("port %d open" % port, 'green' ))

    except Exception as error:
        print(error)



def portScan (host,ports):
     for port in ports:
         if 0 < int(port) < 65353:
            Th =Thread(target=portscanner,args=(host,int(port)))
            Th.start()
         else:
            print('%d is not valid' % port)



def main():
    parser = optparse.OptionParser('for scan -t <host ip> -p <host port > ')
    parser.add_option('-t',dest='targethost', type= 'string', help='type target host')
    parser.add_option('-p',dest='targetport', type= 'string', help='ports , seperated')
    (options, args) =parser.parse_args()
    target_host = options.targethost
    target_port = str(options.targetport).split(',')

    if (target_host is None) | (target_port[0] is None):
        print(parser.usage)
        exit(0)
    else:
        validIP = re.match(r"\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b", target_host)

        if bool(validIP):
            portScan(target_host,target_port)
        else:
            print('check the ip')



if __name__ == '__main__':
    main()



# while True:
#
#     try:
#         sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#         host = input("enter the host: ")
#         port = int(input("enter the port:  "))
#
#         validIP = re.match(r"\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b",host)
#         validport = True if 0 < port < 65535 else False
#
#
#         if bool(validIP) and validport:
#             portScan(host,port)
#         else:
#             print('check port or ip is valid')
#
#
#         sock.close()
#
#     except Exception as error:
#         print(error)
This post is licensed under CC BY 4.0 by the author.