argparse - Python Port Scanner with arg parser doesn't properly take multiple arguments -
i trying update code great albeit dated book called "violent python." many of examples used deprecated optparse library , have switched argparse in examples, however, modified code doesn't work particular script if use more 1 port argument. became frustrated attempted use original example, code not work @ all.
what works...
python portscan.py -h ipaddress -p 21 [+] scan results for: (banner) [-]21/tcp closed port
what doesn't work...
python portscan.py -h ipaddress -p 21, 22 usage: usage%prog -h <target host> -p <target port> [-h] [-h tgthost] [-p [tgtport [tgtport ...]]] usage%prog -h <target host> -p <target port>: error: argument -p/--tgtport: invalid int value: '21,'
i realize because argparse takes multiple values 1 argument , turns them list, have tried multiple methods mapping list integer values. fail. appreciate insight ladies , gents can give!
here's code below...
import argparse socket import * threading import * screenlock = semaphore(value=1) def connscan(tgthost, tgtport): try: connskt = socket(af_inet, sock_stream) connskt.connect((tgthost, tgtport)) connskt.send('violentpython\r\n') results = connskt.recv(100) screenlock.acquire() print '[+]%d/tcp open port '% tgtport #+ str(tgtport) print '[+] ' + str(results) except: screenlock.acquire() print '[-]%d/tcp closed port '% tgtport #+ str(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) tgtport in tgtports: t = thread(target=connscan, args=(tgthost, tgtport)) t.start() def main(): parser = argparse.argumentparser("usage%prog " "-h <target host> -p <target port>") parser.add_argument('-h', '--tgthost', help='specify target host') parser.add_argument('-p', '--tgtport', nargs= '*', type=int, help='specify target port') args = parser.parse_args() tgthost = args.tgthost tgtports = args.tgtport #str(args.tgtport).split(',') if (tgthost == none) | (tgtports == none): print parser.usage exit(0) portscan(tgthost, tgtports) if __name__ == '__main__': main()
i've tried code. know of time don't use ,
seperate arg values. instead, use space:
>python port_scanner.py -h 127.0.0.1 -p 21 22 [+] scan results for: localhost [-]21/tcp closed port [-]22/tcp closed port
Comments
Post a Comment