[英]I can't understand why my Port Scanner Python program is giving errors
I have recently started to learn Python and I tried to make a port scanner with Python but I am facing a few errors.我最近开始学习 Python 并尝试使用 Python 制作端口扫描器,但我遇到了一些错误。 Could someone help me understand where I went wrong?
有人可以帮助我了解我哪里出错了吗?
#!/usr/bin/python3
from socket import *
import optparse
from threading import *
def connScan(tgHost,tgPort):
try:
sock=socket(AF_NET,SOCK_STREAM)
sock.connect((tgHost,tgPort))
print('[+]%d/tcp Open'%tgPort)
except:
print('[-]%d/tcp Closed'%tgPort)
finally:
sock.close()
def portscan(tgHost,tgPort):
try:
tgIP=gethostbyname(tgHost)
except:
print('[!] Unkonown Host %s'%tgHost)
try:
tgName=gethostbyaddr(tgIP)
print('[+] Scan Result :' + tgName[0])
except:
print('[+]Scan Reults for:' + tgIP)
setdefaulttimeout(0)
for port in tgPort:
t=Thread(target=connScan,args=(tgHost,int(port)))
t.start()
def main():
parser=optparse.OptionParser("Usage of Program :" + " -H <target host> -p <target port> ")
parser.add_option('-H',dest='tgHost',type='string',help='specify target host')
parser.add_option('-p',dest='tgPort',type='string',help='specify target port separated by comma')
(options,args)=parser.parse_args()
tgHost=options.tgHost
tgPort=str(options.tgPort).split(',')
if (tgHost==None) | (tgPort[0]==None):
print (parser.usage)
exit(0)
portscan(tgHost,tgPort)
if __name__=='__main__':
main()
Sample Input:样本输入:
python portscan.py -H 192.168.0.102 -p 80 python portscan.py -H 192.168.0.102 -p 80
Sample Output:样品 Output:
[+]Scan Reults for:192.168.0.102
[-]80/tcp Closed
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\python3.9.4\lib\threading.py", line 954, in _bootstrap_inner
self.run()
File "C:\python3.9.4\lib\threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\DEBGANDHAR\pytools\adv.py", line 15, in connScan
sock.close()
UnboundLocalError: local variable 'sock' referenced before assignment
The error message should be self-evident;错误信息应该是不言而喻的; the variable you are attempting to use in the
finally:
block is undefined, because the error in the try:
block occurred before the variable was assigned.您尝试在
finally:
块中使用的变量未定义,因为try:
块中的错误发生在分配变量之前。
You have a similar error where you would try to use tgIP
even though you just found that no IP address can be resolved.即使您刚刚发现无法解析
tgIP
地址,您也会遇到类似的错误。
More generally you should avoid import *
when you can;更一般地说,您应该尽可能避免
import *
; your code only uses socket
in a few places, so spelling it out is a minor inconvenience, while it makes your code clearer.您的代码仅在少数地方使用了
socket
,因此将其拼写出来会带来一些不便,但它会使您的代码更清晰。 Ditto for threading
.同上
threading
。
Similarly, you should avoid blanket except:
blocks, and only trap exceptions which you actually know how to handle.同样,您应该避免笼统的
except:
块,并且只捕获您真正知道如何处理的异常。
The optparse
module is obsolescent, and should usually be replaced with argparse
in new code; optparse
模块已过时,在新代码中通常应替换为argparse
; but your arguments are not optional in the first place, so perhaps don't use a separate module for this trivial task.但是您的 arguments 首先不是可选的,所以也许不要为这个琐碎的任务使用单独的模块。
#!/usr/bin/python3
import socket as s
import threading
def connScan(tgHost, tgPort):
sock = None
try:
# Notice typo fix AF_INET
sock = s.socket(AF_INET, SOCK_STREAM)
sock.connect((tgHost,tgPort))
print('[+]%d/tcp Open'%tgPort)
except s.error:
print('[-]%d/tcp Closed'%tgPort)
finally:
if sock is not None:
sock.close()
def portscan(tgHost,tgPorts):
try:
tgIP = s.gethostbyname(tgHost)
except s.gaierror:
print('[!] Unknown Host %s'%tgHost)
# Give up
return None
try:
tgName = s.gethostbyaddr(tgIP)
print('[+] Scan Result :' + tgName[0])
except s.gaierror:
print('[+]Scan Results for:' + tgIP)
s.setdefaulttimeout(0)
for port in tgPorts:
t = threading.Thread(target=connScan,args=(tgHost,int(port)))
t.start()
def main():
from sys import argv
import logging
if len(argv) < 3:
logging.error("Usage of Program: %s <target host> <target port> ...", argv[0].split('/')[-1])
exit(2)
portscan(argv[1], argv[2:])
if __name__=='__main__':
main()
Notice how the list of ports is now just whitespace-separated.请注意端口列表现在是如何以空格分隔的。 (Notice also the correct spelling of "separate".)
(还要注意“分离”的正确拼写。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.