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


Python ConnectHandler.send_command_timing方法代码示例

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


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

示例1: ssh_conn

# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import send_command_timing [as 别名]
def ssh_conn(**kwargs):
    """SSH to Device and send commands (Threaded)"""
    output_q = kwargs['output_q']
    sout = []
    try:
        net_connect = ConnectHandler(device_type=kwargs['Platform'],
                                     ip=kwargs['FQDN'],
                                     username=config['nsj']['username'],
                                     password=config['nsj']['password'])
        net_connect.enable()
        for s in kwargs['shcmds']:
            output = net_connect.send_command(s)
            #print(output)
            #output = net_connect.send_config_set(cfg_command)
            sout.append(output)
        if len(kwargs['confcmds']) > 0:
            net_connect.config_mode()
            for c in kwargs['confcmds']:
                output = ""
                logging.debug('Sending Command to %s: %s' % (kwargs['Name'], c))
                if args.timing:
                    output = net_connect.send_command_timing(c)
                else:
                    output = net_connect.send_command(c)
                sout.append(output)
            net_connect.exit_config_mode()
        if args.wrmem:
            logging.info("Writing Mem on %s" % (kwargs['Name']))
            net_connect.send_command("wr")
            sleep(20)
        net_connect.disconnect()
    except Exception as e:
        error = 'Error on {}: {}'.format(kwargs['FQDN'], e)
        logger.critical(error)
        #print('ERROR on ', kwargs['FQDN'], e)
        output = ERROR_PATTERN
    output_q.put({kwargs['Name']: sout})
开发者ID:yantisj,项目名称:netgrph,代码行数:39,代码来源:nsj.py

示例2: IOSXR

# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import send_command_timing [as 别名]

#.........这里部分代码省略.........
                                         port=self.port,
                                         username=self.username,
                                         password=self.password)
            self.device.timeout = self.timeout
        except NetMikoTimeoutException as t_err:
            raise ConnectError(t_err.message)
        except NetMikoAuthenticationException as au_err:
            raise ConnectError(au_err.message)

        self._cli_prompt = self.device.find_prompt()  # get the prompt

        self._enter_xml_mode()

    def _timeout_exceeded(self, start=None, msg='Timeout exceeded!'):
        if not start:
            return False  # reference not specified, noth to compare => no error
        if time.time() - start > self.timeout:
            # it timeout exceeded, throw TimeoutError
            raise TimeoutError(msg, self)
        return False

    def _lock_xml_agent(self, start=None):
        while (not self._xml_agent_locker.acquire(False)
            and not self._timeout_exceeded(start, 'Waiting to acquire the XML agent!')):
                # will wait here till the XML agent is ready to receive new requests
                # if stays too much, _timeout_exceeded will raise TimeoutError
                pass  # do nothing, just wait
        return True  # ready to go now

    def _unlock_xml_agent(self):
        if self._xml_agent_locker.locked():
            self._xml_agent_locker.release()

    def _send_command_timing(self, command):

        return self.device.send_command_timing(command,
                                               delay_factor=self._READ_DELAY,
                                               max_loops=self._XML_MODE_DELAY/self._READ_DELAY,
                                               strip_prompt=False,
                                               strip_command=False)

    def _in_cli_mode(self):

        out = self._send_command_timing('\n')
        if not out:
            return False
        if self._cli_prompt in out:
            return True
        return False

    def _enter_xml_mode(self):

        self._unlock_xml_agent()
        # release - other commands should not have anyway access to the XML agent
        # when not in XML mode
        self._lock_xml_agent()  # make sure it won't collide with other parallel requests

        out = self._send_command_timing(self._XML_SHELL)  # send xml shell command

        if '0x24319600' in out:
            # XML agent is not enabled
            raise ConnectError('XML agent is not enabled. Please configure `xml agent tty iteration off`!', self)

        self._unlock_xml_agent()

        if self.lock_on_connect:
开发者ID:courtsmith,项目名称:pyiosxr,代码行数:70,代码来源:iosxr.py

示例3: ConnectHandler

# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import send_command_timing [as 别名]
} 

ssh_device = {
    'device_type': 'cisco_ios_ssh',
    'ip': ip_addr,
    'username': 'pyclass',
    'password': pwd,
    'port': 22,
} 

print "telnet"
net_connect1 = ConnectHandler(**telnet_device)
print "telnet prompt: {}".format(net_connect1.find_prompt())
print "send_command: "
print '-' * 50
print net_connect1.send_command_timing("show arp")
print '-' * 50
print '-' * 50
print net_connect1.send_command("show run")
print '-' * 50
print

print "SSH"
net_connect2 = ConnectHandler(**ssh_device)
print "SSH prompt: {}".format(net_connect2.find_prompt())
print "send_command: "
print '-' * 50
print net_connect2.send_command("show arp")
print '-' * 50
print '-' * 50
print net_connect1.send_command("show run")
开发者ID:cshultz,项目名称:netmiko,代码行数:33,代码来源:test_cisco_simple.py

示例4: main

# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import send_command_timing [as 别名]
def main(username, device, ipaddr):
    '''Get password and create device
    '''
    pwd = getpass('Password: ')
    dev = {
    'device_type': 'a10',
    'ip': device,
    'username': username,
    'password': pwd,
    'global_delay_factor': 3,
    'verbose': True,
    'secret': pwd,
    }

    '''Detect query, use it as a partition. Please adjust to your network. 
    '''

    net1 = IPSet(['172.29.1.0/24']) | IPSet(['172.29.2.0/24'])
    net2 = IPSet(['172.31.1.0/24'])
    net3 = IPSet(['172.29.3.0/24']) | IPSet(['172.29.4.0/24'])
    net4 = IPSet(['172.31.3.0/24'])

    '''We use ip address for partition selection
       Adjust to your needs.
    '''

    if ipaddr in net1:
        network = 'First_Partition'

    if ipaddr in net2:
        network = 'Second_partition'

    if ipaddr in net3:
        network = 'Third_Partition'

    if ipaddr in net4:
        network = 'Fourth_Partition'

    '''Connect to device
    '''

    net_connect = ConnectHandler(**dev)

    print("\nStart time: {}".format(str(datetime.now())))
    print("---------------------------------")
    print('Connected to: {}'.format(device))

    net = 'active-partition %s' % network
    net_connect.send_command_timing(net)

    '''Look for ip
    '''

    cmdip = 'show run | section %s' % (ipaddr)
    out = net_connect.send_command(cmdip)
    ports = re.findall('port\s(.*)', out)
    vip = re.findall('service-group\s(.*)', out)
    print(' ')
    print('Searching {} ports {}'.format(vip, ports))


    for m in vip:
        members = 'show slb service-group %s config | include Member' % (m)
        cmdmembers = net_connect.send_command(members)
        regex = re.findall(r'Member[0-9]:([^\t][^:]+)', cmdmembers)

        print(' ')
        print('Hosts for {} are:'.format(m))
        print(' ')
        for host in regex:
            host = host.strip()
            iphosts = 'show running-config | include %s' % (host)
            findhosts = net_connect.send_command(iphosts)
            hosts = re.findall('slb\sserver\s(.*)', findhosts)
            if hosts:
                print(hosts)

    print("---------------------------------")
开发者ID:pathcl,项目名称:scripts,代码行数:80,代码来源:a10vip.py

示例5: FrroutingDriver

# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import send_command_timing [as 别名]

#.........这里部分代码省略.........
        if filename is not None:
            with open(filename, 'r') as f:
                candidate = f.readlines()
        else:
            candidate = config

        if not isinstance(candidate, list):
            candidate = [candidate]

        candidate = [line for line in candidate if line]
        for command in candidate:
            if 'sudo' not in command:
                command = '{0}'.format(command)
            output = self._send_command(command)
            if "error" in output or "not found" in output:
                raise MergeConfigException("Command '{0}' cannot be applied.".format(command))

    def discard_config(self):
        return ''

    def compare_config(self):
        if self.loaded:
            diff = self._send_command('/usr/lib/frr/frr-reload.py --test /etc/frr/frr.conf')
            return re.sub('\x1b\[\d+m', '', diff)
        return ''

    def commit_config(self):
        if self.loaded:
            self._send_command('net commit')
            self.changed = True
            self.loaded = False

    def _send_command(self, command):
        response = self.device.send_command_timing(command)
        if '[sudo]' in response:
            response = self.device.send_command_timing(self.sudo_pwd)
        return response

    def get_config(self, retrieve='all'):
        configs = {
            'startup': '',
            'running': '',
            'candidate': '',
        }

        if retrieve in ('running', 'all'):
            command = 'vtysh -c "show running-config"'
            output = self._send_command(command)
            configs['running'] = output

        return configs

    def get_facts(self):
        facts = {
            'vendor': py23_compat.text_type('FRRouting')
        }

        # Get "net show hostname" output.
        hostname = self.device.send_command('hostname')

        uptime_output = self._send_command("cat /proc/uptime | awk '{print $1}'")
        uptime = int(float(uptime_output))

        os_version = self._send_command("vtysh -c 'show version'").split("\n")

        model = self._send_command("lsb_release -d | awk -F':' '{print $2}'").strip()
开发者ID:jpbe-network,项目名称:napalm-frrouting,代码行数:70,代码来源:frrouting.py


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