pyserial-在运行时发送参数-输入与raw_input-安全缺陷?

发布于 2024-08-20 10:41:53 字数 686 浏览 12 评论 0原文

我正在编写一个程序,该程序打开并将通过串行端口发送的数据记录到文本文件中。我目前正在添加功能以允许在运行时重新配置串行端口。我提示用户选择一次更改哪个变量,以便让我自己保持简单(我也很欣赏优雅的解决方案)。

创建串行实例的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

难得心□动 2024-08-27 10:41:53

最安全的方法就是接受用户的输入作为字符串,然后解析它。即让用户输入键=值对:

baudrate = 9600
parity = N

然后通过拆分“=”并剥离两侧来解析这些对。使用字符串查找表分配变量(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:

baudrate = 9600
parity = N

Then parse these pairs, by splitting on '=' and stripping both sides. Assign the variables with a string lookup table (the baudrate string maps to the baudrate var, and so on). This way you can handle the None 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文