简体   繁体   English

我不明白为什么我的端口扫描仪 Python 程序出错

[英]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.

相关问题 为什么我的简单 python 程序给我错误 - Why is my simple python program giving me errors 为什么我的端口扫描程序不扫描Python中的端口? - Why is my Port Scanner not scanning ports in Python? 我的程序清空了我的列表,但我不明白为什么 - My program empties my list and I don't understand why 伙计们,我是 python 新手,请帮助我理解为什么我的代码给我“无”作为输出? - Guys I am new to python, can please help me understand why my code is giving me “none” as output? 我不明白为什么我不能让 python 中的 readline function 在这个程序中工作。 我究竟做错了什么? - I don't understand why i can't get readline function in python to work in this program. What am I doing wrong? Python 3给了我我无法解决的错误 - Python 3 is giving me errors that I can't resolve 我不明白为什么我的 python 脚本无法运行 Traceback 和 UnboundLocalError - I can't understand why my python script wont work Traceback and UnboundLocalError 如何向我的 Python 端口扫描器添加提示,要求用户输入他们想要扫描的端口? - How can I add a prompt to my Python port scanner that asks users to enter what ports they want scanned? 我不明白为什么我的 python 代码显示警告? - I don't understand why my python code is showing warning? Python-无法理解此反向程序 - Python - can't understand this reverse program
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM