0

I am writing some codes to scan ports with Python. However, the error keeps showing up, I am not sure how to fix.

Error is listed below:

[+] Scan Results for: ubuntu
[-] 80/tcp closed
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "portscanner.py", line 23, in connScan
    connSkt.close()
UnboundLocalError: local variable 'connSkt' referenced before assignment

I did some research and appeared that I did not declare the variable properly, but I double checked the code and could not see what is wrong with it. Here is the tutorial I followed:

https://www.youtube.com/watch?v=IOvvjNi8OdU&list=PL1A2CSdiySGLtKwqBnqj9BON6QQjWkP4n&index=5

def connScan(tgtHost,tgtPort):
        try:
                connSkt = socket(AD_INET, SOCKET_STREAM)
                connSkt.connect((tgtHost,tgtPort))
                connSkt.send('Hello\r\n')

                results = connSkt.recv(100)
                screenLock.acquire()
                print "[+] "+ str(tgtPort) + "/tcp open"
        except:
                screenLock.acquire()
                print "[-] "+ str(tgtPort) + "/tcp closed"
        finally:
                screenLock.release()
                connSkt.close()`

any advise would be highly appreciated. Thanks in advance!

Lancer Xue
  • 118
  • 2
  • 9

1 Answers1

0

When socket creation fails with an exception, the variable connSkt is not yet created/defined in the Python interpreter. In that case, the call to close in the "finally" clause, is being invoked on an undefined variable. Hence, the interpreter is complaining.

Responding to follow-up question, one way to avoid this in the above (using LYBL approach):

connSkt = None
try:
    ...
except:
    ...
finally:
    screenLock.Release()
    if connSkt:
        connSkt.close() 

An EAFP approach might catch the exception but with my C-background, I am not quite comfortable catching exception for UnboundLocalError.

gsr
  • 91
  • 5
  • Thanks for the feedback. May I know how to create/define connSkt in python interpreter? or another alternative way to fix it? – Lancer Xue Jul 22 '19 at 12:45