pyserial-在运行时发送参数-输入与raw_input-安全缺陷?
我正在编写一个程序,该程序打开并将通过串行端口发送的数据记录到文本文件中。我目前正在添加功能以允许在运行时重新配置串行端口。我提示用户选择一次更改哪个变量,以便让我自己保持简单(我也很欣赏优雅的解决方案)。
创建串行实例的 pyserial 函数 (serial.Serial()) 具有以下参数:
import serial
ser = serial.Serial(port=0, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0, writeTimeout=None, dsrdtr=None, interCharTimeout=None) #default values shown
我注意到,虽然大多数是 int() 参数,但有些不是,即“超时”。
我知道使用 int(raw_input("for the int() 类型变量)) 可以让我安全地分配 int 变量,但是默认为 None 的变量将需要 input()< /code> 函数来正确分配可能的 None 值。
我在其他地方读到,通常不建议使用 input() ,因为它有可能被利用(关于 eval() 的事情?)。使用serial.Serial(),其中writeTimout = str(None) 会引发错误,
谢谢!
I am writing a program that opens and records data sent through a serial port into a text file. I am currently adding functionality to allow reconfiguring the serial port during run-time. I prompt the user to choose which variable to change one at a time, so as to keep it simple for myself (i would appreciate elegant solutions as well).
The pyserial function that creates the serial instance (serial.Serial()) has the following parameters:
import serial
ser = serial.Serial(port=0, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0, writeTimeout=None, dsrdtr=None, interCharTimeout=None) #default values shown
I notice that while most are int() arguments, some are not, i.e. "timeout".
I know using int(raw_input("for the int() type variables))
would let me safely assign the int variables, but the variables with None as default would require an input()
function to properly assign the possible None value.
I have read elsewhere that input() is generally not recommended, since it has potential for being exploited(something about eval()?). How then should i handle those inputs? i.e. using serial.Serial() where writeTimout = str(None) throws an error.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最安全的方法就是接受用户的输入作为字符串,然后解析它。即让用户输入键=值对:
然后通过拆分“=”并剥离两侧来解析这些对。使用字符串查找表分配变量(
baudrate
字符串映射到baudrate
变量,依此类推)。这样您就可以按照您想要的方式处理None
值。此方法简单、安全。如果用户输入不是有效的 Python,
input
将引发异常,而您可能不希望这样。The safest way is just to accept the user's input as a string and then parse it. I.e. let the user enter key=value pairs:
Then parse these pairs, by splitting on '=' and stripping both sides. Assign the variables with a string lookup table (the
baudrate
string maps to thebaudrate
var, and so on). This way you can handle theNone
value any way you want.This method is simple and safe.
input
will raise exceptions if the user input isn't valid Python, and you may not want that.