Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use types when set string value #60

Open
beruhan opened this issue Apr 23, 2019 · 1 comment
Open

How to use types when set string value #60

beruhan opened this issue Apr 23, 2019 · 1 comment
Labels

Comments

@beruhan
Copy link

beruhan commented Apr 23, 2019

I want to set sysDescr.0 use set,but I don't know how to convert my string it to Type

oid = "1.3.6.1.2.1.1.1.0"
#how to conver a python string to Utf8String
value = "snmp test"
result = set(host, write_community, oid, value, port, timeout)
@exhuma
Copy link
Owner

exhuma commented Apr 23, 2019

Quick Fix

You can set it by creating an puresnmp.x690.types.OctetString instance and encoding the value to UTF-8:

from puresnmp.x690.types import OctetString
encoded_value = OctetString(value.encode('utf8'))

Let me know if this will work and I will close this issue.

Python 2 vs Python 3

The solution above is for Python 3! If you already use Python 3 you are fine and don't need to worry about byte details!

In Python 2, string values without "u" prefix are already considered bytes and you may run into double-encoding errors in the worst case. You have to be 100% certain that the value you encode into "utf8" is an instance of unicode. To do that, if the value is hard-coded in the script, simply prefix the string with u (u"tha-value") or decode it if it comes from user-input. If you have questions, don't hesitate to ask.

sysDescr is documented to be ASCII

A warning: According to RFC-1213 Section 3.2 the sysDescr field is limited to US-ASCII. Storing UTF-8 values is possible because the limit is purely conventional. And I have myself encountered devices which store non-ASCII values in those fields. So make sure that this will not break anything in unexpected ways.

If you want to be safe, and don't want to lose any data, you can use one of the replacement error-handlers for string encoding. For example, I quite like xmlcharrefreplace:

from puresnmp.x690.types import OctetString
encoded_value = OctetString(value.encode('ascii', errors='xmlcharrefreplace'))

If you want to use US-ASCII you can just wrap the string-value in OctetString without encoding. The encoding is automatic in puresnmp if not already encoded (see

self.value = value.encode('ascii')
)

@exhuma exhuma added the v1.x label May 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants