Hi I am using a python 3 script to do snmp set operation to one of switch.
The script is as follows.
import pysnmp
from pysnmp import hlapi
def cast(value):
try:
return int(value)
except (ValueError, TypeError):
try:
return float(value)
except (ValueError, TypeError):
try:
return str(value)
except (ValueError, TypeError):
pass
return value
def fetch(handler, count):
result = []
for i in range(count):
try:
error_indication, error_status, error_index, var_binds = next(handler)
if not error_indication and not error_status:
items = {}
for var_bind in var_binds:
items[str(var_bind[0])] = cast(var_bind[1])
result.append(items)
else:
raise RuntimeError('Got SNMP error: {0}'.format(error_indication))
except StopIteration:
break
return result
def construct_value_pairs(list_of_pairs):
pairs = []
for key, value in list_of_pairs.items():
pairs.append(hlapi.ObjectType(hlapi.ObjectIdentity(key), value))
return pairs
def set(target, value_pairs, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()):
handler = hlapi.setCmd(
engine,
credentials,
hlapi.UdpTransportTarget((target, port)),
context,
*construct_value_pairs(value_pairs)
)
return fetch(handler, 1)[0]
If i run set('10.23.193.153', {'1.3.6.1.2.1.1.5.0': 'Test1'}, hlapi.CommunityData('public'))
The script is executed and the hostname on switch changes to Test1.
However if i do another set operation using
set('10.23.193.153', {'1.3.6.1.4.1.11.2.14.11.5.1.16.19.1.2.1': 'admin'}, hlapi.CommunityData('public'))
I am getting the following error.
The above oid changes username of the switch.
> ============ RESTART: C:/Users/regop/Desktop/SNMP Password Reset.py ============ Traceback (most recent call last): File "C:/Users/regop/Desktop/SNMP Password Reset.py", line 53, in <module>
> set('10.23.193.153', {'1.3.6.1.4.1.11.2.14.11.5.1.16.19.1.2.1': 'admin'}, hlapi.CommunityData('public')) File
> "C:/Users/regop/Desktop/SNMP Password Reset.py", line 49, in set
> return fetch(handler, 1)[0] File "C:/Users/regop/Desktop/SNMP Password Reset.py", line 22, in fetch
> error_indication, error_status, error_index, var_binds = next(handler) File
> "C:\Users\regop\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysnmp\hlapi\asyncore\sync\cmdgen.py",
> line 214, in setCmd
> cmdgen.setCmd(snmpEngine, authData, transportTarget, File "C:\Users\regop\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysnmp\hlapi\asyncore\cmdgen.py",
> line 239, in setCmd
> return cmdgen.SetCommandGenerator().sendVarBinds( File "C:\Users\regop\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysnmp\entity\rfc3413\cmdgen.py",
> line 249, in sendVarBinds
> v2c.apiPDU.setVarBinds(reqPDU, varBinds) File "C:\Users\regop\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysnmp\proto\api\v1.py",
> line 131, in setVarBinds
> apiVarBind.setOIDVal( File "C:\Users\regop\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysnmp\proto\api\v1.py",
> line 42, in setOIDVal
> varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(val.getTagSet(),
> val, verifyConstraints=False, matchTags=False, matchConstraints=False,
> innerFlag=True) AttributeError: 'str' object has no attribute
> 'getTagSet'
Not sure what different I am doing here.
This unhandled exception feels like a bug in pysnmp, but that's irrelevant to your question.
My guess is that the problem is caused by your second OID not being resolved at a MIB and therefore the value (admin) not automatically casted into some SNMP type object.
The solution is one of:
Refer to your SNMP objects by their symbolic names (MIB, symbol, instance ID)
Keep using OIDs, but pre-load the MIB where that OID is defined
Keep using OIDs, but pass your values as SNMP objects so that no MIBs would be necessary
I have the same error, Because of my SNMP Device doesn't support 'integer' to write, just 'String'.
I suggest to check your OID address whether it supports 'String' to write or not.
Related
Here is a function to check the data and update it
div , update are my mongodb collection object
def data_updater(user1_id,code):
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"$set":message":code,"date":current_date}})
print(x.acknowledged)
and when I am calling the function it is giving TypeError data_updater(95626,972681)
the error
Traceback (most recent call last):
File line 170, in <module>
data_updater(95626,972681)
File line 71, in data_updater
device_id = dvi.find_one({"user_id":int(user1_id)},{"_id":0,"user_id":0})["device_id"]
TypeError: 'NoneType' object is not subscriptable
I am not able to find any mistake please help
Your context isn't very clear, however, from the error trace as generated it seems that your find_one() function returns None with the arguments as passed and you are trying to access the value for the key device_id. I recommend you refactor your find_one() function or make use of the following code to resolve the issue at hand:
def data_updater(user1_id,code):
try:
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"message":code,"date":current_date}})
print(x.acknowledged)
except TypeError:
print('No value found for specified parameters :/')
PS: I also didn't understand the use of $ in your code, so I removed it thinking of it as a mistake. Hope this helps! 😊
I have a function which returns a list. But it has nothing to return. I want to handle the TypeError.
I have tried this:
def isLookingAround(lst):
res = []
body = []
for data in lst:
res += isLookingAt(normalize2(data))
body += isBodyDirection(normalize2(data))
if most_body == "front" or most_body == "backward":
if ('lookL' in res and 'lookR' in res):
return 'lookingAround'
elif most_body == "left" or most_body == "right":
if ('lookF' in res and 'lookB' in res):
return 'lookingAround'
Error:
Traceback (most recent call last):
File "action_detector.py", line 201, in <module>
write_labels(input_source, labels)
File "action_detector.py", line 179, in write_labels
for itr, word in enumerate(lbls):
TypeError: 'NoneType' object is not iterable
I am still getting the error with labels.append(detectors.isLookingAround(back_Data)) . I would appreciate your help.
To check data is empty. you can use below code
if data:
l.append(data)
In order to handle the NoneType exception, you can surround the statement within try-except blocks.
For example, you can do something like,
try:
labels.append(detectors.isLookingAround(back_Data))
except TypeError:
# Do something. Like,
return
It will "catch" the error, and then you can handle it properly. However, the error seems to come from isLookingAround method.
You can re-check that, and if you're unable to resolve it, post a new question, I guess.
Here I have a mistake that I can't find the solution. Please excuse me for the quality of the code, I didn't start classes until 6 months ago. I've tried to detach category objects with expunge but once it's added it doesn't work.I was thinking when detaching the object with expunge it will work. and I can't find a solution :( . I pasted as much code as I could so you could see
Traceback (most recent call last):
File "/home/scwall/PycharmProjects/purebeurre/recovery.py", line 171, in <module>
connection.connect.add(article)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1776, in add
self._save_or_update_state(state)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1796, in _save_or_update_state
self._save_or_update_impl(st_)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2101, in _save_or_update_impl
self._update_impl(state)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2090, in _update_impl
self.identity_map.add(state)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/identity.py", line 149, in add
orm_util.state_str(state), state.key))
sqlalchemy.exc.InvalidRequestError: Can't attach instance <Categories at 0x7fe8d8000e48>; another instance with key (<class 'packages.databases.models.Categories'>, (26,), None) is already present in this session.
Process finished with exit code 1
class CategoriesQuery(ConnectionQuery):
#classmethod
def get_categories_by_tags(cls, tags_list):
return cls.connection.connect.query(Categories).filter(Categories.id_category.in_(tags_list)).all()
other file:
def function_recovery_and_push(link_page):
count_and_end_page_return_all = {}
count_f = 0
total_count_f = 0
list_article = []
try:
products_dic = requests.get(link_page).json()
if products_dic['count']:
count_f = products_dic['page_size']
if products_dic['count']:
total_count_f = products_dic['count']
if not products_dic['products']:
count_and_end_page_return_all['count'] = False
count_and_end_page_return_all['total_count'] = False
count_and_end_page_return_all['final_page'] = True
else:
count_and_end_page_return_all['final_page'] = False
for product in products_dic["products"]:
if 'nutrition_grades' in product.keys() \
and 'product_name_fr' in product.keys() \
and 'categories_tags' in product.keys() \
and 1 <= len(product['product_name_fr']) <= 100:
try:
list_article.append(
Products(name=product['product_name_fr'], description=product['ingredients_text_fr'],
nutrition_grade=product['nutrition_grades'], shop=product['stores'],
link_http=product['url'],
categories=CategoriesQuery.get_categories_by_tags(product['categories_tags'])))
except KeyError:
continue
count_and_end_page_return_all['count'] = count_f
count_and_end_page_return_all['total_count'] = total_count_f
list_article.append(count_and_end_page_return_all)
return list_article
except:
count_and_end_page_return_all['count'] = False
count_and_end_page_return_all['total_count'] = False
count_and_end_page_return_all['final_page'] = True
list_article.append(count_and_end_page_return_all)
return list_article
p = Pool()
articles_list_all_pool = p.map(function_recovery_and_push, list_page_for_pool)
p.close()
for articles_list_pool in articles_list_all_pool:
for article in articles_list_pool:
if type(article) is dict:
if article['count'] != False and article['total_count'] != False:
count += article['count']
total_count = article['total_count']
if article['final_page'] is True:
final_page = article['final_page']
else:
connection.connect.add(article)
I receive this as an error message, thank you in advance for your answers
This error happens when you try to add an object to a session but it is already loaded.
The only line that I see you use .add function is at the end where you run:
connection.connect.add(article)
So my guess is that this Model is already loaded in the session and you don't need to add it again. You can add a try, except and rollback the operation if it throws an exception.
Had the same issue, not sure you implemented the models as same as I did, but in my case at least, I had in the table's model - i.e:
product_items = relationship(...)
So later when I tried to do
products = session.query(Products).all()
one_of_the_products = products[0]
new_product = ProductItem(product_id=one_of_the_products.id, name='foo', category='bla')
session.add(new_product)
It raises the same exception as you:
sqlalchemy.exc.InvalidRequestError: Can't attach instance <ProductItem at 0x7fe8d8000e48>; another instance with key (<class 'packages.databases.models.ProductItem'>, (26,), None) is already present in this session.
The reason for the exception, is that when I queried for products - the relationship created it's own sub-query and attached the product_item's objects, it placed them in the variable name I defined in the relationship() -> product_items.
So instead of doing:
session_add(new_product)
I just had to use the relationship:
one_of_the_products.product_items.append(new_product)
session.commit()
hope it helps others.
unloading all objects from session and then adding it again in session might help.
db.session.expunge_all()
db.session.add()
I'm trying to prevent to use eval based on an example how-to-avoid-eval-in-python-for-string-conversion using ast. The challange is that there are a dozen of these self.ch%s_label's to be made but the variable for it changes based on user input in the GUI.
My code:
import ast ...etc.
....
channel_no += 1
ch_width = eval('self.ch%s_label.frameGeometry().width()' % (channel_no))
When I change it into:
ch_width = ast.literal_eval('self.ch%s_label.frameGeometry().width()' % (channel_no))
I'll get the error:
File "c:\python\anac2\lib\ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "c:\python\anac2\lib\ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
Changing the code (using closing " ") retains the error:
ch_width = ast.literal_eval("'self.ch%s_label.frameGeometry().width()' % (channel_no)")
What other options are there... Any suggestions?
You could use getattr to get the attribute from the instance using the dynamically constructed attribute name:
ch_width = getattr(self, 'ch%s_label' % channel_no).frameGeometry().width()
Or step by step:
channel_no = 5
attr_name = 'ch%s_label' % channel_no
attr = getattr(self, attr_name)
ch_width = attr.frameGeometry().width()
Using getattr in this way also means you get an AttributeError if an object doesn't have the attribute, as you'd expect.
I try to use these both prepared statements in my django app:
READINGS = "SELECT * FROM readings"
READINGS_BY_USER_ID = "SELECT * FROM readings WHERE user_id=?"
I query against the db with:
def get_all(self):
query = self.session.prepare(ps.ALL_READINGS)
all_readings = self.session.execute(query)
return all_readings
def get_all_by_user_id(self, user_id):
query = self.session.prepare(ps.READINGS_BY_USER_ID)
readings = self.session.execute(query, [user_id])
return readings
The first of both works pretty well. But the second gives me:
ERROR 2015-07-08 09:42:56,634 | views::exception_handler 47 | ('Unable to complete the operation against any hosts', {<Host: localhost data1>: TypeError("'unicode' does not have the buffer interface",)})
Can anyone tell me what happened here? I understand, that there must be a unicode string somewhere that does not have a buffer interface. But which string is meant? My prepared statement?
Here is the stacktrace in addition:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/views.py", line 448, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/me/Workspace/project/Readings/views.py", line 36, in get_by_user_id
readings = self.tr_dao.get_all_by_user_id(user_id)
File "/Users/me/Workspace/project/Readings/dao.py", line 22, in get_all_by_user_id
readings = self.session.execute(query, [user_id], timeout=60)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cassandra/cluster.py", line 1405, in execute
result = future.result(timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cassandra/cluster.py", line 2967, in result
raise self._final_exception
if you are on python 2 this will probably fix it
def get_all_by_user_id(self, user_id):
query = self.session.prepare(ps.READINGS_BY_USER_ID)
readings = self.session.execute(query, [str(user_id)])
return readings
This is not working because your user_id is of type unicode. You can check it using
type(user_id)
If that is the case you should encode it to string:
str(user_id)
It will solve the issue.