使用 Python 脚本禁用 HID 设备
在 Linux 系统中,xinput
是一个非常强大的工具,允许我们管理输入设备,比如键盘、鼠标和触控板。有时,我们可能需要禁用特定的 HID 设备。本篇博客将介绍如何编写一个 Python 脚本来自动禁用指定的 HID 设备。
环境准备
在开始之前,请确保你的系统中已经安装了 xinput
和 dmesg
命令。你可以使用以下命令检查是否安装:
which xinput
which dmesg
如果没有安装,可以使用包管理器安装它们。例如,在 Debian 或 Ubuntu 系统上,可以使用以下命令:
sudo apt-get install xinput
脚本介绍
下面是一个 Python 脚本,它接受一个 HID 设备路径(例如 /dev/hidrawX
),并通过一系列操作禁用该设备。
import subprocess
import sys
import re
def main(device_path):
# 提取 hidrawX
device_name = device_path.split('/')[-1]
# 获取 dmesg 信息
command = f"dmesg | grep {device_name} | tail -1"
process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, text=True)
if process.returncode != 0:
print(f"Error executing command: {command}")
print(process.stderr)
return
dmesg_output = process.stdout.strip()
print(f"dmesg output: {dmesg_output}")
# 提取第二个中括号中的字符串
matches = re.findall(r'\[([^\]]+)\]', dmesg_output)
if len(matches) < 2:
print("Could not find the second string in brackets.")
return
target_string = matches[1]
print(f"Extracted string: {target_string}")
# 执行 xinput 命令
xinput_command = f"xinput --list | grep '{target_string}' | grep -v Control"
xinput_process = subprocess.run(xinput_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, text=True)
if xinput_process.returncode != 0:
print(f"Error executing command: {xinput_command}")
print(xinput_process.stderr)
return
# 提取设备 ID
xinput_output = xinput_process.stdout.strip()
print(f"xinput output:\n{xinput_output}")
id_match = re.search(r'id=(\d+)', xinput_output)
if not id_match:
print("Could not find device ID.")
return
device_id = id_match.group(1)
print(f"Device ID: {device_id}")
# 禁用设备
disable_command = f"xinput --set-prop {device_id} 'Device Enabled' 0"
disable_process = subprocess.run(disable_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, text=True)
if disable_process.returncode != 0:
print(f"Error executing command: {disable_command}")
print(disable_process.stderr)
else:
print(f"Device {device_id} disabled successfully.")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python disable_hid.py /dev/hidrawX")
sys.exit(1)
device_path = sys.argv[1]
main(device_path)
运行脚本
将上述代码保存为 disable_hid.py
。在终端中运行以下命令以禁用指定的 HID 设备:
python disable_hid.py /dev/hidrawX
将 /dev/hidrawX
替换为你想要禁用的 HID 设备路径。
脚本解析
-
提取设备名称:从传入的设备路径中提取设备名称,例如
hidrawX
。 -
获取 dmesg 信息:使用
dmesg
命令获取包含设备名称的最新一条信息。 -
提取目标字符串:从
dmesg
输出中提取第二个中括号内的字符串,这通常是设备的标识信息。 -
查找设备 ID:使用
xinput --list
命令查找匹配目标字符串的设备,并提取设备 ID。 -
禁用设备:使用
xinput --set-prop
命令将设备的Device Enabled
属性设置为 0,禁用该设备。
注意事项
- 确保你有足够的权限运行这些命令。某些操作可能需要
sudo
权限。 - 脚本中的正则表达式和命令假定特定的输出格式,可能需要根据实际情况进行调整。
通过这个脚本,你可以轻松地自动化禁用特定的 HID 设备,省去了手动操作的麻烦。如果你有任何问题或建议,欢迎在评论区留言讨论。
原文地址:https://blog.csdn.net/dmgy110/article/details/140699670
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!