76 lines
2.5 KiB
Python
76 lines
2.5 KiB
Python
|
|
import requests
|
|||
|
|
from requests.auth import HTTPDigestAuth
|
|||
|
|
import xml.etree.ElementTree as ET
|
|||
|
|
|
|||
|
|
def control_hikvision_door(device_ip, user_name, password, command="open"):
|
|||
|
|
"""
|
|||
|
|
通过 ISAPI 协议控制海康门禁设备的开关状态。
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
device_ip (str): 设备的 IP 地址 (例如 "192.168.1.69")。
|
|||
|
|
user_name (str): 登录用户名。
|
|||
|
|
password (str): 登录密码。
|
|||
|
|
command (str): 控制指令,默认为 "open" (常开/开门)。
|
|||
|
|
部分设备支持 "close" (关门), "alwaysOpen" (常开), "alwaysClose" (常闭)。
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
bool: 命令执行成功返回 True,失败返回 False。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
# 构建 API URL
|
|||
|
|
# 对于 DS-K1T673 系列,门编号通常为 1
|
|||
|
|
api_url = f"http://{device_ip}/ISAPI/AccessControl/RemoteControl/door/1"
|
|||
|
|
|
|||
|
|
# 构建 XML 请求体
|
|||
|
|
# xmlns 命名空间通常是必须的,version 可选
|
|||
|
|
xml_body = f"""
|
|||
|
|
<RemoteControlDoor version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">
|
|||
|
|
<cmd>{command}</cmd>
|
|||
|
|
</RemoteControlDoor>
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
headers = {
|
|||
|
|
"Content-Type": "application/xml"
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
# 发送 PUT 请求,必须使用 Digest 认证
|
|||
|
|
response = requests.put(
|
|||
|
|
api_url,
|
|||
|
|
auth=HTTPDigestAuth(user_name, password),
|
|||
|
|
data=xml_body,
|
|||
|
|
headers=headers,
|
|||
|
|
timeout=5
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 检查 HTTP 状态码
|
|||
|
|
if response.status_code == 200:
|
|||
|
|
# 解析返回的 XML 确认执行结果
|
|||
|
|
# 成功通常返回 <statusCode>1</statusCode> 和 <statusString>OK</statusString>
|
|||
|
|
print(f"[成功] 门禁响应: {response.text}")
|
|||
|
|
return True
|
|||
|
|
else:
|
|||
|
|
print(f"[失败] HTTP 错误码: {response.status_code}")
|
|||
|
|
print(f"[失败] 错误信息: {response.text}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
except requests.exceptions.RequestException as e:
|
|||
|
|
print(f"[错误] 连接异常: {e}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
# --- 主程序执行 ---
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
# 配置参数
|
|||
|
|
target_ip = "192.168.1.69"
|
|||
|
|
admin_user = "admin"
|
|||
|
|
admin_pass = "hzx12345"
|
|||
|
|
|
|||
|
|
print(f"正在尝试连接门禁 {target_ip} ...")
|
|||
|
|
|
|||
|
|
# 执行开门操作
|
|||
|
|
is_success = control_hikvision_door(target_ip, admin_user, admin_pass, "open")
|
|||
|
|
|
|||
|
|
if is_success:
|
|||
|
|
print("开门指令发送完毕。")
|
|||
|
|
else:
|
|||
|
|
print("开门指令发送失败,请检查网络或密码。")
|