text
stringlengths
81
112k
Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity def sell(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and ...
Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity def sell_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)...
Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float Limit price def sell_limit(self, quantity, price, **kwarg...
Get the positions data for the instrument :Optional: attr : string Position attribute to get (optional attributes: symbol, position, avgCost, account) :Retruns: positions : dict (positions) / float/str (attribute) positions data f...
Modify quantity and/or limit price of an active order for the instrument :Parameters: orderId : int the order id to modify :Optional: quantity : int the required quantity of the modified order limit_price : int the new...
Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders only) target: float new target limit price (for unfilled limit orders only...
Modify stop order. Auto-discover **orderId** and **quantity** and invokes ``self.modify_order(...)``. :Parameters: stoploss : float the new stoploss limit price def move_stoploss(self, stoploss): """Modify stop order. Auto-discover **orderId** and **quantity...
Get margin requirements for intrument (futures only) :Retruns: margin : dict margin requirements for instrument (all values are ``None`` for non-futures instruments) def get_margin_requirement(self): """ Get margin requirements for intrument (futures only) ...
Get maximum contracts allowed to trade baed on required margin per contract and current account balance (futures only) :Parameters: overnight : bool Calculate based on Overnight margin (set to ``False`` to use Intraday margin req.) :Retruns: cont...
Check if instrument pnl is within given range :Parameters: min_pnl : flaot minimum session pnl (in USD / IB currency) max_pnl : flaot maximum session pnl (in USD / IB currency) :Retruns: status : bool if pnl is within ...
Parse a single entry from show interfaces output. Different cases: mgmt0 is up admin state is up Ethernet2/1 is up admin state is up, Dedicated Interface Vlan1 is down (Administratively down), line protocol is down, autostate enabled Ethernet154/1/48 is up (with no 'admin state') def pa...
Convert hh:mm:ss to seconds. def convert_hhmmss(hhmmss): """Convert hh:mm:ss to seconds.""" fields = hhmmss.split(":") if len(fields) != 3: raise ValueError("Received invalid HH:MM:SS data: {}".format(hhmmss)) fields = [int(x) for x in fields] hours, minutes, seconds = fields return (ho...
The 'show bgp all summary vrf all' table can have entries that wrap multiple lines. 2001:db8:4:701::2 4 65535 163664 163693 145 0 0 3w2d 3 2001:db8:e0:dd::1 4 10 327491 327278 145 0 0 3w1d 4 Normalize this so the line wrap doesn't exit. ...
Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM Example line: 10.2.1.14 4 10 472516 472238 361 0 0 3w1d 9 def bgp_table_parser(bgp_table): """Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM ...
Parse 'show bgp all summary vrf' output information from NX-OS devices. def bgp_summary_parser(bgp_summary): """Parse 'show bgp all summary vrf' output information from NX-OS devices.""" bgp_summary_dict = {} # Check for BGP summary information lines that have no data if len(bgp_summary.strip().splitl...
Wrapper for Netmiko's send_command method (for list of commands. def _send_command_list(self, commands): """Wrapper for Netmiko's send_command method (for list of commands.""" output = "" for command in commands: output += self.device.send_command( command, strip_pro...
Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer def parse_uptime(uptime_str): """ Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer """ # Initialize to zero ...
Returns a flag with the state of the SSH connection. def is_alive(self): """Returns a flag with the state of the SSH connection.""" null = chr(0) try: if self.device is None: return {"is_alive": False} else: # Try sending ASCII null byte t...
Return a set of facts from the devices. def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = "Cisco" uptime = -1 serial_number, fqdn, os_version, hostname, domain_name, model = ("",) * 6 # obtain output from device show_v...
Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, 'mac_address': u'a493.4cc1.67a7', ...
BGP neighbor information. Supports VRFs and IPv4 and IPv6 AFIs { "global": { "router_id": "1.1.1.103", "peers": { "10.99.99.2": { "is_enabled": true, "uptime": -1, "remote_as": 22, ...
Get environment facts. power and fan are currently not implemented cpu is using 1-minute average def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average """ environment = {} ...
Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, "ipv6": { "20...
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (boolean) * moves (int) * last...
BGP protocol attributes for get_route_tp Only IPv4 supported def _get_bgp_route_attr(self, destination, vrf, next_hop, ip_version=4): """ BGP protocol attributes for get_route_tp Only IPv4 supported """ CMD_SHIBNV = 'show ip bgp neighbors vrf {vrf} | include "is {neigh}...
Only IPv4 supported, vrf aware, longer_prefixes parameter ready def get_route_to(self, destination="", protocol=""): """ Only IPv4 supported, vrf aware, longer_prefixes parameter ready """ longer_pref = "" # longer_prefixes support, for future use vrf = "" ip_version =...
Standardized method of creating a Netmiko connection using napalm attributes. def _netmiko_open(self, device_type, netmiko_optional_args=None): """Standardized method of creating a Netmiko connection using napalm attributes.""" if netmiko_optional_args is None: netmiko_optional_args = {} ...
Will load a templated configuration on the device. :param cls: Instance of the driver class. :param template_name: Identifies the template name. :param template_source (optional): Custom config template rendered and loaded on device :param template_path (optional): Absolute path to dire...
Executes traceroute on the device and returns a dictionary with the result. :param destination: Host or IP Address of the destination :param source (optional): Use a specific IP Address to execute the traceroute :param ttl (optional): Maimum number of hops :param timeout (optional): Num...
Return a compliance report. Verify that the device complies with the given validation file and writes a compliance report file. See https://napalm.readthedocs.io/en/latest/validate/index.html. :param validation_file: Path to the file containing compliance definition. Default is None. :...
Expose the helper function within this class. def _canonical_int(self, interface): """Expose the helper function within this class.""" if self.use_canonical_interface is True: return napalm.base.helpers.canonical_interface_name( interface, addl_name_map=None ) ...
Open the connection with the device. def open(self): """Open the connection with the device.""" try: self.device.open() except ConnectTimeoutError as cte: raise ConnectionException(cte.msg) self.device.timeout = self.timeout self.device._conn._session.tra...
Close the connection. def close(self): """Close the connection.""" if not self.lock_disable and self.session_config_lock: self._unlock() self.device.close()
Lock the config DB. def _lock(self): """Lock the config DB.""" if not self.locked: try: self.device.cu.lock() self.locked = True except JnprLockError as jle: raise LockError(py23_compat.text_type(jle))
Unlock the config DB. def _unlock(self): """Unlock the config DB.""" if self.locked: try: self.device.cu.unlock() self.locked = False except JnrpUnlockError as jue: raise UnlockError(jue.messsage)
This allows you to construct an arbitrary RPC call to retreive common stuff. For example: Configuration: get: "<get-configuration/>" Interface information: get: "<get-interface-information/>" A particular interfacece information: get: "<get-interface-information/>" ...
Open the candidate config and merge. def load_replace_candidate(self, filename=None, config=None): """Open the candidate config and merge.""" self.config_replace = True self._load_candidate(filename, config, True)
Open the candidate config and replace. def load_merge_candidate(self, filename=None, config=None): """Open the candidate config and replace.""" self.config_replace = False self._load_candidate(filename, config, False)
Commit configuration. def commit_config(self, message=""): """Commit configuration.""" commit_args = {"comment": message} if message else {} self.device.cu.commit(ignore_warning=self.ignore_warning, **commit_args) if not self.lock_disable and not self.session_config_lock: se...
Discard changes (rollback 0). def discard_config(self): """Discard changes (rollback 0).""" self.device.cu.rollback(rb_id=0) if not self.lock_disable and not self.session_config_lock: self._unlock()
Return interfaces details. def get_interfaces(self): """Return interfaces details.""" result = {} interfaces = junos_views.junos_iface_table(self.device) interfaces.get() interfaces_logical = junos_views.junos_logical_iface_table(self.device) interfaces_logical.get() ...
Return interfaces counters. def get_interfaces_counters(self): """Return interfaces counters.""" query = junos_views.junos_iface_counter_table(self.device) query.get() interface_counters = {} for interface, counters in query.items(): interface_counters[interface] = {...
Return environment details. def get_environment(self): """Return environment details.""" environment = junos_views.junos_environment_table(self.device) routing_engine = junos_views.junos_routing_engine_table(self.device) temperature_thresholds = junos_views.junos_temperature_thresholds(...
Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family def _get_address_family(table, instance): """ Function to derive address family from a junos table name. :params table: The name of the routing tabl...
Detailed view of the LLDP neighbors. def get_lldp_neighbors_detail(self, interface=""): """Detailed view of the LLDP neighbors.""" lldp_neighbors = defaultdict(list) lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device) if not interface: try: ...
Execute raw CLI commands and returns their output. def cli(self, commands): """Execute raw CLI commands and returns their output.""" cli_output = {} def _count(txt, none): # Second arg for consistency only. noqa """ Return the exact output, as Junos displays ...
Return BGP configuration. def get_bgp_config(self, group="", neighbor=""): """Return BGP configuration.""" def _check_nhs(policies, nhs_policies): if not isinstance(policies, list): # Make it a list if it is a single policy policies = [policies] ...
Detailed view of the BGP neighbors operational data. def get_bgp_neighbors_detail(self, neighbor_address=""): """Detailed view of the BGP neighbors operational data.""" bgp_neighbors = {} default_neighbor_details = { "up": False, "local_as": 0, "remote_as": 0...
Return the ARP table. def get_arp_table(self, vrf=""): """Return the ARP table.""" # could use ArpTable # from jnpr.junos.op.phyport import ArpTable # and simply use it # but # we need: # - filters # - group by VLAN ID # - hostname & TTE fie...
Return the IPv6 neighbors table. def get_ipv6_neighbors_table(self): """Return the IPv6 neighbors table.""" ipv6_neighbors_table = [] ipv6_neighbors_table_raw = junos_views.junos_ipv6_neighbors_table(self.device) ipv6_neighbors_table_raw.get() ipv6_neighbors_table_items = ipv6_...
Return NTP stats (associations). def get_ntp_stats(self): """Return NTP stats (associations).""" # NTP Peers does not have XML RPC defined # thus we need to retrieve raw text and parse... # :( ntp_stats = [] REGEX = ( r"^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)" ...
Return the configured IP addresses. def get_interfaces_ip(self): """Return the configured IP addresses.""" interfaces_ip = {} interface_table = junos_views.junos_ip_interfaces_table(self.device) interface_table.get() interface_table_items = interface_table.items() _FAM...
Return the MAC address table. def get_mac_address_table(self): """Return the MAC address table.""" mac_address_table = [] switch_style = self.device.facts.get("switch_style", "") if switch_style == "VLAN_L2NG": mac_table = junos_views.junos_mac_address_table_switch_l2ng(sel...
Return route details to a specific destination, learned from a certain protocol. def get_route_to(self, destination="", protocol=""): """Return route details to a specific destination, learned from a certain protocol.""" routes = {} if not isinstance(destination, py23_compat.string_types): ...
Return the SNMP configuration. def get_snmp_information(self): """Return the SNMP configuration.""" snmp_information = {} snmp_config = junos_views.junos_snmp_config_table(self.device) snmp_config.get() snmp_items = snmp_config.items() if not snmp_items: re...
get root user password. def _get_root(self): """get root user password.""" _DEFAULT_USER_DETAILS = {"level": 20, "password": "", "sshkeys": []} root = {} root_table = junos_views.junos_root_table(self.device) root_table.get() root_items = root_table.items() for u...
Return the configuration of the users. def get_users(self): """Return the configuration of the users.""" users = {} _JUNOS_CLASS_CISCO_PRIVILEGE_LEVEL_MAP = { "super-user": 15, "superuser": 15, "operator": 5, "read-only": 1, "unauthor...
Return optics information. def get_optics(self): """Return optics information.""" optics_table = junos_views.junos_intf_optics_table(self.device) optics_table.get() optics_items = optics_table.items() # optics_items has no lane information, so we need to re-format data ...
Dynamically create PY3 version of the file by re-writing 'unicode' to 'str'. def _preprocess_yml(path): """Dynamically create PY3 version of the file by re-writing 'unicode' to 'str'.""" with open(path) as f: tmp_yaml = f.read() return re.sub(r"unicode", "str", tmp_yaml)
Use CiscoConfParse to find parent lines that contain a specific child line. :param parent: The parent line to search for :param child: The child line required under the given parent :param config: The device running/startup config def cisco_conf_parse_parents(parent, child, config): """ Use Cisco...
Use CiscoConfParse to find and return a section of Cisco IOS config. Similar to "show run | section <cfg_section>" :param cfg_section: The section of the config to return eg. "router bgp" :param config: The running/startup config of the device to parse def cisco_conf_parse_objects(cfg_section, config): ...
RegEx search for pattern in text. Will try to match the data type of the "default" value or return the default value if no match is found. This is to parse IOS config like below: regex_find_txt(r"remote-as (65000)", "neighbor 10.0.0.1 remote-as 65000", default=0) RETURNS: 65001 :param pattern: RegE...
Applies a TextFSM template over a raw text and return the matching table. Main usage of this method will be to extract data form a non-structured output from a network device and return the values in a table format. :param cls: Instance of the driver class :param template_name: Specifies the name of t...
Converts a raw string to a valid IP address. Optional version argument will detect that \ object matches specified version. Motivation: the groups of the IP addreses may contain leading zeros. IPv6 addresses can \ contain sometimes uppercase characters. E.g.: 2001:0dB8:85a3:0000:0000:8A2e:0370:7334 has \ ...
Convert AS Number to standardized asplain notation as an integer. def as_number(as_number_val): """Convert AS Number to standardized asplain notation as an integer.""" as_number_str = py23_compat.text_type(as_number_val) if "." in as_number_str: big, little = as_number_str.split(".") return...
Split an interface name based on first digit, slash, or space match. def split_interface(intf_name): """Split an interface name based on first digit, slash, or space match.""" head = intf_name.rstrip(r"/\0123456789. ") tail = intf_name[len(head) :].lstrip() return (head, tail)
Function to return an interface's canonical name (fully expanded name). Use of explicit matches used to indicate a clear understanding on any potential match. Regex and other looser matching methods were not implmented to avoid false positive matches. As an example, it would make sense to do "[P|p][O|o]" w...
Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/value pairs that updates the base mapping. Used if an OS has specific differences. e.g. {"Po": "PortChannel"} vs ...
Close the connection to the device and do the necessary cleanup. def close(self): """Close the connection to the device and do the necessary cleanup.""" # Return file prompt quiet to the original state if self.auto_file_prompt and self.prompt_quiet_changed is True: self.device.send...
Wrapper for self.device.send.command(). If command is a list will iterate through commands until valid command. def _send_command(self, command): """Wrapper for self.device.send.command(). If command is a list will iterate through commands until valid command. """ try: ...
Returns a flag with the state of the connection. def is_alive(self): """Returns a flag with the state of the connection.""" null = chr(0) if self.device is None: return {"is_alive": False} if self.transport == "telnet": try: # Try sending IAC + NO...
Filter out strings that should not show up in the diff. def _normalize_compare_config(self, diff): """Filter out strings that should not show up in the diff.""" ignore_strings = [ "Contextual Config Diffs", "No changes were found", "ntp clock-period", ] ...
Make the compare config output look better. Cisco IOS incremental-diff output No changes: !List of Commands: end !No changes were found def _normalize_merge_diff_incr(diff): """Make the compare config output look better. Cisco IOS incremental-diff output ...
Make compare_config() for merge look similar to replace config diff. def _normalize_merge_diff(diff): """Make compare_config() for merge look similar to replace config diff.""" new_diff = [] for line in diff.splitlines(): # Filter blank lines and prepend +sign if line.st...
show archive config differences <base_file> <new_file>. Default operation is to compare system:running-config to self.candidate_cfg def compare_config(self): """ show archive config differences <base_file> <new_file>. Default operation is to compare system:running-config to self.candi...
Decorator to toggle 'file prompt quiet' for methods that perform file operations. def _file_prompt_quiet(f): """Decorator to toggle 'file prompt quiet' for methods that perform file operations.""" @functools.wraps(f) def wrapper(self, *args, **kwargs): if not self.prompt_quiet_conf...
Special handler for hostname change on commit operation. Also handles username removal which prompts for confirmation (username removal prompts for each user...) def _commit_handler(self, cmd): """ Special handler for hostname change on commit operation. Also handles username removal wh...
If replacement operation, perform 'configure replace' for the entire config. If merge operation, perform copy <file> running-config. def commit_config(self, message=""): """ If replacement operation, perform 'configure replace' for the entire config. If merge operation, perform copy <...
Set candidate_cfg to current running-config. Erase the merge_cfg file. def _discard_config(self): """Set candidate_cfg to current running-config. Erase the merge_cfg file.""" discard_candidate = "copy running-config {}".format( self._gen_full_path(self.candidate_cfg) ) disca...
Rollback configuration to filename or to self.rollback_cfg file. def rollback(self): """Rollback configuration to filename or to self.rollback_cfg file.""" filename = self.rollback_cfg cfg_file = self._gen_full_path(filename) if not self._check_file_exists(cfg_file): raise R...
Use Netmiko InlineFileTransfer (TCL) to transfer file or config to remote device. Return (status, msg) status = boolean msg = details on what happened def _inline_tcl_xfer( self, source_file=None, source_config=None, dest_file=None, file_system=None ): """ Use Netmi...
SCP file to remote device. Return (status, msg) status = boolean msg = details on what happened def _scp_file(self, source_file, dest_file, file_system): """ SCP file to remote device. Return (status, msg) status = boolean msg = details on what happened...
Transfer file to remote device. By default, this will use Secure Copy if self.inline_transfer is set, then will use Netmiko InlineTransfer method to transfer inline using either SSH or telnet (plus TCL onbox). Return (status, msg) status = boolean msg = details on what ...
Cleanup actions on send_command() for NAPALM getters. Remove "Load for five sec; one minute if in output" Remove "Time source is" def _send_command_postprocess(output): """ Cleanup actions on send_command() for NAPALM getters. Remove "Load for five sec; one minute if in output...
Get interface ip details. Returns a dict of dicts Example Output: { u'FastEthernet8': { 'ipv4': { u'10.66.43.169': { 'prefix_length': 22}}}, u'Loopback555': { 'ipv4': { u'192.168.1.1': { 'prefix_length': 24}}, 'ipv6': { u'1::1': { ...
Parse BGP config params into a dict :param group='': :param neighbor='': def get_bgp_config(self, group="", neighbor=""): """ Parse BGP config params into a dict :param group='': :param neighbor='': """ bgp_config = {} def build_...
BGP neighbor information. Currently no VRF support. Supports both IPv4 and IPv6. def get_bgp_neighbors(self): """BGP neighbor information. Currently no VRF support. Supports both IPv4 and IPv6. """ supported_afi = ["ipv4", "ipv6"] bgp_neighbor_data = dict() bg...
Return interface counters and errors. 'tx_errors': int, 'rx_errors': int, 'tx_discards': int, 'rx_discards': int, 'tx_octets': int, 'rx_octets': int, 'tx_unicast_packets': int, 'rx_unicast_packets': int, 'tx_multicast_packets': int, 'rx_mu...
Get environment facts. power and fan are currently not implemented cpu is using 1-minute average cpu hard-coded to cpu0 (i.e. only a single CPU) def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-min...
Implementation of get_ntp_peers for IOS. def get_ntp_peers(self): """Implementation of get_ntp_peers for IOS.""" ntp_stats = self.get_ntp_stats() return { ntp_peer.get("remote"): {} for ntp_peer in ntp_stats if ntp_peer.get("remote") }
Implementation of get_ntp_servers for IOS. Returns the NTP servers configuration as dictionary. The keys of the dictionary represent the IP Addresses of the servers. Inner dictionaries do not have yet any available keys. Example:: { '192.168.0.1': {}, ...
Implementation of get_ntp_stats for IOS. def get_ntp_stats(self): """Implementation of get_ntp_stats for IOS.""" ntp_stats = [] command = "show ntp associations" output = self._send_command(command) for line in output.splitlines(): # Skip first two lines and last l...
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (boolean) * moves (int) * last...
Returns a dict of dicts Example Output: { 'chassis_id': u'Asset Tag 54670', 'community': { u'private': { 'acl': u'12', 'mode': u'rw'}, u'public': { 'acl': u'11', 'mode': u'ro'}, u'public_named_acl': { 'acl': u'ALLOW-SNMP-ACL', ...
Returns a dictionary with the configured users. The keys of the main dictionary represents the username. The values represent the details of the user, represented by the following keys: * level (int) * password (str) * sshkeys (list) *Note: sshkeys o...
Execute ping on the device and returns a dictionary with the result. Output dictionary has one of following keys: * success * error In case of success, inner dictionary will have the followin keys: * probes_sent (int) * packet_loss (int) * rtt...
Get IPv6 neighbors table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) in seconds * state (string) For example:: [ { ...
Implementation of NAPALM method open. def open(self): """Implementation of NAPALM method open.""" try: connection = self.transport_class( host=self.hostname, username=self.username, password=self.password, timeout=self.timeout,...
Converts running-config HEREDOC into EAPI JSON dict def _multiline_convert(config, start="banner login", end="EOF", depth=1): """Converts running-config HEREDOC into EAPI JSON dict""" ret = list(config) # Don't modify list in-place try: s = ret.index(start) e = s ...
EOS has the concept of multi-line mode comments, shown in the running-config as being inside a config stanza (router bgp, ACL definition, etc) and beginning with the normal level of spaces and '!!', followed by comments. Unfortunately, pyeapi does not accept mode comments in this format, and ha...