所以我从“Violent Python”同时学习Python和黑客攻击,我遇到了一个问题 这是我的代码:
import optparse
import socket
from socket import *
from 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' %tgtPort
print '[+] ' + str(results)
except:
screenLock.acquire()
print '[-]%d/tcp closed' %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(10)
for tgtPort in tgtPorts:
print 'Scanning port ' +tgtPort
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
t.start()
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[s] seperated by a comma')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(', ')
if (tgtHost == None) | (tgtPorts[0] == None):
print parser.usage
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()
运行程序我收到以下错误消息:
File "port_scanner.py", line 54, in <module>
main()
File "port_scanner.py", line 52, in main
portScan(tgtHost, tgtPorts)
File "port_scanner.py", line 37, in portScan
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
ValueError: invalid literal for int() with base 10: '21,'
有人可以帮忙吗?我还是新手,但我的猜测是Python没有通过运行此命令来分隔我输入的不同端口:
python port_scanner.py -H 74.207.244.221 -p 21, 22, 80
我定位的ip是scanme.org,用于扫描。谢谢!
答案 0 :(得分:6)
首先,您误解了命令行的解析方式。
你传入:
python port_scanner.py -H 74.207.244.221 -p 21, 22, 80
这意味着Python看到了:
['-H', '74.207.244.221', '-p', '21,', '22,', '80']
并且optparse.OptionParser
因此解析仅 '21,'
作为-p
切换的值。因此,options.tgtPort
设置为'21,'
,并且该值的.split(', ')
会产生['21,']
,因为否 ', '
(输入字符串中的逗号和空格)。
要在参数中包含空格,请在命令行中使用引号:
python port_scanner.py -H 74.207.244.221 -p "21, 22, 80"
但是您真的想调整命令行解析以在逗号上拆分只并容忍空格:
tgtPorts = [p.strip() for p in options.tgtPort.split(',')]
另一件需要理解的事情是,使用.split()
拆分字符串会产生一个至少一个元素的列表:
>>> 'foo'.split(',')
['foo']
因此,tgtPorts[0] == None
的测试始终为False
。请注意,正常的Python惯用法是使用is
代替None
(tgtPorts[0] is None
),因为None
是单身。
答案 1 :(得分:0)
端口的值中有逗号,因此Python无法顺利将字符串转换为整数。您可以轻松地在解释器中重现此异常:
>>> int("2,")
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
int("2,")
ValueError: invalid literal for int() with base 10: '2,'
>>> int("2")
2
要删除逗号,请不要在命令行中传递它。或者,如果你真的必须,处理输入,以便它可以转换。
答案 2 :(得分:0)
如果你改变:
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
到
t = Thread(target=connScan, args=(tgtHost, int(tgtPort.strip(","))))
它应该工作,不知道解析它的参数在哪里出错了..