No relevant resource is found in the selected language.

This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies. Read our privacy policy>Search

Reminder

To have a better experience, please upgrade your IE browser.

upgrade

CX11x, CX31x, CX710 (Earlier Than V6.03), and CX91x Series Switch Modules V100R001C10 Configuration Guide 12

The documents describe the configuration of various services supported by the CX11x&CX31x&CX91x series switch modules The description covers configuration examples and function configurations.
Rate and give feedback:
Huawei uses machine translation combined with human proofreading to translate this document to different languages in order to help you better understand the content of this document. Note: Even the most advanced machine translation cannot match the quality of professional translators. Huawei shall not bear any responsibility for translation accuracy and it is recommended that you refer to the English document (a link for which has been provided).
Principles

Principles

This section describes how ZTP is implemented.

Implementation

Automatic Deployment and Typical Networking

When the configuration recovery mode is asynchronous, after an unconfigured device is powered on, the device automatically starts the ZTP process. The device attempts to complete automatic deployment using DHCP. For the detailed process, see ZTP Process.

Figure 1-1 shows the typical networking of automatic deployment through DHCP.

Figure 1-1 Networking diagram of automatic deployment
  • DHCP server: assigns a temporary management IP address, the default gateway, the IP addresses of the DNS server and the intermediate file server to the device running ZTP. An intermediate file server can be a TFTP, an FTP, SFTP, or HTTP server.

  • DHCP relay agent: relays packets exchanged between the device and DHCP server located on different network segments.

  • Intermediate file server: stores the intermediate file required by the device running ZTP. The intermediate file can be an .ini file or a Python script. By parsing the intermediate file, the device can obtain information about the version files and the IP address of the version file server.

  • Version file server: stores the version files to be loaded to unconfigured devices, including system software, configuration files, and patch files. The version file server and the intermediate file server can be deployed on the same server, which can be a TFTP, an FTP, SFTP, or HTTP server.

  • DNS server: provides mappings between the domain names and IP addresses, and resolves the IP address of the file server for the device running ZTP. Based on the resolved IP address, the device can download the requested files.

ZTP Process
Figure 1-2 shows the ZTP flowchart.
Figure 1-2 ZTP flowchart
The ZTP process goes through six stages:
  1. The device is powered on and starts.

    If a configuration file is available, the device starts with the configuration file. If no configuration file is available, the device automatically starts the ZTP process.

    If you use a console port to log in when the device is powered on, you can choose whether to terminate the ZTP process as prompted. If you choose to terminate the ZTP process, the device starts with zero configuration.

  2. The device obtains DHCP information.

    The device starts automatic deployment through DHCP. In DHCP mode, the device broadcasts DHCP Request packets on ports in the following sequence: management port -> high-bandwidth Ethernet port -> low-bandwidth Ethernet port. After receiving the DHCP Request packet, the DHCP server sends a DHCP Reply packet to the device. Options in the packet contain the requested information, including the IP address of the device, default gateway, IP address of the intermediate file server, and name of the intermediate file.

  3. The device obtains the intermediate file and version files.

    According to the information carried in the DHCP Reply packet, the device obtains the intermediate file and then downloads the version files from the version file server.

    If the intermediate file is an .ini file, the device downloads the version files based on the IP address and version file names contained in the intermediate file. If the intermediate file is a Python script, the device automatically runs the script to download the version files.

  4. The device restarts.

    The device automatically sets the version files downloaded from the server as the next startup files. After that, the device restarts, and automatic deployment is complete.

Format of The Intermediate File

The device supports an .ini file or a Python script as an intermediate file. You can choose a file type as required.

INI File

An .ini file can be used as an intermediate file to store device and version file information.

The .ini file has the name extension .ini. The file format is as follows:
NOTE:

If the device implements automatic deployment through DHCP, a user-defined file name can be used.

;BEGIN DC
[GLOBAL CONFIG]
FILESERVER=ftp://ftpuser:Pwd123456@10.1.3.2

[DEVICEn DESCRIPTION]
ESN=210235527210D4000028
MAC=e468-a356-0cb0
DEVICETYPE=DEFAULT
SYSTEM-SOFTWARE=V100R003C00.cc
SYSTEM-CONFIG=vrpcfg.cfg
SYSTEM-PAT=DCV100R003SPH001.pat
;END DC
Table 1-10 Fields in the .ini file

Field

Mandatory or Optional

Description

;BEGIN DC

Mandatory

It is the start flag of the file and cannot be modified.

[GLOBAL CONFIG]

Mandatory

It is the start flag of the global configuration and cannot be modified.

FILESERVER

This field is mandatory when the device implements automatic deployment through DHCP.

If automatic deployment is performed through DHCP, this field specifies the server path where the device can obtain version files. The version file server can be a TFTP, an FTP, SFTP, or HTTP server. The format of this field depends on the server type and can be any of the following:
  • tftp://hostname/path

  • ftp://[username[:password]@]hostname[:port]/path

  • sftp://[username[:password]@]hostname[:port]/path

  • http://hostname[:port]/path

The parameters username, password, and port are optional. path specifies the directory where the version file is saved on the file server.

[DEVICEn DESCRIPTION]

Mandatory

It is the start flag of the file description. n is a device number and starts from 0.

ESN

Optional

It specifies the equipment serial number (ESN) of a device. If this field is set to DEFAULT, the ESN of the device is not checked. If this field is set to another value, the ESN of the device must be the same as the configured value.

NOTE:

The default value of this field is DEFAULT. If this field does not exist or is empty, the default value is used.

MAC

Optional

It specifies the MAC address of a device, in the XXXX-XXXX-XXXX format. X is a hexadecimal number. If this field is set to DEFAULT, the device MAC address is not checked. If this field is set to another value, the device MAC address must be the same as the configured value.

The device ESN is checked ahead of MAC address.

NOTE:

The default value of this field is DEFAULT. If this field does not exist or is empty, the default value is used.

DEVICETYPE

Optional

It specifies the device type. The value of this field can be CX110 or CX31x&CX91x. If this field is set to DEFAULT, the device type is not checked.

NOTE:

The default value of this field is DEFAULT. If this field does not exist or is empty, the default value is used.

SYSTEM-SOFTWARE

Optional

It specifies a system software name, with an extension .cc.

SYSTEM-CONFIG

Optional

It specifies a configuration file name, with an extension .cfg, .zip, or .dat.

SYSTEM-PAT

Optional

It specifies a patch file name, with an extension .pat.

;END DC

Mandatory

It is the end flag of the file and cannot be modified.

Python Script

A Python script can be used as an intermediate file. The device runs the Python script to download version files.

The file name extension of the Python script is .py. Example of Python Script shows an example of a Python script. Python Script Descriptions describes contents in the Python script.
NOTE:

If the device implements automatic deployment through DHCP, a user-defined file name can be used.

Example of Python Script
#md5sum="5bb3da014aa88ba8111c2f1191373716"
#!/usr/bin/env python
#
# Copyright (C) Huawei Technologies Co., Ltd. 2008-2013. All rights reserved.
# ----------------------------------------------------------------------------------------------------------------------
# History:
# Date                Author                      Modification
# 20130629            Author                      created file.
# ----------------------------------------------------------------------------------------------------------------------

"""
Zero Touch Provisioning (ZTP) enables devices to automatically load version files including system software,
patch files, configuration files when the device starts up, the devices to be configured must be new devices
or have no configuration files.

This is a sample of Zero Touch Provisioning user script. You can customize it to meet the requirements of
your network environment.
"""

import httplib
import urllib
import string
import re
import xml.etree.ElementTree as etree
import os
import stat
import logging
import traceback
import hashlib

from urlparse import urlparse
from urlparse import urlunparse
from time import sleep

# error code
OK          = 0
ERR         = 1

# File server in which stores the necessary system software, configuration and patch files:
#   1) Specify the file server which supports the following format.
#      tftp://hostname
#      ftp://[username[:password]@]hostname[:port]
#      sftp://[username[:password]@]hostname[:port]
#      http://hostname[:port]
#   2) Do not add a trailing slash at the end of file server path.
FILE_SERVER         = 'ftp://ftpuser:Pwd123@10.1.3.2'

# Remote file paths:
#   1) The path may include directory name and file name.
#   2) If file name is not specified, indicate the procedure can be skipped.
# File paths of system software on file server, filename extension is '.cc'.
REMOTE_PATH_IMAGE   = {
    'CX110'    :   '/image/CX110-Switch-V103.cc',
    'CX310'    :   '/image/CX310-Switch-V103.cc',
}
# File path of configuration file on file server, filename extension is '.cfg', '.zip' or '.dat'.
REMOTE_PATH_CONFIG  = '/conf_%s.cfg'
# File path of patch file on file server, filename extension is '.pat'
REMOTE_PATH_PATCH   = '/patch/patch.pat'
# File path of stack member ID file on file server, filename extension is '.txt'
REMOTE_PATH_MEMID   = '/stack/stack_member.txt'
# File path of md5 file, contains md5 value of image / patch / memid file, file extension if '.txt'
REMOTE_PATH_MD5     = '/md5.txt'


# Max times to retry get startup when no query result
GET_STARTUP_INTERVAL        = 15    # seconds
MAX_TIMES_GET_STARTUP       = 120   # Max times to retry

# Max times to retry when download file faild
MAX_TIMES_RETRY_DOWNLOAD    = 3


class OPSConnection(object):
    """Make an OPS connection instance."""

    def __init__(self, host, port = 80):
        self.host = host
        self.port = port
        self.headers = {
            "Content-type": "application/xml",
            "Accept":       "application/xml"
            }

        self.conn = httplib.HTTPConnection(self.host, self.port)

    def close(self):
        """Close the connection"""
        self.conn.close()

    def create(self, uri, req_data):
        """Create a resource on the server"""
        ret = self._rest_call("POST", uri, req_data)
        return ret

    def delete(self, uri, req_data):
        """Delete a resource on the server"""
        ret = self._rest_call("DELETE", uri, req_data)
        return ret

    def get(self, uri, req_data = None):
        """Retrieve a resource from the server"""
        ret = self._rest_call("GET", uri, req_data)
        return ret

    def set(self, uri, req_data):
        """Update a resource on the server"""
        ret = self._rest_call("PUT", uri, req_data)
        return ret

    def _rest_call(self, method, uri, req_data):
        """REST call"""
        if req_data == None:
            body = ""
        else:
            body = req_data

        logging.debug('HTTP request: %s %s HTTP/1.1', method, uri)
        self.conn.request(method, uri, body, self.headers)
        response = self.conn.getresponse()
        ret = (response.status, response.reason, response.read())
        if response.status != httplib.OK:
            logging.debug('%s', body)
        logging.debug('HTTP response: HTTP/1.1 %s %s\n%s', ret[0], ret[1], ret[2])
        return ret

class OPIExecError(Exception):
    """OPI executes error."""
    pass

class ZTPErr(Exception):
    """ZTP error."""
    pass


def get_addr_by_hostname(ops_conn, host, addr_type = '1'):
    """Translate a host name to IPv4 address format. The IPv4 address is returned as a string."""
    logging.info("Get IP address by host name...")
    uri = "/dns/dnsNameResolution"
    root_elem = etree.Element('dnsNameResolution')
    etree.SubElement(root_elem, 'host').text = host
    etree.SubElement(root_elem, 'addrType').text = addr_type
    req_data = etree.tostring(root_elem, "UTF-8")
    ret, _, rsp_data = ops_conn.get(uri, req_data)
    if ret != httplib.OK:
        raise OPIExecError('Failed to get address by host name')

    root_elem = etree.fromstring(rsp_data)
    namespaces = {'vrp' : 'http://www.huawei.com/netconf/vrp'}
    uri = 'data' + uri.replace('/', '/vrp:') + '/vrp:'
    elem = root_elem.find(uri + "ipv4Addr", namespaces)
    if elem is None:
        raise OPIExecError('Failed to get IP address by host name')

    return elem.text

def _http_download_file(ops_conn, url, local_path):
    """Download file using HTTP."""
    logging.info('HTTP download "%s" to "%s".', url, local_path)

    url_tuple = urlparse(url)
    if not re.match(r"\d+\.\d+\.\d+\.\d+", url_tuple.hostname):
        netloc = get_addr_by_hostname(ops_conn, url_tuple.hostname)
        if url_tuple.port:
            netloc += ':' + str(url_tuple.port)
        url = urlunparse((url_tuple.scheme, netloc, url_tuple.path, url_tuple.params, url_tuple.query,
                          url_tuple.fragment))

    ret = OK
    opener = urllib.URLopener()
    try:
        dst_file_path = "%s/%s" % (os.getcwd(), os.path.basename(url))
        dst_file_path = os.path.abspath(dst_file_path)
        logging.info('HTTP download destination file=%s.', dst_file_path)
        opener.retrieve(url, dst_file_path)
        os.chmod(dst_file_path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
    except (KeyboardInterrupt, Exception), reason:
        if os.path.exists(dst_file_path):
            os.remove(dst_file_path)    # Remove incomplete file
        logging.error(reason)
        print('Error: Failed to download file "%s" using HTTP' % os.path.basename(url))
        ret = ERR

    return ret

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : ftp_download_file
# Date Created    : 2013-7-6
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def _ftp_download_file(ops_conn, url, local_path):
    """Download file using FTP."""
    logging.info('FTP download "%s" to "%s".', url, local_path)
    uri = "/ftpc/ftpcTransferFiles/ftpcTransferFile"
    str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<ftpcTransferFile>
    <serverIpv4Address>$serverIp</serverIpv4Address>
    <commandType>get</commandType>
    <userName>$username</userName>
    <password>$password</password>
    <localFileName>$localPath</localFileName>
    <remoteFileName>$remotePath</remoteFileName>
</ftpcTransferFile>
''')
    url_tuple = urlparse(url)
    if re.match(r"\d+\.\d+\.\d+\.\d+", url_tuple.hostname):
        server_ip = url_tuple.hostname
    else:
        server_ip = get_addr_by_hostname(ops_conn, url_tuple.hostname)
    req_data = str_temp.substitute(serverIp = server_ip, username = url_tuple.username, password = url_tuple.password,
                                   remotePath = url_tuple.path[1:], localPath = local_path)
    ret, _, _ = ops_conn.create(uri, req_data)
    if ret != httplib.OK:
        print('Failed to download file "%s" using FTP' % os.path.basename(local_path))
        return ERR

    return OK

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : _del_rsa_peer_key
# Date Created    : 2013-8-1
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def _del_rsa_peer_key(ops_conn, key_name):
    """Delete RSA peer key configuration"""
    logging.debug("Delete RSA peer key %s", key_name)
    uri = "/rsa/rsaPeerKeys/rsaPeerKey"
    root_elem = etree.Element('rsaPeerKey')
    etree.SubElement(root_elem, 'keyName').text = key_name
    req_data = etree.tostring(root_elem, "UTF-8")
    try:
        ret, _, _ = ops_conn.delete(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError('Failed to delete RSA peer key')

    except Exception, reason:
        logging.debug(reason)

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : _del_sshc_rsa_key
# Date Created    : 2013-8-1
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def _del_sshc_rsa_key(ops_conn, server_name, key_type = 'RSA'):
    """Delete SSH client RSA key configuration"""
    logging.debug("Delete SSH client RSA key for %s", server_name)
    uri = "/sshc/sshCliKeyCfgs/sshCliKeyCfg"
    root_elem = etree.Element('sshCliKeyCfg')
    etree.SubElement(root_elem, 'serverName').text = server_name
    etree.SubElement(root_elem, 'pubKeyType').text = key_type
    req_data = etree.tostring(root_elem, "UTF-8")
    try:
        ret, _, _ = ops_conn.delete(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError('Failed to delete SSH client RSA key')

    except Exception, reason:
        logging.debug(reason)

    _del_rsa_peer_key(ops_conn, server_name)

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : _set_sshc_first_time
# Date Created    : 2013-8-1
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def _set_sshc_first_time(ops_conn, switch):
    """Set SSH client attribute of authenticating user for the first time access"""
    if switch not in ['Enable', 'Disable']:
        return ERR

    logging.debug('Set SSH client first-time enable switch = %s', switch)
    uri = "/sshc/sshClient"
    str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<sshClient>
    <firstTimeEnable>$enable</firstTimeEnable>
</sshClient>
''')
    req_data = str_temp.substitute(enable = switch)
    ret, _, _ = ops_conn.set(uri, req_data)
    if ret != httplib.OK:
        if switch == 'Enable':
            raise OPIExecError('Failed to enable SSH client first-time')
        else:
            raise OPIExecError('Failed to disable SSH client first-time')

    return OK

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : sftp_download_file
# Date Created    : 2013-7-6
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def _sftp_download_file(ops_conn, url, local_path):
    """Download file using SFTP."""
    _set_sshc_first_time(ops_conn, 'Enable')

    logging.debug('SFTP download "%s" to "%s".', url, local_path)
    uri = "/sshc/sshcConnects/sshcConnect"
    str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<sshcConnect>
    <HostAddrIPv4>$serverIp</HostAddrIPv4>
    <commandType>get</commandType>
    <userName>$username</userName>
    <password>$password</password>
    <localFileName>$localPath</localFileName>
    <remoteFileName>$remotePath</remoteFileName>
    <identityKey>ssh-rsa</identityKey>
    <transferType>SFTP</transferType>
</sshcConnect>
''')
    url_tuple = urlparse(url)
    if re.match(r"\d+\.\d+\.\d+\.\d+", url_tuple.hostname):
        server_ip = url_tuple.hostname
    else:
        server_ip = get_addr_by_hostname(ops_conn, url_tuple.hostname)
    req_data = str_temp.substitute(serverIp = server_ip, username = url_tuple.username, password = url_tuple.password,
                                   remotePath = url_tuple.path[1:], localPath = local_path)
    ret, _, _ = ops_conn.create(uri, req_data)
    if ret != httplib.OK:
        print('Failed to download file "%s" using SFTP' % os.path.basename(local_path))
        ret = ERR
    else:
        ret = OK

    _del_sshc_rsa_key(ops_conn, server_ip)
    _set_sshc_first_time(ops_conn, 'Disable')
    return ret

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : tftp_download_file
# Date Created    : 2013-7-6
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def _tftp_download_file(ops_conn, url, local_path):
    """Download file using TFTP."""
    logging.debug('TFTP download "%s" to "%s".', url, local_path)
    uri = "/tftpc/tftpcTransferFiles/tftpcTransferFile"
    str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<tftpcTransferFile>
    <serverIpv4Address>$serverIp</serverIpv4Address>
    <commandType>get_cmd</commandType>
    <localFileName>$localPath</localFileName>
    <remoteFileName>$remotePath</remoteFileName>
</tftpcTransferFile>
''')
    url_tuple = urlparse(url)
    if re.match(r"\d+\.\d+\.\d+\.\d+", url_tuple.hostname):
        server_ip = url_tuple.hostname
    else:
        server_ip = get_addr_by_hostname(ops_conn, url_tuple.hostname)
    req_data = str_temp.substitute(serverIp = server_ip, remotePath = url_tuple.path[1:], localPath = local_path)
    ret, _, _ = ops_conn.create(uri, req_data)
    if ret != httplib.OK:
        print('Failed to download file "%s" using TFTP' % os.path.basename(local_path))
        return ERR

    return OK

def _usb_download_file(ops_conn, url, local_path):
    """Download file using usb"""
    logging.info('USB download "%s" to "%s".', url, local_path)

    url_tuple = urlparse(url, allow_fragments=False)
    src_path = url_tuple.path[1:]
    try:
        copy_file(ops_conn, src_path, local_path)
    except:
        print('Failed to download file "%s" using USB' % os.path.basename(local_path))
        return ERR
    return OK

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : download_file
# Date Created    : 2013-7-6
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def download_file(ops_conn, url, local_path, retry_times = 0):
    """Download file, support TFTP, FTP, SFTP and HTTP.

    tftp://hostname/path
    ftp://[username[:password]@]hostname[:port]/path
    sftp://[username[:password]@]hostname[:port]/path
    http://hostname[:port]/path

    Args:
      ops_conn: OPS connection instance
      url: URL of remote file
      local_path: local path to put the file

    Returns:
        A integer of return code
    """
    print("Info: Download %s to %s" % (url, local_path))
    url_tuple = urlparse(url)
    func_dict = {'tftp': _tftp_download_file,
                 'ftp':  _ftp_download_file,
                 'sftp': _sftp_download_file,
                 'http': _http_download_file,
                 'file': _usb_download_file}
    scheme = url_tuple.scheme
    if scheme not in func_dict.keys():
        raise ZTPErr('Unknown file transfer scheme %s' % scheme)

    ret = OK
    cnt = 0
    while (cnt < 1 + retry_times):
        if cnt:
            print('Retry downloading...')
            logging.info('Retry downloading...')
        ret = func_dict[scheme](ops_conn, url, local_path)
        if ret is OK:
            break
        cnt += 1

    if ret is not OK:
        raise ZTPErr('Failed to download file "%s"' % os.path.basename(url))

    return OK


class StartupInfo(object):
    """Startup configuration information

    image: startup system software
    config: startup saved-configuration file
    patch: startup patch package
    """
    def __init__(self, image = None, config = None, patch = None):
        self.image = image
        self.config = config
        self.patch = patch

class Startup(object):
    """Startup configuration information

    current: current startup configuration
    next: current next startup configuration
    """
    def __init__(self, ops_conn):
        self.ops_conn = ops_conn
        self.current, self.next = self._get_startup_info()

    def _get_startup_info(self):
        """Get the startup information."""
        logging.info("Get the startup information...")
        uri = "/cfg/startupInfos/startupInfo"
        req_'<?xml version="1.0" encoding="UTF-8"?>
<startupInfo>
    <position/>
    <configedSysSoft/>
    <curSysSoft/>
    <nextSysSoft/>
    <curStartupFile/>
    <nextStartupFile/>
    <curPatchFile/>
    <nextPatchFile/>
</startupInfo>'''

        cnt = 0
        while (cnt < MAX_TIMES_GET_STARTUP):
            ret, _, rsp_data = self.ops_conn.get(uri, req_data)
            if ret != httplib.OK or rsp_data is '':
                cnt += 1
                logging.info('Failed to get the startup information')
                continue

            root_elem = etree.fromstring(rsp_data)
            namespaces = {'vrp' : 'http://www.huawei.com/netconf/vrp'}
            mpath = 'data' + uri.replace('/', '/vrp:')  # match path
            nslen = len(namespaces['vrp'])
            elem = root_elem.find(mpath, namespaces)
            if elem is not None:
                break
            logging.debug('No query result while getting startup info')
            sleep(GET_STARTUP_INTERVAL)     # sleep to wait for system ready when no query result
            cnt += 1

        if elem is None:
            raise OPIExecError('Failed to get the startup information')

        current = StartupInfo()     # current startup info
        curnext = StartupInfo()     # next startup info
        for child in elem:
            tag = child.tag[nslen + 2:]       # skip the namespace, '{namespace}text'
            if tag == 'curSysSoft':
                current.image = child.text
            elif tag == 'nextSysSoft':
                curnext.image = child.text
            elif tag == 'curStartupFile' and child.text != 'NULL':
                current.config = child.text
            elif tag == 'nextStartupFile' and child.text != 'NULL':
                curnext.config = child.text
            elif tag == 'curPatchFile' and child.text != 'NULL':
                current.patch = child.text
            elif tag == 'nextPatchFile' and child.text != 'NULL':
                curnext.patch = child.text
            else:
                continue

        return current, curnext

    def _set_startup_image_file(self, file_path):
        """Set the next startup system software"""
        logging.info("Set the next startup system software to %s...", file_path)
        uri = "/sum/startupbymode"
        str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<startupbymode>
    <softwareName>$fileName</softwareName>
    <mode>STARTUP_MODE_ALL</mode>
</startupbymode>
''')
        req_data = str_temp.substitute(fileName = file_path)
        # it is a action operation, so use create for HTTP POST
        ret, _, _ = self.ops_conn.create(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError("Failed to set startup system software")

    def _set_startup_config_file(self, file_path):
        """Set the next startup saved-configuration file"""
        logging.info("Set the next startup saved-configuration file to %s...", file_path)
        uri = "/cfg/setStartup"
        str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<setStartup>
    <fileName>$fileName</fileName>
</setStartup>
''')
        req_data = str_temp.substitute(fileName = file_path)
        # it is a action operation, so use create for HTTP POST
        ret, _, _ = self.ops_conn.create(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError("Failed to set startup configuration file")

    def _del_startup_config_file(self):
        """Delete startup config file"""
        logging.info("Delete the next startup config file...")
        uri = "/cfg/deleteStartup"
        req_data = '''<?xml version="1.0" encoding="UTF-8"?>
<deleteStartup>
</deleteStartup>
'''
        # it is a action operation, so use create for HTTP POST
        ret, _, _ = self.ops_conn.create(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError("Failed to delete startup configuration file")

    def _set_startup_patch_file(self, file_path):
        """Set the next startup patch file"""
        logging.info("Set the next startup patch file to %s...", file_path)
        uri = "/patch/startup"
        str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<startup>
    <packageName>$fileName</packageName>
</startup>
''')
        req_data = str_temp.substitute(fileName = file_path)
        # it is a action operation, so use create for HTTP POST
        ret, _, _ = self.ops_conn.create(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError("Failed to set startup patch file")

    def _get_cur_stack_member_id(self):
        """rest api: Get current stack member id"""

        logging.info("Get current stack member ID...")
        uri = "/stack/stackMemberInfos/stackMemberInfo"
        req_data =  \
            '''<?xml version="1.0" encoding="UTF-8"?>
            <stackMemberInfo>
                    <memberID></memberID>
                </stackMemberInfo>
            '''
        ret, _, rsp_data = self.ops_conn.get(uri, req_data)
        if ret != httplib.OK or rsp_data is '':
            raise OPIExecError('Failed to get current stack member id, rsp not ok')

        root_elem = etree.fromstring(rsp_data)
        namespaces = {'vrp' : 'http://www.huawei.com/netconf/vrp'}
        uri = 'data' + uri.replace('/', '/vrp:') + '/vrp:'
        elem = root_elem.find(uri + "memberID", namespaces)
        if elem is None:
            raise OPIExecError('Failed to get the current stack member id for no "memberID" element')

        return elem.text

    def _set_stack_member_id(self, file_path, esn):
        """Set the next stack member ID"""

        def get_stackid_from_file(fname, esn):
            """parse esn_id.txt file and get stack id according to esn num
            format of esn_stackid file is like below:

            sn              Irf group              Irf number
            Sdddg              100                         1
            Sddde              100                         2
            """
            # fname must exist, guaranteed by caller
            fname = os.path.basename(fname)
            with open(fname, 'rb') as item:
                for line in item:
                    token = line.strip('[\r\n]')
                    token = token.split()
                    if token[0] == esn:
                        return token[2]
            return None

        logging.info('Set the next stack member ID, filename %s', file_path)
        uri = "/stack/stackMemberInfos/stackMemberInfo"
        str_temp = string.Template(
            '''<?xml version="1.0" encoding="UTF-8"?>
                <stackMemberInfo>
                    <memberID>$curmemberid</memberID>
                    <nextMemberID>$memberid</nextMemberID>
                </stackMemberInfo>
            ''')

        cur_memid = self._get_cur_stack_member_id()
        next_memid = get_stackid_from_file(file_path, esn)
        if not next_memid:
            logging.debug('Failed to get stack id from %s, esn %s', file_path, esn)
            return

        req_data = str_temp.substitute(curmemberid = cur_memid, memberid = next_memid)
        ret, _, _ = self.ops_conn.set(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError('Failed to set stack id {}'.format(next_memid))

        return OK

    def _reset_stack_member_id(self):
        """rest api: reset stack member id"""

        logging.info('Reset the next stack member ID')
        uri = "/stack/stackMemberInfos/stackMemberInfo"
        req_data = \
            '''<?xml version="1.0" encoding="UTF-8"?>
                <stackMemberInfo>
                    <memberID>1</memberID>
                    <nextMemberID>1</nextMemberID>
                </stackMemberInfo>
            '''

        ret, _, _ = self.ops_conn.set(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError('Failed to reset stack id ')

        return OK

    def _reset_startup_patch_file(self):
        """Rest patch file for system to startup"""
        logging.info("Reset the next startup patch file...")
        uri = "/patch/resetpatch"
        req_data = '''<?xml version="1.0" encoding="UTF-8"?>
<resetpatch>
</resetpatch>
'''
        # it is a action operation, so use create for HTTP POST
        ret, _, _ = self.ops_conn.create(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError('Failed to reset patch')

    def reset_startup_info(self, slave):
        """Reset startup info and delete the downloaded files"""
        logging.info("Reset the next startup information...")
        _, configured = self._get_startup_info()

        # 1. Reset next startup config file and delete it
        try:
            if configured.config != self.next.config:
                if self.next.config is None:
                    self._del_startup_config_file()
                else:
                    self._set_startup_config_file(self.next.config)
                    if configured.config is not None:
                        del_file_all(self.ops_conn, configured.config, slave)

        except Exception, reason:
            logging.error(reason)

        # 2. Reset next startup patch file
        try:
            if configured.patch != self.next.patch:
                if self.next.patch is None:
                    self._reset_startup_patch_file()
                else:
                    self._set_startup_patch_file(self.next.patch)

                if configured.patch is not None:
                    del_file_all(self.ops_conn, configured.patch, slave)
        except Exception, reason:
            logging.error(reason)

        # 3. Reset next startup system software and delete it
        try:
            if configured.image != self.next.image:
                self._set_startup_image_file(self.next.image)
                del_file_all(self.ops_conn, configured.image, slave)
        except Exception, reason:
            logging.error(reason)

        # 4. reset stack member id
        try:
            self._reset_stack_member_id()
        except Exception, reason:
            logging.error(reason)

    def set_startup_info(self, image_file, config_file, patch_file, memid_file, slave, esn_str):
        """Set the next startup information."""
        logging.info("Set the next startup information...")
        # 1. Set next startup system software
        if image_file is not None:
            try:
                self._set_startup_image_file(image_file)
            except Exception, reason:
                logging.debug(reason)
                del_file_all(self.ops_conn, image_file, slave)
                self.reset_startup_info(slave)
                raise

        # 2. Set next startup config file
        if config_file is not None:
            try:
                self._set_startup_config_file(config_file)
            except Exception, reason:
                logging.debug(reason)
                del_file_all(self.ops_conn, config_file, slave)
                self.reset_startup_info(slave)
                raise

        # 3. Set next startup patch file
        if patch_file is not None:
            try:
                self._set_startup_patch_file(patch_file)
            except Exception, reason:
                logging.debug(reason)
                del_file_all(self.ops_conn, patch_file, slave)
                self.reset_startup_info(slave)
                raise

        # 4. Set next member id
        if memid_file is not None:
            try:
                self._set_stack_member_id(memid_file, esn_str)
            except Exception, reason:
                logging.debug(reason)
                del_file_all(self.ops_conn, memid_file, None)
                self.reset_startup_info(slave)
                raise

def get_cwd(ops_conn):
    """Get the full filename of the current working directory"""
    logging.info("Get the current working directory...")
    uri = "/vfm/pwds/pwd"
    req_data =  \
'''<?xml version="1.0" encoding="UTF-8"?>
<pwd>
    <dictionaryName/>
</pwd>
'''
    ret, _, rsp_data = ops_conn.get(uri, req_data)
    if ret != httplib.OK or rsp_data is '':
        raise OPIExecError('Failed to get the current working directory')

    root_elem = etree.fromstring(rsp_data)
    namespaces = {'vrp' : 'http://www.huawei.com/netconf/vrp'}
    uri = 'data' + uri.replace('/', '/vrp:') + '/vrp:'
    elem = root_elem.find(uri + "dictionaryName", namespaces)
    if elem is None:
        raise OPIExecError('Failed to get the current working directory for no "directoryName" element')

    return elem.text

def file_exist(ops_conn, file_path):
    """Returns True if file_path refers to an existing file, otherwise returns False"""
    uri = "/vfm/dirs/dir"
    str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<dir>
    <fileName>$fileName</fileName>
</dir>
''')
    req_data = str_temp.substitute(fileName = file_path)
    ret, _, rsp_data = ops_conn.get(uri, req_data)
    if ret != httplib.OK or rsp_data is '':
        raise OPIExecError('Failed to list information about the file "%s"' % file_path)

    root_elem = etree.fromstring(rsp_data)
    namespaces = {'vrp' : 'http://www.huawei.com/netconf/vrp'}
    uri = 'data' + uri.replace('/', '/vrp:') + '/vrp:'
    elem = root_elem.find(uri + "fileName", namespaces)
    if elem is None:
        return False

    return True

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : del_file
# Date Created    : 2013-7-6
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def del_file(ops_conn, file_path):
    """Delete a file permanently"""
    if file_path is None or file_path is '':
        return

    logging.info("Delete file %s permanently", file_path)
    uri = "/vfm/deleteFileUnRes"
    str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<deleteFileUnRes>
    <fileName>$filePath</fileName>
</deleteFileUnRes>
''')
    req_data = str_temp.substitute(filePath = file_path)
    try:
        # it is a action operation, so use create for HTTP POST
        ret, _, _ = ops_conn.create(uri, req_data)
        if ret != httplib.OK:
            raise OPIExecError('Failed to delete the file "%s" permanently' % file_path)

    except Exception, reason:
        logging.debug(reason)

def del_file_all(ops_conn, file_path, slave):
    """Delete a file permanently on all main boards"""
    if file_path:
        del_file(ops_conn, file_path)
        if slave:
            del_file(ops_conn, 'slave#' + file_path)

def copy_file(ops_conn, src_path, dest_path):
    """Copy a file"""
    print('Info: Copy file %s to %s...' % (src_path, dest_path))
    logging.info('Copy file %s to %s...', src_path, dest_path)
    uri = "/vfm/copyFile"
    str_temp = string.Template(
'''<?xml version="1.0" encoding="UTF-8"?>
<copyFile>
    <srcFileName>$src</srcFileName>
    <desFileName>$dest</desFileName>
</copyFile>
''')
    req_data = str_temp.substitute(src = src_path, dest = dest_path)

    # it is a action operation, so use create for HTTP POST
    ret, _, _ = ops_conn.create(uri, req_data)
    if ret != httplib.OK:
        raise OPIExecError('Failed to copy "%s" to "%s"' % (src_path, dest_path))

def has_slave_mpu(ops_conn):
    """Whether device has slave switch module, returns a bool value"""
    logging.info("Test whether device has slave MPU...")
    uri = "/devm/phyEntitys"
    req_data =  \
'''<?xml version="1.0" encoding="UTF-8"?>
<phyEntitys>
    <phyEntity>
        <entClass>mpuModule</entClass>
        <entStandbyState/>
        <position/>
    </phyEntity>
</phyEntitys>
'''
    ret, _, rsp_data = ops_conn.get(uri, req_data)
    if ret != httplib.OK or rsp_data is '':
        raise OPIExecError('Failed to get the device slave information')

    root_elem = etree.fromstring(rsp_data)
    namespaces = {'vrp' : 'http://www.huawei.com/netconf/vrp'}
    uri = 'data' + uri.replace('/', '/vrp:') + '/vrp:'
    for entity in root_elem.findall(uri + 'phyEntity', namespaces):
        elem = entity.find("vrp:entStandbyState", namespaces)
        if elem is not None and elem.text == 'slave':
            return True

    return False

def get_system_info(ops_conn):
    """Get system info, returns a dict"""
    logging.info("Get the system information...")
    uri = "/system/systemInfo"
    req_data =  \
'''<?xml version="1.0" encoding="UTF-8"?>
<systemInfo>
    <productName/>
    <esn/>
    <mac/>
</systemInfo>
'''
    ret, _, rsp_data = ops_conn.get(uri, req_data)
    if ret != httplib.OK or rsp_data is '':
        raise OPIExecError('Failed to get the system information')

    sys_info = {}.fromkeys(('productName', 'esn', 'mac'))
    root_elem = etree.fromstring(rsp_data)
    namespaces = {'vrp' : 'http://www.huawei.com/netconf/vrp'}
    uri = 'data' + uri.replace('/', '/vrp:')
    nslen = len(namespaces['vrp'])
    elem = root_elem.find(uri, namespaces)
    if elem is not None:
        for child in elem:
            tag = child.tag[nslen + 2:]       # skip the namespace, '{namespace}esn'
            if tag in sys_info.keys():
                sys_info[tag] = child.text

    return sys_info

def test_file_paths(image, config, patch, stack_memid, md5_file):
    """Test whether argument paths are valid."""
    logging.info("Test whether argument paths are valid...")
    # check image file path
    file_name = os.path.basename(image)
    if file_name is not '' and not file_name.lower().endswith('.cc'):
        print('Error: Invalid filename extension of system software')
        return False

    # check config file path
    file_name = os.path.basename(config)
    file_name = file_name.lower()
    _, ext = os.path.splitext(file_name)
    if file_name is not '' and ext not in ['.cfg', '.zip', '.dat']:
        print('Error: Invalid filename extension of configuration file')
        return False

    # check patch file path
    file_name = os.path.basename(patch)
    if file_name is not '' and not file_name.lower().endswith('.pat'):
        print('Error: Invalid filename extension of patch file')
        return False

    # check stack member id file path
    file_name = os.path.basename(stack_memid)
    if file_name is not '' and not file_name.lower().endswith('.txt'):
        print('Error: Invalid filename extension of stack member ID file')
        return False

    # check md5 file path
    file_name = os.path.basename(md5_file)
    if file_name is not '' and not file_name.lower().endswith('.txt'):
        print('Error: Invalid filename extension of md5 file')
        return False

    return True

def md5sum(fname, need_skip_first_line = False):  
    """ 
    Calculate md5 num for this file. 
    """

    def read_chunks(fhdl):  
        chunk = fhdl.read(8096)  
        while chunk:
            yield chunk
            chunk = fhdl.read(8096)  
        else:
            fhdl.seek(0)

    md5_obj = hashlib.md5()
    if isinstance(fname, basestring) and os.path.exists(fname):  
        with open(fname, "rb") as fhdl:
            #skip the first line
            fhdl.seek(0)
            if need_skip_first_line:
                fhdl.readline()
            for chunk in read_chunks(fhdl):
                md5_obj.update(chunk)
    elif fname.__class__.__name__ in ["StringIO", "StringO"] or isinstance(fname, file):  
        for chunk in read_chunks(fname):
            md5_obj.update(chunk)
    else:
        pass
    return md5_obj.hexdigest()

def md5_get_from_file(fname):
    """Get md5 num form file, stored in first line"""

    with open(fname, "rb") as fhdl:
        fhdl.seek(0)
        line_first = fhdl.readline()

    # if not match pattern, the format of this file is not supported
    if not re.match('^#md5sum="[\\w]{32}"[\r\n]+$', line_first):
        return ''

    return line_first[9:41]

def md5_check_with_first_line(fname):
    """Validate md5 for this file"""

    fname = os.path.basename(fname)
    md5_calc = md5sum(fname, True)
    print('MD5 checksum of the file "%s" is %s' % (fname, md5_calc))

    md5_file = md5_get_from_file(fname)
    print('MD5 checksum received from the file "%s" is %s' % (fname, md5_file))

    if md5_file != md5_calc:
        return False

    return True

def md5_check_with_dic(md5_dic, fname):
    """"""
    if not md5_dic.has_key(fname):
        logging.debug('md5_dic does not has key %s', fname)
        return True
    if md5_dic[fname] == md5sum(fname, False):
        return True
    return False

def parse_md5_file(fname):
    """parse md5 file"""

    def read_line(fhdl):  
        line = fhdl.readline()  
        while line:
            yield line
            line = fhdl.readline()  
        else:
            fhdl.seek(0)

    md5_dic = {}
    with open(fname, "rb") as fhdl:
        for line in read_line(fhdl):
            line_spilt = line.split()
            if 2 != len(line_spilt):
                continue
            dic_tmp = {line_spilt[0]: line_spilt[1]}
            md5_dic.update(dic_tmp)
    return md5_dic

def verify_and_parse_md5_file(fname):
    """
    vefiry data integrity of md5 file and parse this file

    format of this file is like:
    ------------------------------------------------------------------
    #md5sum="517cf194e2e1960429c6aedc0e4dba37"

    file-name              md5
    conf_5618642831132.cfg c0ace0f0542950beaacb39cd1c3b5716
    ------------------------------------------------------------------
    """
    if not md5_check_with_first_line(fname):
        return ERR, None
    return OK, parse_md5_file(fname)

def main_proc(ops_conn):
    """Main processing"""
    sys_info = get_system_info(ops_conn)    # Get system info, such as esn and system mac
    cwd = get_cwd(ops_conn)                 # Get the current working directory
    startup = Startup(ops_conn)
    slave = has_slave_mpu(ops_conn)         # Check whether slave MPU board exists or not
    chg_flag = False

    # check remote file paths
    if not test_file_paths(REMOTE_PATH_IMAGE.get(sys_info['productName'], ''), REMOTE_PATH_CONFIG,
                           REMOTE_PATH_PATCH, REMOTE_PATH_MEMID, REMOTE_PATH_MD5):
        return ERR

    # download md5 file first, used to verify data integrity of files which will be downloaded next
    local_path_md5 = None
    file_path = REMOTE_PATH_MD5
    if not file_path.startswith('/'):
        file_path = '/' + file_path
    file_name = os.path.basename(file_path)
    if file_name is not '':
        url = FILE_SERVER + file_path
        local_path_md5 = cwd + file_name
        ret = download_file(ops_conn, url, local_path_md5, MAX_TIMES_RETRY_DOWNLOAD)
        if ret is ERR or not file_exist(ops_conn, file_name):
            print('Error: Failed to download MD5 file "%s"' % file_name)
            return ERR
        print('Info: Download MD5 file successfully')
        ret, md5_dic = verify_and_parse_md5_file(file_name)
        # delete the file immediately
        del_file_all(ops_conn, local_path_md5, None)
        if ret is ERR:
            print('Error: MD5 check failed, file "%s"' % file_name)
            return ERR
    else:
        md5_dic = {}

    # download configuration file
    local_path_config = None
    file_path = REMOTE_PATH_CONFIG % sys_info['esn']
    if not file_path.startswith('/'):
        file_path = '/' + file_path
    file_name = os.path.basename(file_path)
    if file_name is not '':
        url = FILE_SERVER + file_path
        local_path_config = cwd + file_name
        ret = download_file(ops_conn, url, local_path_config, MAX_TIMES_RETRY_DOWNLOAD)
        if ret is ERR or not file_exist(ops_conn, file_name):
            print('Error: Failed to download configuration file "%s"' % file_name)
            return ERR
        print('Info: Download configuration file successfully')
        if not md5_check_with_dic(md5_dic, file_name):
            print('Error: MD5 check failed, file "%s"' % file_name)
            return ERR
        if slave:
            copy_file(ops_conn, local_path_config, 'slave#' + local_path_config)
        chg_flag = True

    # download patch file
    local_path_patch = None
    file_path = REMOTE_PATH_PATCH
    if not file_path.startswith('/'):
        file_path = '/' + file_path
    file_name = os.path.basename(file_path)
    if startup.current.patch:
        cur_pat = os.path.basename(startup.current.patch).lower()
    else:
        cur_pat = ''
    if file_name is not '' and file_name.lower() != cur_pat:
        url  = FILE_SERVER + file_path
        local_path_patch = cwd + file_name
        ret = download_file(ops_conn, url, local_path_patch, MAX_TIMES_RETRY_DOWNLOAD)
        if ret is ERR or not file_exist(ops_conn, file_name):
            print('Error: Failed to download patch file "%s"' % file_name)
            del_file_all(ops_conn, local_path_config, slave)
            return ERR
        print('Info: Download patch file successfully')
        if not md5_check_with_dic(md5_dic, file_name):
            print('Error: MD5 check failed, file "%s"' % file_name)
            del_file_all(ops_conn, local_path_config, slave)
            return ERR
        if slave:
            copy_file(ops_conn, local_path_patch, 'slave#' + local_path_patch)
        chg_flag = True

    # download stack member ID file
    local_path_memid = None
    file_path = REMOTE_PATH_MEMID
    if not file_path.startswith('/'):
        file_path = '/' + file_path
    file_name = os.path.basename(file_path)
    if file_name is not '':
        url = FILE_SERVER + file_path
        local_path_memid = cwd + file_name
        ret = download_file(ops_conn, url, local_path_memid, MAX_TIMES_RETRY_DOWNLOAD)
        if ret is ERR or not file_exist(ops_conn, file_name):
            print('Error: Failed to download system software "%s"' % file_name)
            del_file_all(ops_conn, local_path_config, slave)
            del_file_all(ops_conn, local_path_patch, slave)
            return ERR
        print('Info: Download stack member ID file successfully')
        if not md5_check_with_dic(md5_dic, file_name):
            print('Error: MD5 check failed, file "%s"' % file_name)
            del_file_all(ops_conn, local_path_config, slave)
            del_file_all(ops_conn, local_path_patch, slave)
            return ERR
        chg_flag = True
        #no need copy to slave board

    # download system software
    local_path_image = None
    file_path = REMOTE_PATH_IMAGE.get(sys_info['productName'], '')
    if not file_path.startswith('/'):
        file_path = '/' + file_path
    file_name = os.path.basename(file_path)
    if startup.current.image:
        cur_image = os.path.basename(startup.current.image).lower()
    else:
        cur_image = ''
    if file_name is not '' and file_name.lower() != cur_image:
        url  = FILE_SERVER + file_path
        local_path_image = cwd + file_name
        ret = download_file(ops_conn, url, local_path_image, MAX_TIMES_RETRY_DOWNLOAD)
        if ret is ERR or not file_exist(ops_conn, file_name):
            print('Error: Failed to download system software "%s"' % file_name)
            del_file_all(ops_conn, local_path_config, slave)
            del_file_all(ops_conn, local_path_patch, slave)
            del_file_all(ops_conn, local_path_memid, slave)
            return ERR
        print('Info: Download system software file successfully')
        if not md5_check_with_dic(md5_dic, file_name):
            print('Error: MD5 check failed, file "%s"' % file_name)
            del_file_all(ops_conn, local_path_config, slave)
            del_file_all(ops_conn, local_path_patch, slave)
            del_file_all(ops_conn, local_path_memid, slave)
            return ERR
        if slave:
            copy_file(ops_conn, local_path_image, 'slave#' + local_path_image)
        chg_flag = True

    if chg_flag is False:
        return ERR

    # set startup info
    startup.set_startup_info(local_path_image, local_path_config, local_path_patch,
                             local_path_memid, slave, sys_info['esn'])

    # delete stack member ID file after used
    del_file_all(ops_conn, local_path_memid, None)

    return OK

# ----------------------------------------------------------------------------------------------------------------------
# Func Name       : main
# Date Created    : 2013-7-2
# Author          : Author
# History         :
# Date                Author                      Modification
# ----------------------------------------------------------------------------------------------------------------------
def main(usb_path = ''):
    """The main function of user script. It is called by ZTP frame, so do not remove or change this function.

    Args:
    Raises:
    Returns: user script processing result
    """
    host = "localhost"
    if usb_path and len(usb_path):
        logging.debug('ztp_script usb_path: %s', usb_path)
        global FILE_SERVER
        FILE_SERVER = 'file:///' + usb_path
    try:
        # Make an OPS connection instance.
        ops_conn = OPSConnection(host)
        ret = main_proc(ops_conn)

    except OPIExecError, reason:
        logging.debug('OPI execute error: %s', reason)
        print("Error: %s" % reason)
        ret = ERR

    except ZTPErr, reason:
        logging.debug('ZTP error: %s', reason)
        print("Error: %s" % reason)
        ret = ERR

    except Exception, reason:
        logging.debug(reason)
        traceinfo = traceback.format_exc()
        logging.debug(traceinfo)
        ret = ERR

    finally:
        # Close the OPS connection
        ops_conn.close()

    return ret

if __name__ == "__main__":
    main()

Python Script Descriptions
NOTE:

Information in bold can be modified based on the actual running environment.

Table 1-11 Python script descriptions

Function

Script Content

Description

Specifies the MD5 code of the script.

#md5sum="5bb3da014aa88ba8111c2f1191373716"

You can use the MD5 code to check the integrity of the script downloaded by the device.

You can use an MD5 calculation tool, such as md5sum, to generate the MD5 code of the script.
NOTE:

The script cannot contain #md5sum= when the MD5 code is generated. Add #md5sum= to the beginning of the script after the MD5 code is generated.

Specifies the path where version files can be obtained.

FILE_SERVER  = 'ftp://ftpuser:Pwd123@10.1.3.2'

You can obtain version files from a TFTP, an FTP, SFTP, or HTTP server. Based on the server used, the path can be any of the following:

  • tftp://hostname
  • ftp://[username[:password]@]hostname[:port]
  • sftp://[username[:password]@]hostname[:port]
  • http://hostname[:port]

The parameters username, password, and port are optional.

Specifies the path and name of the system software.

REMOTE_PATH_IMAGE  = {
  'CX110'  : '/image/CX110-Switch-V103.cc',
  'CX310'  : '/image/CX310-Switch-V103.cc',
}

CX110 indicates the device model. /image/CX110-Switch-V103.cc specifies the path and name of the system software obtained by CX110 switch module GE switching plane.

If the device does not need to load system software, set this field to ''.

Specifies the path and name of the configuration file.

REMOTE_PATH_CONFIG  = '/config/conf_%s.cfg'

%s indicates the device ESN and cannot be modified. The device obtains the configuration file matching the ESN.

Specifies the path and name of the patch file.

REMOTE_PATH_PATCH  = '/patch/patch.pat'

This field specifies the path and name of the patch file to be loaded.

If the device does not need to load a patch file, set this field to ''.

Specifies the path and name of the stack member ID file.

REMOTE_PATH_MEMID  = '/stack/stack_member.txt'

If multiple unconfigured devices set up a stack after they complete automatic deployment, configure a stack member ID for each device.

See Automatic Stacking in ZTP for the format of the stack member ID file.

This parameter is mandatory if a stack must be set up; otherwise, set this parameter to ''.

Specifies the path and name of the MD5 code file.

REMOTE_PATH_MD5  = '/md5.txt'

You can use the MD5 code file to check the integrity of the files downloaded by the device.

See Checking the Integrity of Version Files for the format of the MD5 code file.

If the downloaded files do not need to be checked, set this field to ''.

Defines the interval for collecting device startup information.

GET_STARTUP_INTERVAL  = 15

This field defines the interval for collecting device startup information.

Defines the maximum number of times that device startup information are retransmitted.

MAX_TIMES_GET_STARTUP  = 120

This field defines the maximum number of device startup information retransmissions.

Defines the number of retries to download files.

MAX_TIMES_RETRY_DOWNLOAD  = 3

This field defines the maximum number of retries to download files.

Creates an OPS connection.

class OPSConnection()

You do not need to edit this field.

Defines the HTTP header.

def __init__()

You do not need to edit this field.

Encapsulates the OPS connection.

self.conn = httplib.HTTPConnection()

You do not need to edit this field.

Closes the OPS connection.

def close()

You do not need to edit this field.

Defines an add action.

def create()

You do not need to edit this field.

Defines a delete action.

def delete()

You do not need to edit this field.

Defines an obtain action.

def get()

You do not need to edit this field.

Defines a configure action.

def set()

You do not need to edit this field.

Sets the format of request code to REST.

def _rest_call()

You do not need to edit this field.

Displays debugging logs.

logging.debug()

You do not need to edit this field.

Indicates an OPS process error.

class OPIExecError()

You do not need to edit this field.

Indicates an automatic deployment error.

class ZTPErr()

You do not need to edit this field.

Resolves domain names.

def get_addr_by_hostname()

You do not need to edit this field.

Downloads files in HTTP mode.

def _http_download_file()

You do not need to edit this field.

Downloads files in FTP mode.

def _ftp_download_file()

You do not need to edit this field.

Clears the RSA key after SFTP download fails.

def _del_rsa_peer_key()

You do not need to edit this field.

Clears the IP address of the SSH server and RSA key after SSH download fails.

def _del_sshc_rsa_key()

You do not need to edit this field.

Configures user attributes for SSH client authentication at the first login.

def _set_sshc_first_time()

You do not need to edit this field.

Downloads files in SFTP mode.

def _sftp_download_file()

You do not need to edit this field.

Downloads files in TFTP mode.

def _tftp_download_file()

You do not need to edit this field.

Downloads files from a USB flash drive.

def _usb_download_file()

You do not need to edit this field.

Defines file download parameters.

def download_file()

You do not need to edit this field.

Obtains startup information and starts the device.

class StartupInfo()
class Startup()

You do not need to edit this field.

Obtains the working directory of the user.

def get_cwd()

You do not need to edit this field.

Checks whether the file to be downloaded exists.

def file_exist()

You do not need to edit this field.

Deletes files after a load failure.

def del_file()

If files fail to be loaded, they are deleted so that the device can restore to the state before ZTP starts. This facilitates subsequent operations.

You do not need to edit this field.

Copies a file.

def copy_file()

You do not need to edit this field.

Checks whether the device has a standby switch module.

def has_slave_mpu()

You do not need to edit this field.

Obtains the system information.

def get_system_info()

You do not need to edit this field.

Checks whether the file path is available.

def test_file_paths()

You do not need to edit this field.

Verifies the file using the MD5 code.

def md5sum()
def md5_get_from_file(fname)
def md5_check_with_first_line()
def md5_check_with_dic()
def parse_md5_file()
def verify_and_parse_md5_file()

You do not need to edit this field.

Defines the overall automatic deployment process.

def main_proc()
def main()
if __name__ == "__main__":
    main()

You do not need to edit this field.

The main function must be provided; otherwise, the script cannot be executed.

Automatic Stacking in ZTP

To enable multiple unconfigured devices to set up a stack after automatic deployment is complete, configure a stack member ID for each member device using the stack member ID file.

The stack member ID file must be a text file, with the name extension .txt. The format is as follows:

ESN                    Stack group   Stack member
21023553380DCCE12823   10            1
21023553380DCCE12824   10            2
Table 1-12 Description of fields in the stack member ID file

Field

Mandatory or Optional

Description

ESN

Mandatory

Specifies the equipment serial number (ESN) of a device.

Stack group

Mandatory

Indicates the stack ID used to identify different stacks.

Stack member

Mandatory

Specifies the stack member ID of the device.

Checking the Integrity of Version Files

You can use an MD5 code file to check the integrity of the files downloaded by the device. The MD5 code of a file to be downloaded is saved in the MD5 code file in advance. After the device downloads the file, it generates an MD5 code and then compares the generated MD5 code with that saved in the MD5 code file. If the generated MD5 code is different from that saved in the MD5 code file, the device does not load the file.

The MD5 code file must be a text file, with the name extension .txt. The format is as follows:

#md5sum="540102b82d5ff5aee70deccc9236e3bb"

file-name                 md5
conf_5618642831132.cfg    c0ace0f0542950beaacb39cd1c3b5716
Table 1-13 Description of fields in the MD5 code file

Field

Mandatory or Optional

Description

#md5sum

Mandatory

Specifies the MD5 code of the file to be checked.

file-name

Mandatory

Specifies the file name.

md5

Mandatory

Specifies the MD5 code generated by the device.

Translation
Download
Updated: 2019-08-09

Document ID: EDOC1000041694

Views: 59090

Downloads: 3623

Average rating:
This Document Applies to these Products
Related Version
Related Documents
Share
Previous Next