从Python中的列表项目中解析特定字符串
我在 python 中有以下代码,其中包含用于调试 SSH 的日志消息。
for log_item in ssh_log:
print(log_item.rstrip())
#will show ...
2022-04-06 01:55:15,085 10.x Remote version/idstring: SSH-2.0-ConfD-4.3.11.4
2022-04-06 01:55:15,085 20.x Connected (version 2.0, client ConfD-4.3.11.4)
2022-04-06 01:55:15,161 10.x kex algos:['diffie-hellman-group14-sha1'] server key:['ssh-rsa']
...
获取粗体值的方法是什么分配我的变量,可能是一些正则表达式作为 for 循环的一部分或其他东西来获取以下内容:
idstring = SSH-2.0-ConfD-4.3.11.4
kex_algos = ['diffie-hellman-group14-sha1']
key_type = ['ssh-rsa']
I have the following code in python, which contains log messages to debug SSH.
for log_item in ssh_log:
print(log_item.rstrip())
#will show ...
2022-04-06 01:55:15,085 10.x Remote version/idstring: SSH-2.0-ConfD-4.3.11.4
2022-04-06 01:55:15,085 20.x Connected (version 2.0, client ConfD-4.3.11.4)
2022-04-06 01:55:15,161 10.x kex algos:['diffie-hellman-group14-sha1'] server key:['ssh-rsa']
...
What is the approach to get the values in bold assign my variables, maybe some regex as part of the for loop or something else to get the following:
idstring = SSH-2.0-ConfD-4.3.11.4
kex_algos = ['diffie-hellman-group14-sha1']
key_type = ['ssh-rsa']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有正则表达式的解决方案。请参阅下面的内联评论。
如果您需要的话,您可以将打印更新为变量分配。
Solution without regex. See comments inline below.
You can update prints to variable assignments if this is what you required.
如果所有数据的格式与此处给出的数据相同,您可以使用以下正则表达式:
输出:
If all the data is in the same format as the data given here, You can use the following regex:
Output:
如果数据具有相似的结构,您也可以使用TTP模板来解析数据。
输出是:
You can also use ttp template to parse your data if your data has similar structure.
The output is :
通过文件中原始问题的3行示例数据,可以采用这种方法:
这里的假设是,只有关键字“远程”或“ kex”的行都是有趣的。
输出:
With the 3 lines of sample data from the original question in a file, one could take this approach:
The assumption here is that only lines with either of the keywords 'Remote' or 'kex' are of interest.
Output: