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!
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.
Related
I copied the codes from the example to learn scapy. But realized the IDE showed the error with unsolved reference for IP() & TCP(). Anyone know how to fix this?
Here are the codes:
#! /usr/bin/env python
from scapy.all import *
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
dst_ip = "10.0.0.1"
src_port = RandShort()
dst_port=80
tcp_connect_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"), timeout=10)
if(str(type(tcp_connect_scan_resp))==""):
print("Closed")
elif(tcp_connect_scan_resp.haslayer(TCP)):
if(tcp_connect_scan_resp.getlayer(TCP).flags == 0x12):
send_rst =sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="AR"),timeout=10)
print("Open")
elif (tcp_connect_scan_resp.getlayer(TCP).flags ==0x14):
print("Closed")
I'm using Pycharm IDE. Python2.7 and scapy 2.4.0. I searched on stackoverflow and found someone asked the same question before but no answer.....
Here is the error after I tried to run the codes:
/Users/chenneyhuang/PycharmProjects/Scanner/venv/bin/python /Users/chenneyhuang/PycharmProjects/Scanner/TCP.py
Traceback (most recent call last):
File "/Users/chenneyhuang/PycharmProjects/Scanner/TCP.py", line 12, in <module>
tcp_connect_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"), timeout=10)
File "/Users/chenneyhuang/PycharmProjects/Scanner/venv/lib/python2.7/site-packages/scapy/sendrecv.py", line 393, in sr1
s=conf.L3socket(promisc=promisc, filter=filter, nofilter=nofilter, iface=iface)
File "/Users/chenneyhuang/PycharmProjects/Scanner/venv/lib/python2.7/site-packages/scapy/arch/bpf/supersocket.py", line 58, in __init__
(self.ins, self.dev_bpf) = get_dev_bpf()
File "/Users/chenneyhuang/PycharmProjects/Scanner/venv/lib/python2.7/site-packages/scapy/arch/bpf/core.py", line 98, in get_dev_bpf
raise Scapy_Exception("No /dev/bpf handle is available !")
scapy.error.Scapy_Exception: No /dev/bpf handle is available !
Process finished with exit code 1
I answered the same Unsolved Reference issue last week here:
vscode import error: from scapy.all import IP
In short, don't worry about that error, it's a limitation of Pylint (or similar). I propose a workaround in the other question, if you'd like to remove the error/warning.
For the No /dev/bpf handle is available error, have you tried running the script as root? I see that suggested as a solution over on this GitHub issue: https://github.com/secdev/scapy/issues/1343
GECKODRIVER_PATH = 'F:/geckodriver.exe'
firefox_options = Options()
firefox_options .add_argument("-headless")
driver = webdriver.Firefox(executable_path=CHROMEDRIVER_PATH, firefox_options = firefox_options )
test = []
test.append('http://google.com')
test.append('http://stackoverflow.com')
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Now, how can I take multiple screenshots and save them in the different filename? As you can see I am trying to save the filename according to domain URL but failed.
See the error below:
http://google.com
http://card.com
Traceback (most recent call last):
File "F:\AutoRecon-master\test.py", line 125, in <module>
driver.get(x)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 326, in get
self.execute(Command.GET, {'url': url})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Tried to run command without establishing a connection
Can anyone please tell me what is the exact problem is? Will be a big help.
Try to move driver.close() out of loop:
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Also note that x is already a string, so there is no need in str(x)
P.S. I'm not sure that http://stackoverflow.com.png filename is acceptable, you might need to use:
filename = x.split('//')[-1] + '.png'
Tried to run command without establishing a connection
you are closing the browser within your for loop... so the 2nd time through the loop it fails with the error above (since the browser is closed, the connection to geckodriver has already been terminated).
other issues:
you are setting the page_load_timeout after you have already fetched the page, so it is not doing anything useful.
using CHROMEDRIVER_PATH as the name for Geckodriver is just confusing. Chromedriver is not used at all here.
In the beginning of the program the log file is named as:
filename='D://my_code_3/logging/'+timestr+'_XFR.log'
###set up logging to file
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',datefmt='%m-%d %H:%M',filename='D://my_code_3/logging/'+timestr+'_XFR.log', filemode='w')
During the execution of the program, various entries are made in this log file.
At the end of the program, it is required to rename the log file, to include a unique str variable (str9)captured by the program (which was initially unavailable at the beginning of the program execution, when the log file was just created). In order to rename the log file at the end of the program, the old_name log file has to be closed at first. I included these instructions in the following code:
fh = open('D://my_code_3/logging/'+timestr+'_XFR.log', "r")
print fh.read()
fh.close()
Then at the very end, I ask for a rename as below:
old_file ='D://my_code_3/logging/'+timestr+'_XFR.log'
new_file = 'D://my_code_3/logging/'+timestr+''+str9+'_XFR.log'
os.rename(old_file, new_file)
I get the following error message:
`
Traceback (most recent call last): File "qar_xfr_2017_10_05_WIP.py",
line 283, in
os.rename(old_file, new_file) WindowsError: [Error 32] The process cannot access the file because it is being used by another process`
I think that the old_file is still being written, and hence the message that th e file is open. If so, how can i provide a time delay before attempting to rename the old_file?
Thanks in advance for correcting / suggestion a solution.
All handlers need to be closed properly by calling
logging.shutdown()
After that you can rename the log file.
While trying to run Stem's To Russia With Love example, I am getting the following error:
~$ python practice.py
Starting Tor:
Traceback (most recent call last):
File "practice.py", line 49, in <module>
init_msg_handler = print_bootstrap_lines,
File "/usr/local/lib/python2.7/dist-packages/stem/process.py", line 266, in launch_tor_with_config
return launch_tor(tor_cmd, args, torrc_path, completion_percent, init_msg_handler, timeout, take_ownership)
File "/usr/local/lib/python2.7/dist-packages/stem/process.py", line 143, in launch_tor
raise OSError('Process terminated: %s' % last_problem)
OSError: Process terminated: Timed out
I was initially getting the path error that was solved over here. I tried restarting the Ubuntu instance (I am running Ubuntu 14.04 in VirtualBox) just in case if any other running tor was conflicting but its giving the same error. Could anyone please help?
EDIT: My torrc file also seems to be empty right now if this is in any way connected.
It might be failing because you are missing the GeoIP database which is required to use an exit node from a specific country.
Try removing the 'ExitNodes': '{ru}', line from the python script, or since you're on Ubuntu, try sudo apt-get install tor-geoipdb and see if that helps get the connection up and running.
Since it takes time to build the circuits, you can try increasing the timeout a bit as well (though this probably isn't why its failing).
tor_process = stem.process.launch_tor_with_config(
#tor_cmd = '/usr/bin/tor',
timeout = 300,
config = {
'SocksPort': str(SOCKS_PORT),
# 'ExitNodes': '{ru}',
'DataDir': '/tmp/tor',
'Log': [
'NOTICE file /tmp/tor.notice.log',
'ERR file /tmp/tor.log',
],
},
init_msg_handler = print_bootstrap_lines,
)
I have just installed django-cnotes
But it wont work.
It just throws up this error
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/core/servers/basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "/Library/Python/2.5/site-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/Library/Python/2.5/site-packages/django/core/handlers/wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "/Library/Python/2.5/site-packages/django_cnote-0.3.4-py2.5.egg/cnotes/middleware.py", line 47, in process_response
signed_data = self.sign('cnotes', base64.urlsafe_b64encode(Pickle.dumps(cnotes.cnotes)))
PicklingError: Can't pickle <class 'django.utils.functional.__proxy__'>: attribute lookup django.utils.functional.__proxy__ failed
And it is not even in the normal django error debug page. What you see above is all there is on the screen.
And I have just used it as described on github, I just dont get it. Any one have an idea for what is causing this?
UPDATE:
Okay, so I have found something, I think.
message = _("You have successfully altered ")
message += edituser.username
cnotes.add(message)
message2 = _("You may now close ")
cnotes.add(message2)
This will cause the error. So I thought "Okay, I can only call it once per view" That would have been stupid and it was indeed not the cause.
The following code will produce no error
message = _("You have successfully altered ")
message += edituser.username
cnotes.add(message)
message2 = '_("You may now close ")'
cnotes.add(message2)
But is not because of the translation it uses that fine just 2 lines above, but it has to be something with doing another translation or something. Im lost.
It appears as though pickle is receiving an object of type django.utils.functional.__proxy__. This means either your input is weird, or there is a bug in cnotes.
If there is something wrong with your input to cnotes, you should see it if you take a look at the types of your messages (I used the manage.py shell):
>>> message = _("You have successfully altered ")
>>> message += "Bob Knoblick"
>>> type(message)
<type 'unicode'>
>>> message2 = _("You may now close ")
>>> type(message2)
<type 'unicode'>
>>>
If your types come back as anything other than unicode or str, I'd dig into your code and figure out where that other type is coming from, or ensure that it can be pickled.
If there is something wrong within cnotes, you should get the same error doing this:
cnotes.add(u'Foo')
cnotes.add(u'Bar')
cnotes.add(u'Baz')
Per the original author:
The translated string, _("You may now close ") was not ending up as a unicode string. One can use this to force unicode before sending to cnotes:
message2 = unicode(_("You may now close "))