当前位置: 首页>>代码示例>>Python>>正文


Python Config.commit方法代码示例

本文整理汇总了Python中jnpr.junos.utils.config.Config.commit方法的典型用法代码示例。如果您正苦于以下问题:Python Config.commit方法的具体用法?Python Config.commit怎么用?Python Config.commit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jnpr.junos.utils.config.Config的用法示例。


在下文中一共展示了Config.commit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: edit_config

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
    def edit_config(self,dev,ip):
        conf='set policy-options prefix-list blacklisted-ips'
        _conf=''
        #print p,dev
        ips=ip.split()
        for i in ips:
            print "ip=",i
            if IPAddress(i) in IPNetwork("116.197.188.0/23") or IPAddress(i) in IPNetwork("116.197.190.0/23") or IPAddress(i) in IPNetwork("193.110.49.0/23") or IPAddress(i) in IPNetwork("193.110.55.0/23") or IPAddress(i) in IPNetwork("66.129.239.0/23") or IPAddress(i) in IPNetwork("66.129.241.0/23"):

                print "Internal IP"
                continue
            _conf=_conf+conf+' '+i+'\n'
            print "conf", _conf
        try:
            cu=Config(dev)
            #print '1'
            cu.load(_conf,format='set')
            #fp.write(str(datetime.now())+"the conf has been added to "+p[0]+" \n"+_conf+" \n")
            print dev.facts['hostname']
            cu.pdiff()
            cu.commit(confirm=3)
            print "Waiting for 2 mins before final commit..."
            cu.commit()
            #fp.write(str(datetime.now())+" the commit has been done "+" \n")
            print "the config has been committed for",dev.facts['hostname']
        except Exception as e:
            print "commit failed:",e
开发者ID:ssupratik,项目名称:cns-dashboard,代码行数:29,代码来源:models.py

示例2: test_load_console

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
    def test_load_console(
            self, mock_read_until, mock_select, mock_write, mock_parse):
        mock_select.return_value = ([self.dev._tty._rx], [], [])
        xml = """<policy-options>
                  <policy-statement>
                    <name>F5-in</name>
                    <term>
                        <name>testing</name>
                        <then>
                            <accept/>
                        </then>
                    </term>
                    <from>
                        <protocol>mpls</protocol>
                    </from>
                </policy-statement>
                </policy-options>"""

        mock_read_until.return_value = six.b("""
        <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/15.2I0/junos">
            <load-configuration-results>
            <ok/>
            </load-configuration-results>
            </rpc-reply>
            ]]>]]>""")
        cu = Config(self.dev)
        op = cu.load(xml, format='xml')
        cu.commit()
开发者ID:ydnath,项目名称:py-junos-eznc,代码行数:30,代码来源:test_console.py

示例3: main

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
def main():
    """Simple main method to change port status."""
    routers = ['10.11.12.1', '10.11.12.2']
    pyez_user = 'netconf'
    pyez_pass = 'test123'
    sessions = [Device(host=router, user=pyez_user, password=pyez_pass) for router in routers]

    for session in sessions:
        session.open()
        port = PhyPortClassic(session, namevar='ge-0/0/3')
        # Step 1.1
        # print(port.properties)
        # print(port.admin)

        # Step 1.2
        port.admin = False
        port.write()

        print("Disabling interfaces!")
        cfg = Config(session)
        cfg.commit()
        time.sleep(10)

        port.admin = True
        port.write()

        print("Enabling interfaces!")
        cfg.commit()
        session.close()
开发者ID:darien-hirotsu,项目名称:JNPRAutomationBootcamp,代码行数:31,代码来源:bounce_interface.py

示例4: _normal_device

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
def _normal_device(dev):

    x=loadyaml(site.getsitepackages()[1]+'/jnpr/junos/op/phyport.yml')
    table=x['PhyPortTable'](dev)
    table.get()
    ke=table.keys()
    cu=Config(dev)
    print cu
    for i in ke:
        sw = dev.rpc.get_config(filter_xml=etree.XML('<configuration><interfaces><interface><name>'+i+'</name></interface></interfaces></configuration>'))
        s=etree.tostring(sw)
        #print s
        e = ET.XML(s)
        x=etree_to_dict(e)
        #print x

        if(x['configuration']==''):
            print 'Unused port '+i+ ' disabled'
            set_cmd='set interfaces '+i+' disable description "unused port"'
            cu.load(set_cmd, format='set')
        else:
            try:
                if(x['configuration']['interfaces']['interface']['unit']['family']['inet']==''):
                    #print 'Unused port '+i+ ' disabled'
                    set_cmd='set interfaces '+i+' disable description "unused port"'
                    cu.load(set_cmd, format='set')
            except:
                pass
    cu.pdiff()
    cu.commit(confirm=1)
    print "the config has been committed"
开发者ID:ssupratik,项目名称:cns-dashboard,代码行数:33,代码来源:models.py

示例5: JuniperObject

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
class JuniperObject(object):
    def __init__(self, jnp_dev):
        self.conn = jnp_dev
        self.config = None
        self.ports = {}
        self.routes = {}

    def __get_ports(self):
        self.ports = EthPortTable(self.conn)
        self.ports.get()

    def __get_routes(self):
        self.routes = RouteTable(self.conn)
        self.routes.get()
   
    def config_mode(self):
        self.config = Config(self.conn)
        self.config.lock()

    def send_command(self, command, cmd_format, cmd_merge):
        self.config.load(command, format=cmd_format, merge=cmd_merge)

    def file_command(self, file_path, file_format, file_merge):
        self.config.load(path=file_path, format=file_format, merge=file_merge)
   
    def get_diff(self):
        return self.config.diff()

    def commit(self, comment=None):
        self.config.commit(comment=comment)
   
    def rollback(self):
        self.config.rollback(0)

    def unlock(self):
        self.config.unlock()

    def show_all_interfaces(self):
        self.__get_ports()
        print "Juniper SRX Interface Statistics"
        for my_key in self.ports.keys():
            print "---------------------------------"
            print my_key + ":"
            print "Operational Status: " + self.ports[my_key]['oper']
            print "Packets In: " + self.ports[my_key]['rx_packets']
            print "Packets Out: " + self.ports[my_key]['tx_packets']

    def show_all_routes(self):
        self.__get_routes()
        print "Juniper SRX Routing Table"
        for my_key in self.routes.keys():
            print "---------------------------------"
            print my_key + ":"
            print "  Next Hop: {}".format(self.routes[my_key]['nexthop'])
            print "  Age: {}".format(self.routes[my_key]['age'])
            print "  via: {}".format(self.routes[my_key]['via'])
            print "  Protocol: {}".format(self.routes[my_key]['protocol'])
开发者ID:pmusolino-rms,项目名称:Network-Automation-with-Python-and-Ansible-class,代码行数:59,代码来源:juniper_connection.py

示例6: run

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
    def run(self):
        self.logfile = open(os.getcwd() + '/' + 'linkfailure_log', 'a')
        while True:
            while self.failed() == False:
                time.sleep(1)
            # select a router
            r_number = random.randint(1,len(self.rtr)) - 1
            # select a random interface 
            i_number = random.randint(1, len(self.rtr[r_number]['interfaces'])) - 1

            #set interfaces ge-1/0/3 disable 

            cmd = 'set interfaces ' + self.rtr[r_number]['interfaces'][i_number]['name'] + ' disable'

            dev = Device(host=self.rtr[r_number]['ip'], user='root', password='juniper123')
            dev.open()
            dev.timeout = 60
            cu = Config(dev)
            cu.lock()
            cu.load(cmd, format='set', merge=True)
            cu.commit()
            cu.unlock()
            dev.close()
            link__data = { 'status': 'failed', 'timestamp': datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S'), 
                                'router_id': self.rtr[r_number]['router_id'], 'router_name': self.rtr[r_number]['name'],
                                'interface_address': self.rtr[r_number]['interfaces'][i_number]['address'],
                                'interface_name': self.rtr[r_number]['interfaces'][i_number]['name']
                         }
            jd = json.dumps(link__data)
            self.redis.publish('link_event', jd)
            self.logfile.write("Link failed: " + datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S') + " " +
                               self.rtr[r_number]['name'] + " " +  self.rtr[r_number]['ip'] + " " + self.rtr[r_number]['interfaces'][i_number]['name'] + "\n")
            self.logfile.flush()
            # now repair the link
            while self.repaired() == False:
                time.sleep(1)

            cmd = 'delete interfaces ' + self.rtr[r_number]['interfaces'][i_number]['name'] + ' disable'
            dev = Device(host=self.rtr[r_number]['ip'], user='root', password='juniper123')
            dev.open()
            dev.timeout = 60
            cu = Config(dev)
            cu.lock()
            cu.load(cmd, format='set', merge=True)
            cu.commit()
            cu.unlock()
            dev.close()
            link__data = { 'status': 'healed', 'timestamp': datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S'), 
                                'router_id': self.rtr[r_number]['router_id'], 'router_name': self.rtr[r_number]['name'],
                                'interface_address': self.rtr[r_number]['interfaces'][i_number]['address'],
                                'interface_name': self.rtr[r_number]['interfaces'][i_number]['name']
                         }
            jd = json.dumps(link__data)
            self.redis.publish('link_event', jd)
            self.logfile.write("Link healed: " + datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S') + " " +
                               self.rtr[r_number]['name'] + " " +  self.rtr[r_number]['ip'] + " " + self.rtr[r_number]['interfaces'][i_number]['name'] + "\n")
            self.logfile.flush()
开发者ID:azaringhalam,项目名称:hackathon,代码行数:59,代码来源:link_failure.py

示例7: process_device

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
def process_device(ip, **kwargs):
    dev = Device(host=ip, **kwargs)
    cu = Config(dev)
    print "Searching for active sessions on Device:", ip, "matching the following criteria" + '\n\n\t' + "Destination IP-Address:" + '\t' + destip + '\n\t' + "Destination-Port:" + '\t' +  dport + '\n\t' + "Application:" + '\t\t' +  application + '\n'

    try:

        dev.open()
        cluster_status = ClusterStatus(dev)
        cluster_status.get()
        session_table = SessionTable(dev)
        session_table.get()
        found = 'f'
        cluster = 'a'
        cu.lock()

        for c in cluster_status:
          if cluster_status.keys():
            print "SRX Cluster has redundancy-group", c.redundancy_group_id
          if not cluster_status.keys():
            print "Clustering is not Enabled"

        for s in session_table:
          if session_table.keys() and s.in_destination_address == destip and s.in_destination_port == dport and s.in_session_protocol == application:
            found = 't'
            print "Found Session on", ip, s.re_name  + '\n\n\t' + "Source-Address:" + '\t' + s.in_source_address +'\n\t' + "Session-Id:" + '\t' + s.session_identifier + '\n\n' + "Creating Address-entry on Device:", ip + '\n\n' + "Clearing active session" + '\n\t' + "Session-Id:" + '\t' + s.session_identifier + '\n\t' + "Cluster-Node:" + '\t' + s.re_name + '\n'
            block_src = {'Address': s.in_source_address}
            jinja_data = open("jinjafile.conf", "wb")
            jinja_data.write(JinjaTemplate.render(**block_src))
            jinja_data.close()
            rsp = cu.load( template_path="jinjafile.conf", merge=True )
            clearflow = dev.rpc.clear_flow_session(destination_prefix=s.in_destination_address, source_prefix=s.in_source_address, destination_port=s.in_destination_port, protocol=s.in_session_protocol)
        cu.commit()
        cu.unlock()

        if found == 'f':
            print "No Active Sessions were found with the following criteria:" + '\n\n\t' + "Destination IP-Address:" + '\t' + destip + '\n\t' + "Destination Port:" + '\t' + dport +'\n\t' + "Application:" + '\t\t' + application + '\n'

    except RpcError:
        msg = "{0} was Skipped due to RPC Error.  Device is not a Juniper SRX Series".format(ip.rstrip())
        print msg
        dev.close()

    except Exception as err:
        msg = "{0} was skipped due to unhandled exception.\n{1}".format(ip.rstrip(), err)
        print msg
        traceback.print_exc(file=sys.stdout)

    dev.close()
开发者ID:rlemm-juniper,项目名称:block-ip,代码行数:51,代码来源:block-ip.py

示例8: __init__

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
class Jconfig:

    def __init__(self, host, user='rancid', password='xxxxx', t_vars={}):
        self.host = host
        self.user = user
        self.password = password
        self.t_vars = t_vars

        self.dev = Device(host=self.host, user=self.user, password=self.password, gather_facts=False)
        try:
            self.dev.open()
            self.dev.timeout = 300
            self.cfg = Config(self.dev)
        except Exception as err:
            print err
            sys.exit(1)

    def loadconf(self, t_file):
        try:
            print "=> Loading file %s on %s" % (t_file, self.host)
            self.cfg.load(template_path=t_file, template_vars=self.t_vars, overwrite=False, merge=True)
        except Exception as err:
            print err

    def askcommit(self):
        try:
            print "== Configuration diff on %s" % (self.host)
            self.cfg.pdiff()
            answer = raw_input('Do you want to commit change ? [y/n]')
            if answer[0] == 'y':
                self.cfg.commit()
        except Exception as err:
            print err

    def commit(self):
        try:
            print "== Configuration diff on %s" % (self.host)
            self.cfg.pdiff()
            self.cfg.commit()
        except Exception as err:
            print err
    
    def getconf(self):
        try:
            conf = self.dev.rpc.get_configuration(dict(format='text'))
            return etree.tostring(conf, method="text")
        except Exception as err:
            print err
开发者ID:ut0mt8,项目名称:junos-netconf,代码行数:50,代码来源:jconfig.py

示例9: deployConfig

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
def deployConfig(my_device_list_dict, my_username, my_password, my_config_template_file):
	my_hostname=""
	try:
		my_hostname=my_device_list_dict["mgmt_ip"]
		printProgress("INFO",my_hostname,"Connecting to device through netconf.")
		dev=Device(my_hostname,user=my_username,password=my_password)
		dev.open()
		dev.timeout=3*60
		cu = Config(dev)
		printProgress("INFO",my_hostname,"Going to load template the config now.")
		
		# Determine if template file is in "set" or "bracketed" format
		if isSet(my_config_template_file):
			rsp=cu.load(template_path=my_config_template_file,format='set',template_vars=my_device_list_dict)
		else:
			rsp=cu.load(template_path=my_config_template_file,template_vars=my_device_list_dict)
		
		printProgress("INFO",my_hostname,"Performing diff between active and candidate config.")
		cu.pdiff()
		printProgress("INFO",my_hostname,"Performing commit check")
		if cu.commit_check():
			printProgress("INFO",my_hostname,"commit check was successfull.")
			printProgress("INFO",my_hostname,"performing commit now.")
			commit_status=cu.commit()
			printProgress("INFO",my_hostname,"disconnecting from device.")
			dev.close()
			return commit_status
		else:
			return False
	except Exception,err:
		printProgress("ERROR",my_hostname,"Encountered exception while deploying config")
		printProgress("ERROR",my_hostname,str(err))
		return False
开发者ID:tylerjordan,项目名称:jload,代码行数:35,代码来源:jload.py

示例10: main

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
def main():
    '''
    Exercise using Juniper's PyEZ to make changes to device in various ways
    '''
    pwd = getpass()
    ip_addr = raw_input("Enter Juniper SRX IP: ")
    ip_addr = ip_addr.strip()

    juniper_srx = {
        "host": ip_addr,
        "user": "pyclass",
        "password": pwd
    }

    print "\n\nConnecting to Juniper SRX...\n"
    a_device = Device(**juniper_srx)
    a_device.open()

    cfg = Config(a_device)

    print "Setting hostname using set notation"
    cfg.load("set system host-name test1", format="set", merge=True)

    print "Current config differences: "
    print cfg.diff()

    print "Performing rollback"
    cfg.rollback(0)

    print "\nSetting hostname using {} notation (external file)"
    cfg.load(path="load_hostname.conf", format="text", merge=True)

    print "Current config differences: "
    print cfg.diff()

    print "Performing commit"
    cfg.commit()

    print "\nSetting hostname using XML (external file)"
    cfg.load(path="load_hostname.xml", format="xml", merge=True)

    print "Current config differences: "
    print cfg.diff()

    print "Performing commit"
    cfg.commit()
    print
开发者ID:GnetworkGnome,项目名称:pynet,代码行数:49,代码来源:ex4_change_hostname.py

示例11: updateDeviceConfiguration

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
    def updateDeviceConfiguration(self):
        '''
        Device Connection should be open by now, no need to connect again 
        '''
        logger.debug('updateDeviceConfiguration for %s' % (self.deviceLogStr))
        l3ClosMediation = L3ClosMediation(conf = self._conf)
        config = l3ClosMediation.createLeafConfigFor2Stage(self.device)
        # l3ClosMediation used seperate db sessions to create device config
        # expire device from current session for lazy load with committed data
        self._session.expire(self.device)
        
        configurationUnit = Config(self.deviceConnectionHandle)

        try:
            configurationUnit.lock()
            logger.debug('Lock config for %s' % (self.deviceLogStr))

        except LockError as exc:
            logger.error('updateDeviceConfiguration failed for %s, LockError: %s, %s, %s' % (self.deviceLogStr, exc, exc.errs, exc.rpc_error))
            raise DeviceError(exc)

        try:
            # make sure no changes are taken from CLI candidate config left over
            configurationUnit.rollback() 
            logger.debug('Rollback any other config for %s' % (self.deviceLogStr))
            configurationUnit.load(config, format='text')
            logger.debug('Load generated config as candidate, for %s' % (self.deviceLogStr))

            #print configurationUnit.diff()
            #print configurationUnit.commit_check()
            configurationUnit.commit()
            logger.info('Committed twoStage config for %s' % (self.deviceLogStr))
        except CommitError as exc:
            #TODO: eznc Error handling is not giving helpful error message
            logger.error('updateDeviceConfiguration failed for %s, CommitError: %s, %s, %s' % (self.deviceLogStr, exc, exc.errs, exc.rpc_error))
            configurationUnit.rollback() 
            raise DeviceError(exc)
        except Exception as exc:
            logger.error('updateDeviceConfiguration failed for %s, %s' % (self.deviceLogStr, exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            configurationUnit.rollback() 
            raise DeviceError(exc)

        finally:
            configurationUnit.unlock()
            logger.debug('Unlock config for %s' % (self.deviceLogStr))
开发者ID:codyrat,项目名称:OpenClos,代码行数:48,代码来源:devicePlugin.py

示例12: updateDeviceConfiguration

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
    def updateDeviceConfiguration(self):
        '''
        Device Connection should be open by now, no need to connect again 
        '''
        logger.debug('updateDeviceConfiguration for %s' % (self.deviceLogStr))
        config = self.getDeviceConfig()
        
        configurationUnit = Config(self.deviceConnectionHandle)

        try:
            configurationUnit.lock()
            logger.debug('Lock config for %s' % (self.deviceLogStr))

        except LockError as exc:
            logger.error('updateDeviceConfiguration failed for %s, LockError: %s, %s, %s' % (self.deviceLogStr, exc, exc.errs, exc.rpc_error))
            raise DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), exc)

        try:
            # make sure no changes are taken from CLI candidate config left over
            configurationUnit.rollback() 
            logger.debug('Rollback any other config for %s' % (self.deviceLogStr))
            configurationUnit.load(config, format='text')
            logger.debug('Load generated config as candidate, for %s' % (self.deviceLogStr))

            #print configurationUnit.diff()
            #print configurationUnit.commit_check()
            configurationUnit.commit()
            logger.info('Committed twoStage config for %s' % (self.deviceLogStr))
        except CommitError as exc:
            #TODO: eznc Error handling is not giving helpful error message
            logger.error('updateDeviceConfiguration failed for %s, CommitError: %s, %s, %s' % (self.deviceLogStr, exc, exc.errs, exc.rpc_error))
            configurationUnit.rollback() 
            raise DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), exc)
        except Exception as exc:
            logger.error('updateDeviceConfiguration failed for %s, %s' % (self.deviceLogStr, exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            configurationUnit.rollback() 
            raise DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), exc)
        finally:
            configurationUnit.unlock()
            logger.debug('Unlock config for %s' % (self.deviceLogStr))
开发者ID:Juniper,项目名称:OpenClos,代码行数:43,代码来源:devicePlugin.py

示例13: VlanDeployer

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
class VlanDeployer(threading.Thread):
	def __init__(self , host , vlans):
		self.cred = host
		self.vlans = vlans
		threading.Thread.__init__(self)
		self.dev1 = None
		self.cu=None
	
	def run(self):
		self.dev1 = Device(host=self.cred[0] , user=self.cred[1] , password=self.cred[2])
		self.dev1.open()
		self.cu = Config(self.dev1)
		print "CONNECTED TO "+self.cred[0]

		for term in self.vlans:
			config_text= 'vlans{ ' + term['Vlan-name'] + '{description "'  + term['Desc'] + '"; vlan-id ' + term["Vlan-id"]+ ';}}'
			self.cu.load(config_text , format="text" , merge=True)

		self.cu.commit()
		self.dev1.close()
		print "CONF PUSHED TO "+ self.cred[0]
开发者ID:ihafiri,项目名称:jnprEZ,代码行数:23,代码来源:vlansetup.py

示例14: main

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
def main():

    pwd = getpass()

    juniper = {
        "host": "50.76.53.27",
        "user": "pyclass",
        "password": pwd
    }

    a_device = Device(**juniper)
    a_device.open()

    cfg = Config(a_device)

    print "Changing hostname with set command"
    cfg_load = cfg.load("set system host-name batz-jnpr-srx1", format ="set", merge=True)
    print cfg.diff()
    print
    print "Doing rollback"
    cfg.rollback(0)


    print "Changing hostname with conf method "
    cfg_load_conf = cfg.load(path='hostname.conf', format='text', merge=True)
    print cfg.diff()
    print
    print "Doing rollback"
    cfg.rollback(0)


    print "Changing hostname with xml method"
    cfg_load_xml = cfg.load(path='hostname.xml', format='xml', merge=True)
    print cfg.diff()
    print

    print "Doing changes"
    cfg.commit()
    print
开发者ID:jabibenito,项目名称:pynet_course,代码行数:41,代码来源:exercise4.py

示例15: main

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import commit [as 别名]
def main():

    '''
    I will test the case with applying config for 1 minute
    '''
    pwd = getpass()
    ip_addr = raw_input('''Enter Juniper SRX IP"(184.105.247.76)": ''')
    ip_addr = ip_addr.strip()
    juniper_srx = {
        "host": ip_addr,
        "user": "pyclass",
        "password": pwd
    }
    try:
        a_device = Device(**juniper_srx)
        a_device.open()
        cfg = Config(a_device)
        cfg.lock()
        cfg.load(path="exercice4_config.xml" , format="xml", merge=True)
        print "#"*80
        print "Displaying the differences between the running config and the candidate config:"
        print "#"*80
        cfg.pdiff()
        print "+"*80
        print "Applying config"
        print "+"*80
        cfg.commit(comment="Applying config from exercice4_config.xml")
        print "-"*80
        print "reverting config back"
        cfg.rollback(1)
        cfg.pdiff()
        cfg.commit()
        print "-"*80
        print "\n"*2
        print
    except:
        print
        print "Authentication Error"
        print
开发者ID:HassanHbar,项目名称:pynet_ansible,代码行数:41,代码来源:exercice4_2.py


注:本文中的jnpr.junos.utils.config.Config.commit方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。