Python3端口扫描器

套接字

import optparse
import socket
from threading import *


screenLock = Semaphore(value=1)
def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connSkt.connect((tgtHost, int(tgtPort)))
        connSkt.send('ViolentPython\r\n'.encode(encoding='utf-8'))
        results = connSkt.recv(100)
        screenLock.acquire()
        print('[+] %d/tcp open' % int(tgtPort))
        print('[+] ' + str(results))
        connSkt.close()
    except:
        screenLock.acquire()
        print('[-] %d/tcp close' % int(tgtPort))
    finally:
        screenLock.release()
        connSkt.close()

def portScan(tgtHost, tgtPorts):
    socket.setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        # print('scanning port ' + tgtPort)
        # connScan(tgtHost, tgtPort)
        t = Thread(target=connScan, args=(tgtHost, tgtPort))
        t.start()

def main():
    parser = optparse.OptionParser('usage %prog -H  -P ')
    parser.add_option('-H', dest='tgtHost', type='string', help='host')
    parser.add_option('-P', dest='tgtPort', type='string', help='port')
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')

    if (tgtHost is None) | (tgtPorts is None):
        print('[-] missing args')
        exit(0)
    portScan(tgtHost, tgtPorts)


if __name__ == '__main__':
    main()

nmap

import nmap
import optparse


def nmapScan(tgtHost, tgtPort):
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost, tgtPort)
    # print(nmScan)
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print('[*] ' + tgtHost + 'tcp/' + tgtPort + ' ' + state)


def main():
    parser = optparse.OptionParser('usage %prog -H  -P ')
    parser.add_option('-H', dest='tgtHost', type='string', help='host')
    parser.add_option('-P', dest='tgtPort', type='string', help='port')
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')

    if (tgtHost is None) | (tgtPorts is None):
        print('[-] missing args')
        exit(0)
    for tgtPort in tgtPorts:
        nmapScan(tgtHost, tgtPort)


if __name__ == '__main__':
    main()

你可能感兴趣的:(Python)