海康威视摄像头批量更改源码

 

  1. 更改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


#格式数据,给摄像头输出


def fun_GetIP(url):
    # 尝试使用Digest Auth登录,不是Basic Auth
    session = requests.Session()
    session.auth = HTTPDigestAuth(USERNAME, PASSWORD)  # 确保USERNAME和PASSWORD已经被定义
    
    while True:
        try:
            # 发送GET请求
            response = session.get(url,timeout=5)
            
            # 检查响应状态码
            if response.status_code == 200:
                # 将HTML转化为ElementTree对象
                ip_config = ET.fromstring(response.text)  # 使用response.text
                # 将Element转换为字符串并打印
                #xml_str = ET.tostring(ip_config, encoding='unicode')
                #print(xml_str)
                # 提取命名空间
                # 注意:命名空间的格式应该是这样的:'{http://www.hikvision.com/ver20/XMLSchema}'
                ns = {'ns': 'http://www.hikvision.com/ver20/XMLSchema'}  # 注意这里命名空间的格式
                # 查找ipv4的ipaddress
                # 根据返回的XML结构,可能需要使用ip_config
                # 并且命名空间需要正确添加到'ipAddress'前面
                ip_address = ip_config.find('.//ns:ipAddress', ns).text
                
                return ip_address
            else:
                print("Request failed with status code:", response.status_code)
                return None
        except requests.exceptions.Timeout:
            print("Connection timed out. Do you want to retry?")
            choice = input("输入1重连,输入2退出: ")
            if choice != '1':
                print("Returning to main program.")
                return None
        except Exception as e:
            print("An error occurred:", e)
            return None

def fun_New_IPAddress(url,xml_data,rebootUrl):
    # 尝试使用Basic Auth登录
    session = requests.Session()
    session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
    try:
        # 发送GET请求
        response = session.get(url)
        # 发送PUT请求,更新IP地址
        time.sleep(2)
        headers = {'Content-Type': 'application/xml'}
        response = session.put(url, data=xml_data, headers=headers)
        # 检查响应状态码,确认更新是否成功
        if response.status_code == 200:
            print("\n IP更改成功!")
            response1=session.put(rebootUrl,data='', headers=headers)#重启设备
            print('重启设备------------------------------------------------')
        else:
            print(f"Failed to update OSD name. Status code: {response.status_code}")
        # 检查响应状态
        if response.status_code == 200:
            print('建立连接成功!')
        else:
            print("建立连接失败:", response.status_code)
    except Exception as e:
        print("An error occurred:", e)



if __name__=='__main__':
    #207辅楼楼顶设备间2(外)
    # 摄像头的IP地址、用户名和密码
    HOST1=input('请输入ip地址前6位不要少写最后的【点】:默认:10.25.')
    if not HOST1:
        HOST1='10.25.'
        
    USERNAME = 'admin'
    PASSWORD = 'qlyy1234'
    #跳转1:
    while 1:
        HOST2 = input('\n请输入原始ip地址最后6位(例如:27.21):\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}'
        url3=f'http://{HOST}/ISAPI/System/Network/interfaces/1'#更改ip地址
        url4=f'http://{HOST}/ISAPI/System/Network/interfaces?security=1&iv={asekey}'#获取ip地址
        rebootUrl=f'http://{HOST}/ISAPI/System/reboot'
        #获取通道名称
        OldIPAddress=fun_GetIP(url4)
        print(f'当前IP地址:{OldIPAddress}')

        HOST2=input('\n请输入新的地址后6位(例如:31.21)【q:退出】:\n\n')
        if not HOST2:
            New_IPAddress=OldIPAddress
        elif HOST2 == 'q':
            exit
        else:
            New_IPAddress=HOST1+HOST2
            
        xml_data3 = f"""
            <?xml version: "1.0" encoding="UTF-8"?>
                <NetworkInterface>
                    <id>1</id>
                    <IPAddress>
                        <ipVersion>dual</ipVersion>
                        <addressingType>static</addressingType>
                        <ipAddress>{New_IPAddress}</ipAddress>
                        <subnetMask>255.255.224.0</subnetMask>
                        <ipV6AddressingType>ra</ipV6AddressingType>
                        <DefaultGateway>
                            <ipAddress>10.25.27.254</ipAddress>
                        </DefaultGateway>
                        <PrimaryDNS>
                            <ipAddress>114.114.114.114</ipAddress>
                        </PrimaryDNS>
                        <SecondaryDNS>
                            <ipAddress>8.8.8.8</ipAddress>
                        </SecondaryDNS></IPAddress>
                </NetworkInterface>
        """
        #执行摄像头通道名称更改
        fun_New_IPAddress(url3,xml_data3,rebootUrl)

        
        
    

海康威视更改ip

# 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


#格式数据,给摄像头输出


def fun_GetIP(url):
    # 尝试使用Digest Auth登录,不是Basic Auth
    session = requests.Session()
    session.auth = HTTPDigestAuth(USERNAME, PASSWORD)  # 确保USERNAME和PASSWORD已经被定义
    
    while True:
        try:
            # 发送GET请求
            response = session.get(url,timeout=5)
            
            # 检查响应状态码
            if response.status_code == 200:
                # 将HTML转化为ElementTree对象
                ip_config = ET.fromstring(response.text)  # 使用response.text
                # 将Element转换为字符串并打印
                #xml_str = ET.tostring(ip_config, encoding='unicode')
                #print(xml_str)
                # 提取命名空间
                # 注意:命名空间的格式应该是这样的:'{http://www.hikvision.com/ver20/XMLSchema}'
                ns = {'ns': 'http://www.hikvision.com/ver20/XMLSchema'}  # 注意这里命名空间的格式
                # 查找ipv4的ipaddress
                # 根据返回的XML结构,可能需要使用ip_config
                # 并且命名空间需要正确添加到'ipAddress'前面
                ip_address = ip_config.find('.//ns:ipAddress', ns).text
                
                return ip_address
            else:
                print("Request failed with status code:", response.status_code)
                return None
        except requests.exceptions.Timeout:
            print("Connection timed out. Do you want to retry?")
            choice = input("输入1重连,输入2退出: ")
            if choice != '1':
                print("Returning to main program.")
                return None
        except Exception as e:
            print("An error occurred:", e)
            return None

def fun_New_IPAddress(url,xml_data,rebootUrl):
    # 尝试使用Basic Auth登录
    session = requests.Session()
    session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
    try:
        # 发送GET请求
        response = session.get(url)
        # 发送PUT请求,更新IP地址
        time.sleep(2)
        headers = {'Content-Type': 'application/xml'}
        response = session.put(url, data=xml_data, headers=headers)
        # 检查响应状态码,确认更新是否成功
        if response.status_code == 200:
            print("\n IP更改成功!")
            response1=session.put(rebootUrl,data='', headers=headers)#重启设备
            print('重启设备------------------------------------------------')
        else:
            print(f"Failed to update OSD name. Status code: {response.status_code}")
        # 检查响应状态
        if response.status_code == 200:
            print('建立连接成功!')
        else:
            print("建立连接失败:", response.status_code)
    except Exception as e:
        print("An error occurred:", e)



if __name__=='__main__':
    #207辅楼楼顶设备间2(外)
    # 摄像头的IP地址、用户名和密码
    HOST1=input('请输入ip地址前6位不要少写最后的【点】:默认:10.25.')
    if not HOST1:
        HOST1='10.25.'
        
    USERNAME = 'admin'
    PASSWORD = 'qlyy1234'
    #跳转1:
    while 1:
        HOST2 = input('\n请输入原始ip地址最后6位(例如:27.21):\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}'
        url3=f'http://{HOST}/ISAPI/System/Network/interfaces/1'#更改ip地址
        url4=f'http://{HOST}/ISAPI/System/Network/interfaces?security=1&iv={asekey}'#获取ip地址
        rebootUrl=f'http://{HOST}/ISAPI/System/reboot'
        #获取通道名称
        OldIPAddress=fun_GetIP(url4)
        print(f'当前IP地址:{OldIPAddress}')

        HOST2=input('\n请输入新的地址后6位(例如:31.21)【q:退出】:\n\n')
        if not HOST2:
            New_IPAddress=OldIPAddress
        elif HOST2 == 'q':
            exit
        else:
            New_IPAddress=HOST1+HOST2
            
        xml_data3 = f"""
            <?xml version: "1.0" encoding="UTF-8"?>
                <NetworkInterface>
                    <id>1</id>
                    <IPAddress>
                        <ipVersion>dual</ipVersion>
                        <addressingType>static</addressingType>
                        <ipAddress>{New_IPAddress}</ipAddress>
                        <subnetMask>255.255.224.0</subnetMask>
                        <ipV6AddressingType>ra</ipV6AddressingType>
                        <DefaultGateway>
                            <ipAddress>10.25.27.254</ipAddress>
                        </DefaultGateway>
                        <PrimaryDNS>
                            <ipAddress>114.114.114.114</ipAddress>
                        </PrimaryDNS>
                        <SecondaryDNS>
                            <ipAddress>8.8.8.8</ipAddress>
                        </SecondaryDNS></IPAddress>
                </NetworkInterface>
        """
        #执行摄像头IPaddress
        fun_New_IPAddress(url3,xml_data3,rebootUrl)

        
        
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

菌王

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

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

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

打赏作者

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

抵扣说明:

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

余额充值