I am working my way through 'Violent Python'. I am in chapter 2, and I receive this syntax error when attempting to run the below code:
python2 portscanner.py -H perl6.org -p 21, 22, 80
['21,'] [+] Scan results for: www.p6c.org Scanning port 21, Traceback (most recent call last): File "/home/wolf/python/Violent-Python-Examples/Chapter-2/portscan.py", line 53, in main() File "/home/wolf/python/Violent-Python-Examples/Chapter-2/portscan.py", line 49, in main portScan(tgtHost, tgtPorts) File "/home/wolf/python/Violent-Python-Examples/Chapter-2/portscan.py", line 32, in portScan connScan(tgtHost, int(tgtPort)) ValueError: invalid literal for int() with base 10: '21,'
I copied it mostly directly from the code, but I did a few things to make it Python3 instead of Python2, such as adding the parenthesis for the print()
function. However, I being new to Python, I don't understand what the problem is here. I assume it is something with the split()
method?
import optparse
import socket
from socket import *
def connScan(tgtHost, tgtPort):
try:
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
connSkt.send('ViolentPython\r\n')
results = connSkt.recv(100)
print('[+]%d/tcp open' % tgtPort)
connSkt.close()
except:
print('[-]%d/tcp closed' % tgtPort)
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)
for tgtPort in tgtPorts:
print('Scanning port ' + tgtPort)
connScan(tgtHost, int(tgtPort))
def main():
parser = optparse.OptionParser("usage%prog -H <target host> +\
-p <target port>")
parser.add_option('-H', dest='tgtHost', type='string',
help='specify target host')
parser.add_option('-p', dest='tgtPort', type='string',
help='specify target port')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(', ')
print(tgtPorts)
if (tgtHost is None) | (tgtPorts[0] is None):
print('[-] You must specify a target host and port[s].')
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()