简单介绍:
说明: 在指定命名空间中计算参数字符串的有效表达式,并返回一个对象,
Help on built-in function eval in module __builtin__: eval(...) eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
技巧: eval很危险,因为它默认在当前命名空间中解析语句表达式,但它支持设定命名空间防止当前命名空间被污染,可以有效防止注入
最佳实践:
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://xmdevops.blog.51cto.com/ # Purpose: # """ # 说明: 兼容绝对导入 from __future__ import absolute_import # 说明: 导入公共模块 import time import operator # 说明: 导入其它模块 from .alarm import alarm_template from .alarm.api import weixin_notify def avg(alarmtmplist, redis_key, trigg_key, trigg_val, errors): scope = {} realdata_lst = [] (service_name, converts_val, during_time, _, operator_val, compare_time, warnning_val, critical_val) = trigg_val convertsfunc = eval(converts_val, scope) warnning_val = convertsfunc(warnning_val) critical_val = convertsfunc(critical_val) datacate, host, plugin = redis_key.split(‘::‘) operatorfunc = getattr(operator, operator_val) for cur_item in alarmtmplist: cur_item = convertsfunc(cur_item[‘data‘][‘target‘]) realdata_lst.append(cur_item) avg_realdata = sum(realdata_lst)/len(realdata_lst) warnning_res = operatorfunc(avg_realdata, warnning_val) critical_res = operatorfunc(avg_realdata, critical_val) msgtime = time.strftime(‘%H:%M:%S‘, time.localtime()) formats = ‘PLUGIN(%s) DURINGTIME(%s) COMPARETIMES(%s) AVG(%s) OPERATION(%s) TARGET(%s)‘ if critical_res: message = formats % (plugin, during_time, compare_time, avg_realdata, operator_val, critical_val) res_msg = alarm_template % (host, ‘critical‘, errors, msgtime, message) weixin_notify(res_msg) return if warnning_res: message = formats % (plugin, during_time, compare_time, avg_realdata, operator_val, warnning_val) res_msg = alarm_template % (host, ‘warnning‘, errors, msgtime, message) weixin_notify(res_msg) return
说明: 此文件本是预警系统阀值处理接口文件,传递过来的参数converts_val可能为str/int/float等类型名称,都属于内置函数名,为了不污染当前线程运行环境同名内置函数,定义一个空scope,搜索时就在scope的__builtins__中调用纯净的str/int/float等内置函数,如果不定义,线程下次运行时可能就找不到str/int/float等内置函数.
本文出自 “ζ自动化运维开发之路ζ” 博客,请务必保留此出处http://xmdevops.blog.51cto.com/11144840/1860640
基础入门_Python-内建函数.运维开发中eval内建函数的最佳实践?
原文地址:http://xmdevops.blog.51cto.com/11144840/1860640