用python来更改海康威视摄像头的OSD通道名称

# coding=utf-8
import os
import time
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
import xml.etree.ElementTree as ET

#和监控摄像头通讯需要一个双方认可的密钥,可以随机生成
def generate_key():
    # 生成一个16字节的随机字节数组,16字节对应128位
    random_bytes = os.urandom(16)
    # 将字节数组转换成十六进制字符串
    hex_key = random_bytes.hex()
    return hex_key


#格式数据,给摄像头输出
xml_data1 ="""
<?xml version: "1.0" encoding="utf-8"?>
<VideoOverlay>
    <normalizedScreenSize>
        <normalizedScreenWidth>704</normalizedScreenWidth>
        <normalizedScreenHeight>576</normalizedScreenHeight>
    </normalizedScreenSize>
    <attribute>
    <transparent>false</transparent>
    <flashing>false</flashing></attribute>
    <fontSize>adaptive</fontSize>
    <frontColorMode>auto</frontColorMode>
    <alignment>customize</alignment>
    <TextOverlayList>
        <TextOverlay>
            <id>1</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText>111</displayText></TextOverlay><TextOverlay>
            <id>2</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText>11</displayText></TextOverlay><TextOverlay>
            <id>3</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText/></TextOverlay><TextOverlay>
            <id>4</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText/></TextOverlay></TextOverlayList>
            <DateTimeOverlay><enabled>true</enabled>
            <positionY>544</positionY><positionX>0</positionX>
            <dateStyle>CHR-YYYY-MM-DD</dateStyle>
            <timeStyle>12hour</timeStyle>
            <displayWeek>true</displayWeek></DateTimeOverlay>
    <channelNameOverlay>
        <enabled>true</enabled>
        <positionY>48</positionY>
        <positionX>336</positionX>
        <videoFormat>PAL</videoFormat>
    </channelNameOverlay>
</VideoOverlay>
"""


def fun_GetOSD_Name(url):
    # 尝试使用Basic Auth登录
    session = requests.Session()
    session.auth = HTTPBasicAuth(USERNAME, PASSWORD)
    try:
        # 发送GET请求
        response = session.get(url)
        # 检查状态码,如果为401则尝试Digest Auth
        #print(f'response.status_code:{response.status_code}')
        if response.status_code == 401:
            session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
            response = session.get(url)
            #print(response.text)
            
            # 解析XML
            osd_config = ET.fromstring(response.text)
        elif response.status_code == 200:
            # 解析XML响应以获取OSD通道名称
            osd_config = ET.fromstring(response.text)
            #print("OSD Configuration:", osd_config)
        else:
            print("Failed to retrieve OSD configuration. Status code:", response.status_code)
        # 找到并打印摄像头的OSD-name元素的文本
        name_element = osd_config.find('{http://www.hikvision.com/ver20/XMLSchema}name')
        if name_element is not None:
            osd_name = name_element.text
            return osd_name
        else:
            print("Name element not found")
            return '没找到通道名称'
    except Exception as e:
        print("An error occurred:", e)

def fun_New_OSD_Name(url,xml_data):
    # 尝试使用Basic Auth登录
    session = requests.Session()
    session.auth = HTTPBasicAuth(USERNAME, PASSWORD)
    try:
        # 发送GET请求
        response = session.get(url)
        # 检查状态码,如果为401则尝试Digest Auth
        if response.status_code == 401:
            session.auth = HTTPDigestAuth(USERNAME, PASSWORD)

            # 发送PUT请求,更新OSD名称
            time.sleep(2)
            headers = {'Content-Type': 'application/xml'}
            response = session.put(url, data=xml_data2, headers=headers)
            # 检查响应状态码,确认更新是否成功
            if response.status_code == 200:
                print("\n OSD 通道名称更改成功!.")
            else:
                print(f"Failed to update OSD name. Status code: {response.status_code}")
        # 检查响应状态
        if response.status_code == 200:
            # 解析XML响应以获取OSD通道名称
            osd_config = response.text
            #print("OSD Configuration:", osd_config)
        else:
            print("Failed to retrieve OSD configuration. Status code:", response.status_code)
    except Exception as e:
        print("An error occurred:", e)



if __name__=='__main__':
    #207辅楼楼顶设备间2(外)
    # 摄像头的IP地址、用户名和密码
    HOST1=input('请输入ip地址前3位不要少写最后的【点】:默认:10.25.27.')
    if not HOST1:
        HOST1='10.25.27.'
        
    USERNAME = 'admin'
    PASSWORD = 'qlyy1234'
    #跳转1:
    while 1:
        HOST2 = input('\n请输入ip地址最后三位:\n\n')
        HOST=HOST1+HOST2
        asekey=generate_key()
        
        #url1:输出格式的地址;url2:输出OSD名字的地址,后边的密钥可以是任意值
        url1=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/overlays'
        url2=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/?security=1&iv={asekey}'
        #获取通道名称
        OldName=fun_GetOSD_Name(url2)
        print(f'{HOST:}当前通道名称:{OldName}')
        New_OSD_Name=input('\n请输入新的通道名称:\n\n')
        if not New_OSD_Name:
            New_OSD_Name=OldName
            
        # 构建XML数据,注意这里的XML数据格式应该符合Hikvision API的要求
        #OSD通道数据,给设想头设置
        xml_data2 = f"""
        <?xml version: "1.0" encoding="UTF-8"?><VideoInputChannel xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0">
        <id>1</id>
        <inputPort>1</inputPort>
        <name>{New_OSD_Name}</name>
        <videoFormat>PAL</videoFormat>
        </VideoInputChannel>
        """
        #执行摄像头通道名称更改
        fun_New_OSD_Name(url2,xml_data2)
        #获取修改后的通道名称
        NewName=fun_GetOSD_Name(url2)
        print(f'{HOST:}当前通道名称:{NewName}')
    

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菌王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值