text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
Calculates the frequency of at most nbits logical zeros and returns the mean of these frequencies
<END_TASK>
<USER_TASK:>
Description:
def estimate_frequency_for_zero(self, sample_rate: float, nbits=42) -> float:
"""
Calculates the frequency of at most nbits logical zeros and returns the ... |
return self.__estimate_frequency_for_bit(False, sample_rate, nbits) |
<SYSTEM_TASK:>
Return the most frequent value in list.
<END_TASK>
<USER_TASK:>
Description:
def get_most_frequent_value(values: list):
"""
Return the most frequent value in list.
If there is no unique one, return the maximum of the most frequent values
:param values:
:return:
""" |
if len(values) == 0:
return None
most_common = Counter(values).most_common()
result, max_count = most_common[0]
for value, count in most_common:
if count < max_count:
return result
else:
result = value
return result |
<SYSTEM_TASK:>
Get the list of start, end indices of messages
<END_TASK>
<USER_TASK:>
Description:
def segment_messages_from_magnitudes(magnitudes: np.ndarray, noise_threshold: float):
"""
Get the list of start, end indices of messages
:param magnitudes: Magnitudes of samples
:param noise_threshold: Th... |
return c_auto_interpretation.segment_messages_from_magnitudes(magnitudes, noise_threshold) |
<SYSTEM_TASK:>
returns a string of new device messages separated by newlines
<END_TASK>
<USER_TASK:>
Description:
def read_messages(self) -> str:
"""
returns a string of new device messages separated by newlines
:return:
""" |
if self.backend == Backends.grc:
errors = self.__dev.read_errors()
if "FATAL: " in errors:
self.fatal_error_occurred.emit(errors[errors.index("FATAL: "):])
return errors
elif self.backend == Backends.native:
messages = "\n".join(self.__d... |
<SYSTEM_TASK:>
Convenience function for creating a ready-to-go CloudflareScraper object.
<END_TASK>
<USER_TASK:>
Description:
def create_scraper(cls, sess=None, **kwargs):
"""
Convenience function for creating a ready-to-go CloudflareScraper object.
""" |
scraper = cls(**kwargs)
if sess:
attrs = ["auth", "cert", "cookies", "headers", "hooks", "params", "proxies", "data"]
for attr in attrs:
val = getattr(sess, attr, None)
if val:
setattr(scraper, attr, val)
return scrap... |
<SYSTEM_TASK:>
Adding a delay after login.
<END_TASK>
<USER_TASK:>
Description:
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login.""" |
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor) |
<SYSTEM_TASK:>
Use threads and Netmiko to connect to each of the devices. Execute
<END_TASK>
<USER_TASK:>
Description:
def main():
"""
Use threads and Netmiko to connect to each of the devices. Execute
'show version' on each device. Record the amount of time required to do this.
""" |
start_time = datetime.now()
for a_device in devices:
my_thread = threading.Thread(target=show_version, args=(a_device,))
my_thread.start()
main_thread = threading.currentThread()
for some_thread in threading.enumerate():
if some_thread != main_thread:
print(some_th... |
<SYSTEM_TASK:>
Establish the secure copy connection.
<END_TASK>
<USER_TASK:>
Description:
def establish_scp_conn(self):
"""Establish the secure copy connection.""" |
ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()
self.scp_conn = self.ssh_ctl_chan._build_ssh_client()
self.scp_conn.connect(**ssh_connect_params)
self.scp_client = scp.SCPClient(self.scp_conn.get_transport()) |
<SYSTEM_TASK:>
Compare md5 of file on network device to md5 of local file.
<END_TASK>
<USER_TASK:>
Description:
def compare_md5(self):
"""Compare md5 of file on network device to md5 of local file.""" |
if self.direction == "put":
remote_md5 = self.remote_md5()
return self.source_md5 == remote_md5
elif self.direction == "get":
local_md5 = self.file_md5(self.dest_file)
return self.source_md5 == local_md5 |
<SYSTEM_TASK:>
SCP copy the file from the local system to the remote device.
<END_TASK>
<USER_TASK:>
Description:
def put_file(self):
"""SCP copy the file from the local system to the remote device.""" |
destination = "{}/{}".format(self.file_system, self.dest_file)
self.scp_conn.scp_transfer_file(self.source_file, destination)
# Must close the SCP connection to get the file written (flush)
self.scp_conn.close() |
<SYSTEM_TASK:>
Enable SCP on remote device.
<END_TASK>
<USER_TASK:>
Description:
def enable_scp(self, cmd=None):
"""
Enable SCP on remote device.
Defaults to Cisco IOS command
""" |
if cmd is None:
cmd = ["ip scp server enable"]
elif not hasattr(cmd, "__iter__"):
cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd) |
<SYSTEM_TASK:>
Disable SCP on remote device.
<END_TASK>
<USER_TASK:>
Description:
def disable_scp(self, cmd=None):
"""
Disable SCP on remote device.
Defaults to Cisco IOS command
""" |
if cmd is None:
cmd = ["no ip scp server enable"]
elif not hasattr(cmd, "__iter__"):
cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd) |
<SYSTEM_TASK:>
Strip command_string from output string.
<END_TASK>
<USER_TASK:>
Description:
def strip_command(self, command_string, output):
"""Strip command_string from output string.""" |
output_list = output.split(command_string)
return self.RESPONSE_RETURN.join(output_list) |
<SYSTEM_TASK:>
Palo Alto requires an extra delay
<END_TASK>
<USER_TASK:>
Description:
def send_command(self, *args, **kwargs):
"""Palo Alto requires an extra delay""" |
kwargs["delay_factor"] = kwargs.get("delay_factor", 2.5)
return super(PaloAltoPanosBase, self).send_command(*args, **kwargs) |
<SYSTEM_TASK:>
Prepare the session after the connection has been established.
<END_TASK>
<USER_TASK:>
Description:
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Extra time to read HP banners.
""" |
delay_factor = self.select_delay_factor(delay_factor=0)
i = 1
while i <= 4:
# Comware can have a banner that prompts you to continue
# 'Press Y or ENTER to continue, N to exit.'
time.sleep(0.5 * delay_factor)
self.write_channel("\n")
i... |
<SYSTEM_TASK:>
Try to send an SNMP GET operation using SNMPv3 for the specified OID.
<END_TASK>
<USER_TASK:>
Description:
def _get_snmpv3(self, oid):
"""
Try to send an SNMP GET operation using SNMPv3 for the specified OID.
Parameters
----------
oid : str
The SNMP OI... |
snmp_target = (self.hostname, self.snmp_port)
cmd_gen = cmdgen.CommandGenerator()
(error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd(
cmdgen.UsmUserData(
self.user,
self.auth_key,
self.encrypt_key,
... |
<SYSTEM_TASK:>
Try to send an SNMP GET operation using SNMPv2 for the specified OID.
<END_TASK>
<USER_TASK:>
Description:
def _get_snmpv2c(self, oid):
"""
Try to send an SNMP GET operation using SNMPv2 for the specified OID.
Parameters
----------
oid : str
The SNMP O... |
snmp_target = (self.hostname, self.snmp_port)
cmd_gen = cmdgen.CommandGenerator()
(error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd(
cmdgen.CommunityData(self.community),
cmdgen.UdpTransportTarget(snmp_target, timeout=1.5, retries=2),
o... |
<SYSTEM_TASK:>
Use Netmiko to execute show version. Use a queue to pass the data back to
<END_TASK>
<USER_TASK:>
Description:
def show_version_queue(a_device, output_q):
"""
Use Netmiko to execute show version. Use a queue to pass the data back to
the main process.
""" |
output_dict = {}
remote_conn = ConnectHandler(**a_device)
hostname = remote_conn.base_prompt
output = ("#" * 80) + "\n"
output += remote_conn.send_command("show version") + "\n"
output += ("#" * 80) + "\n"
output_dict[hostname] = output
output_q.put(output_dict) |
<SYSTEM_TASK:>
Use processes and Netmiko to connect to each of the devices. Execute
<END_TASK>
<USER_TASK:>
Description:
def main():
"""
Use processes and Netmiko to connect to each of the devices. Execute
'show version' on each device. Use a queue to pass the output back to the parent process.
Record t... |
start_time = datetime.now()
output_q = Queue(maxsize=20)
procs = []
for a_device in devices:
my_proc = Process(target=show_version_queue, args=(a_device, output_q))
my_proc.start()
procs.append(my_proc)
# Make sure all processes have finished
for a_proc in procs:
... |
<SYSTEM_TASK:>
IOS-XR requires you not exit from configuration mode.
<END_TASK>
<USER_TASK:>
Description:
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
"""IOS-XR requires you not exit from configuration mode.""" |
return super(CiscoXrSSH, self).send_config_set(
config_commands=config_commands, exit_config_mode=False, **kwargs
) |
<SYSTEM_TASK:>
SCP copy the file from the remote device to local system.
<END_TASK>
<USER_TASK:>
Description:
def get_file(self):
"""SCP copy the file from the remote device to local system.""" |
source_file = "{}".format(self.source_file)
self.scp_conn.scp_get_file(source_file, self.dest_file)
self.scp_conn.close() |
<SYSTEM_TASK:>
Returns the row number that matches the supplied attributes.
<END_TASK>
<USER_TASK:>
Description:
def GetRowMatch(self, attributes):
"""Returns the row number that matches the supplied attributes.""" |
for row in self.compiled:
try:
for key in attributes:
# Silently skip attributes not present in the index file.
# pylint: disable=E1103
if (
key in row.header
and row[key]
... |
<SYSTEM_TASK:>
Parses a string of templates into a list of file handles.
<END_TASK>
<USER_TASK:>
Description:
def _TemplateNamesToFiles(self, template_str):
"""Parses a string of templates into a list of file handles.""" |
template_list = template_str.split(":")
template_files = []
try:
for tmplt in template_list:
template_files.append(open(os.path.join(self.template_dir, tmplt), "r"))
except: # noqa
for tmplt in template_files:
tmplt.close()
... |
<SYSTEM_TASK:>
Overrides sort func to use the KeyValue for the key.
<END_TASK>
<USER_TASK:>
Description:
def sort(self, cmp=None, key=None, reverse=False):
"""Overrides sort func to use the KeyValue for the key.""" |
if not key and self._keys:
key = self.KeyValue
super(CliTable, self).sort(cmp=cmp, key=key, reverse=reverse) |
<SYSTEM_TASK:>
Returns a set of column names that together constitute the superkey.
<END_TASK>
<USER_TASK:>
Description:
def superkey(self):
"""Returns a set of column names that together constitute the superkey.""" |
sorted_list = []
for header in self.header:
if header in self._keys:
sorted_list.append(header)
return sorted_list |
<SYSTEM_TASK:>
Returns the super key value for the row.
<END_TASK>
<USER_TASK:>
Description:
def KeyValue(self, row=None):
"""Returns the super key value for the row.""" |
if not row:
if self._iterator:
# If we are inside an iterator use current row iteration.
row = self[self._iterator]
else:
row = self.row
# If no superkey then use row number.
if not self.superkey:
return ["%s" %... |
<SYSTEM_TASK:>
Run zsh command to unify the environment
<END_TASK>
<USER_TASK:>
Description:
def zsh_mode(self, delay_factor=1, prompt_terminator="$"):
"""Run zsh command to unify the environment""" |
delay_factor = self.select_delay_factor(delay_factor)
self.clear_buffer()
command = self.RETURN + "zsh" + self.RETURN
self.write_channel(command)
time.sleep(1 * delay_factor)
self.set_prompt()
self.clear_buffer() |
<SYSTEM_TASK:>
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
<END_TASK>
<USER_TASK:>
Description:
def autodetect(self):
"""
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
Returns
-------
best_match : str or Non... |
for device_type, autodetect_dict in SSH_MAPPER_BASE.items():
tmp_dict = autodetect_dict.copy()
call_method = tmp_dict.pop("dispatch")
autodetect_method = getattr(self, call_method)
accuracy = autodetect_method(**tmp_dict)
if accuracy:
... |
<SYSTEM_TASK:>
Send command to the remote device with a caching feature to avoid sending the same command
<END_TASK>
<USER_TASK:>
Description:
def _send_command_wrapper(self, cmd):
"""
Send command to the remote device with a caching feature to avoid sending the same command
twice based on the S... |
cached_results = self._results_cache.get(cmd)
if not cached_results:
response = self._send_command(cmd)
self._results_cache[cmd] = response
return response
else:
return cached_results |
<SYSTEM_TASK:>
Factory function selects the proper class and creates object based on device_type.
<END_TASK>
<USER_TASK:>
Description:
def ConnectHandler(*args, **kwargs):
"""Factory function selects the proper class and creates object based on device_type.""" |
if kwargs["device_type"] not in platforms:
raise ValueError(
"Unsupported device_type: "
"currently supported platforms are: {}".format(platforms_str)
)
ConnectionClass = ssh_dispatcher(kwargs["device_type"])
return ConnectionClass(*args, **kwargs) |
<SYSTEM_TASK:>
Dynamically change Netmiko object's class to proper class.
<END_TASK>
<USER_TASK:>
Description:
def redispatch(obj, device_type, session_prep=True):
"""Dynamically change Netmiko object's class to proper class.
Generally used with terminal_server device_type when you need to redispatch after int... |
new_class = ssh_dispatcher(device_type)
obj.device_type = device_type
obj.__class__ = new_class
if session_prep:
obj._try_session_preparation() |
<SYSTEM_TASK:>
Factory function selects the proper SCP class and creates object based on device_type.
<END_TASK>
<USER_TASK:>
Description:
def FileTransfer(*args, **kwargs):
"""Factory function selects the proper SCP class and creates object based on device_type.""" |
if len(args) >= 1:
device_type = args[0].device_type
else:
device_type = kwargs["ssh_conn"].device_type
if device_type not in scp_platforms:
raise ValueError(
"Unsupported SCP device_type: "
"currently supported platforms are: {}".format(scp_platforms_str)
... |
<SYSTEM_TASK:>
Checks if the device is in configuration mode
<END_TASK>
<USER_TASK:>
Description:
def check_config_mode(self, check_string=")#", pattern=""):
"""Checks if the device is in configuration mode""" |
return super(CalixB6Base, self).check_config_mode(check_string=check_string) |
<SYSTEM_TASK:>
Save Config on Mellanox devices Enters and Leaves Config Mode
<END_TASK>
<USER_TASK:>
Description:
def save_config(
self, cmd="configuration write", confirm=False, confirm_response=""
):
"""Save Config on Mellanox devices Enters and Leaves Config Mode""" |
output = self.enable()
output += self.config_mode()
output += self.send_command(cmd)
output += self.exit_config_mode()
return output |
<SYSTEM_TASK:>
RAD presents with the following on login
<END_TASK>
<USER_TASK:>
Description:
def telnet_login(
self, username_pattern=r"(?:user>)", alt_prompt_term=r"#\s*$", **kwargs
):
"""
RAD presents with the following on login
user>
password> ****
""" |
self.TELNET_RETURN = self.RETURN
return super(RadETXTelnet, self).telnet_login(
username_pattern=username_pattern,
alt_prompt_terminator=alt_prompt_term,
**kwargs
) |
<SYSTEM_TASK:>
Enter configuration mode.
<END_TASK>
<USER_TASK:>
Description:
def config_mode(self, config_command="configure", pattern=r"[edit]"):
"""Enter configuration mode.""" |
return super(VyOSSSH, self).config_mode(
config_command=config_command, pattern=pattern
) |
<SYSTEM_TASK:>
Remain in configuration mode.
<END_TASK>
<USER_TASK:>
Description:
def send_config_set(
self,
config_commands=None,
exit_config_mode=False,
delay_factor=1,
max_loops=150,
strip_prompt=False,
strip_command=False,
config_mode_command=None,
... |
return super(VyOSSSH, self).send_config_set(
config_commands=config_commands,
exit_config_mode=exit_config_mode,
delay_factor=delay_factor,
max_loops=max_loops,
strip_prompt=strip_prompt,
strip_command=strip_command,
config_mod... |
<SYSTEM_TASK:>
Autodetect the file system on the remote device. Used by SCP operations.
<END_TASK>
<USER_TASK:>
Description:
def _autodetect_fs(self, cmd="dir", pattern=r"Directory of (.*)/"):
"""Autodetect the file system on the remote device. Used by SCP operations.""" |
if not self.check_enable_mode():
raise ValueError("Must be in enable mode to auto-detect the file-system.")
output = self.send_command_expect(cmd)
match = re.search(pattern, output)
if match:
file_system = match.group(1)
# Test file_system
... |
<SYSTEM_TASK:>
Raise NetMikoTimeoutException if waiting too much in the serving queue.
<END_TASK>
<USER_TASK:>
Description:
def _timeout_exceeded(self, start, msg="Timeout exceeded!"):
"""Raise NetMikoTimeoutException if waiting too much in the serving queue.
:param start: Initial start time to see if ... |
if not start:
# Must provide a comparison time
return False
if time.time() - start > self.session_timeout:
# session_timeout exceeded
raise NetMikoTimeoutException(msg)
return False |
<SYSTEM_TASK:>
Try to acquire the Netmiko session lock. If not available, wait in the queue until
<END_TASK>
<USER_TASK:>
Description:
def _lock_netmiko_session(self, start=None):
"""Try to acquire the Netmiko session lock. If not available, wait in the queue until
the channel is available again.
... |
if not start:
start = time.time()
# Wait here until the SSH channel lock is acquired or until session_timeout exceeded
while not self._session_locker.acquire(False) and not self._timeout_exceeded(
start, "The netmiko channel is not available!"
):
time... |
<SYSTEM_TASK:>
Returns a boolean flag with the state of the connection.
<END_TASK>
<USER_TASK:>
Description:
def is_alive(self):
"""Returns a boolean flag with the state of the connection.""" |
null = chr(0)
if self.remote_conn is None:
log.error("Connection is not initialised, is_alive returns False")
return False
if self.protocol == "telnet":
try:
# Try sending IAC + NOP (IAC is telnet way of sending command)
# IAC ... |
<SYSTEM_TASK:>
Function that reads channel until pattern is detected.
<END_TASK>
<USER_TASK:>
Description:
def _read_channel_expect(self, pattern="", re_flags=0, max_loops=150):
"""Function that reads channel until pattern is detected.
pattern takes a regular expression.
By default pattern wil... |
output = ""
if not pattern:
pattern = re.escape(self.base_prompt)
log.debug("Pattern is: {}".format(pattern))
i = 1
loop_delay = 0.1
# Default to making loop time be roughly equivalent to self.timeout (support old max_loops
# argument for backwards c... |
<SYSTEM_TASK:>
Read data on the channel based on timing delays.
<END_TASK>
<USER_TASK:>
Description:
def _read_channel_timing(self, delay_factor=1, max_loops=150):
"""Read data on the channel based on timing delays.
Attempt to read channel max_loops number of times. If no data this will cause a 15 seco... |
# Time to delay in each read loop
loop_delay = 0.1
final_delay = 2
# Default to making loop time be roughly equivalent to self.timeout (support old max_loops
# and delay_factor arguments for backwards compatibility).
delay_factor = self.select_delay_factor(delay_factor)... |
<SYSTEM_TASK:>
Read until either self.base_prompt or pattern is detected.
<END_TASK>
<USER_TASK:>
Description:
def read_until_prompt_or_pattern(self, pattern="", re_flags=0):
"""Read until either self.base_prompt or pattern is detected.
:param pattern: the pattern used to identify that the output is co... |
combined_pattern = re.escape(self.base_prompt)
if pattern:
combined_pattern = r"({}|{})".format(combined_pattern, pattern)
return self._read_channel_expect(combined_pattern, re_flags=re_flags) |
<SYSTEM_TASK:>
Update SSH connection parameters based on contents of SSH 'config' file.
<END_TASK>
<USER_TASK:>
Description:
def _use_ssh_config(self, dict_arg):
"""Update SSH connection parameters based on contents of SSH 'config' file.
:param dict_arg: Dictionary of SSH connection parameters
... |
connect_dict = dict_arg.copy()
# Use SSHConfig to generate source content.
full_path = path.abspath(path.expanduser(self.ssh_config_file))
if path.exists(full_path):
ssh_config_instance = paramiko.SSHConfig()
with io.open(full_path, "rt", encoding="utf-8") as f:... |
<SYSTEM_TASK:>
Generate dictionary of Paramiko connection parameters.
<END_TASK>
<USER_TASK:>
Description:
def _connect_params_dict(self):
"""Generate dictionary of Paramiko connection parameters.""" |
conn_dict = {
"hostname": self.host,
"port": self.port,
"username": self.username,
"password": self.password,
"look_for_keys": self.use_keys,
"allow_agent": self.allow_agent,
"key_filename": self.key_file,
"pkey": s... |
<SYSTEM_TASK:>
Strip out command echo, trailing router prompt and ANSI escape codes.
<END_TASK>
<USER_TASK:>
Description:
def _sanitize_output(
self, output, strip_command=False, command_string=None, strip_prompt=False
):
"""Strip out command echo, trailing router prompt and ANSI escape codes.
... |
if self.ansi_escape_codes:
output = self.strip_ansi_escape_codes(output)
output = self.normalize_linefeeds(output)
if strip_command and command_string:
command_string = self.normalize_linefeeds(command_string)
output = self.strip_command(command_string, outpu... |
<SYSTEM_TASK:>
Establish SSH connection to the network device
<END_TASK>
<USER_TASK:>
Description:
def establish_connection(self, width=None, height=None):
"""Establish SSH connection to the network device
Timeout will generate a NetMikoTimeoutException
Authentication failure will generate a Ne... |
if self.protocol == "telnet":
self.remote_conn = telnetlib.Telnet(
self.host, port=self.port, timeout=self.timeout
)
self.telnet_login()
elif self.protocol == "serial":
self.remote_conn = serial.Serial(**self.serial_settings)
s... |
<SYSTEM_TASK:>
CLI terminals try to automatically adjust the line based on the width of the terminal.
<END_TASK>
<USER_TASK:>
Description:
def set_terminal_width(self, command="", delay_factor=1):
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the o... |
if not command:
return ""
delay_factor = self.select_delay_factor(delay_factor)
command = self.normalize_cmd(command)
self.write_channel(command)
output = self.read_until_prompt()
if self.ansi_escape_codes:
output = self.strip_ansi_escape_codes(ou... |
<SYSTEM_TASK:>
Finds the current network device prompt, last line only.
<END_TASK>
<USER_TASK:>
Description:
def find_prompt(self, delay_factor=1):
"""Finds the current network device prompt, last line only.
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int
... |
delay_factor = self.select_delay_factor(delay_factor)
self.clear_buffer()
self.write_channel(self.RETURN)
time.sleep(delay_factor * 0.1)
# Initial attempt to get prompt
prompt = self.read_channel()
if self.ansi_escape_codes:
prompt = self.strip_ansi_... |
<SYSTEM_TASK:>
Execute command_string on the SSH channel using a delay-based mechanism. Generally
<END_TASK>
<USER_TASK:>
Description:
def send_command_timing(
self,
command_string,
delay_factor=1,
max_loops=150,
strip_prompt=True,
strip_command=True,
normalize=Tr... |
output = ""
delay_factor = self.select_delay_factor(delay_factor)
self.clear_buffer()
if normalize:
command_string = self.normalize_cmd(command_string)
self.write_channel(command_string)
output = self._read_channel_timing(
delay_factor=delay_fact... |
<SYSTEM_TASK:>
In certain situations the first line will get repainted which causes a false
<END_TASK>
<USER_TASK:>
Description:
def _first_line_handler(self, data, search_pattern):
"""
In certain situations the first line will get repainted which causes a false
match on the terminating pattern.... |
try:
# First line is the echo line containing the command. In certain situations
# it gets repainted and needs filtered
lines = data.split(self.RETURN)
first_line = lines[0]
if BACKSPACE_CHAR in first_line:
pattern = search_pattern + r... |
<SYSTEM_TASK:>
Execute command_string on the SSH channel using a pattern-based mechanism. Generally
<END_TASK>
<USER_TASK:>
Description:
def send_command(
self,
command_string,
expect_string=None,
delay_factor=1,
max_loops=500,
auto_find_prompt=True,
strip_prompt=... |
# Time to delay in each read loop
loop_delay = 0.2
# Default to making loop time be roughly equivalent to self.timeout (support old max_loops
# and delay_factor arguments for backwards compatibility).
delay_factor = self.select_delay_factor(delay_factor)
if delay_factor... |
<SYSTEM_TASK:>
Strip command_string from output string
<END_TASK>
<USER_TASK:>
Description:
def strip_command(self, command_string, output):
"""
Strip command_string from output string
Cisco IOS adds backspaces into output for long commands (i.e. for commands that line wrap)
:param com... |
backspace_char = "\x08"
# Check for line wrap (remove backspaces)
if backspace_char in output:
output = output.replace(backspace_char, "")
output_lines = output.split(self.RESPONSE_RETURN)
new_output = output_lines[1:]
return self.RESPONSE_RETURN... |
<SYSTEM_TASK:>
Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.`
<END_TASK>
<USER_TASK:>
Description:
def normalize_linefeeds(self, a_string):
"""Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.`
:param a_string: A string that may have non-normalized line feeds
i.e. output returned from device, or a device p... |
newline = re.compile("(\r\r\r\n|\r\r\n|\r\n|\n\r)")
a_string = newline.sub(self.RESPONSE_RETURN, a_string)
if self.RESPONSE_RETURN == "\n":
# Convert any remaining \r to \n
return re.sub("\r", self.RESPONSE_RETURN, a_string) |
<SYSTEM_TASK:>
Normalize CLI commands to have a single trailing newline.
<END_TASK>
<USER_TASK:>
Description:
def normalize_cmd(self, command):
"""Normalize CLI commands to have a single trailing newline.
:param command: Command that may require line feed to be normalized
:type command: str
... |
command = command.rstrip()
command += self.RETURN
return command |
<SYSTEM_TASK:>
Check if in enable mode. Return boolean.
<END_TASK>
<USER_TASK:>
Description:
def check_enable_mode(self, check_string=""):
"""Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str
""" |
self.write_channel(self.RETURN)
output = self.read_until_prompt()
return check_string in output |
<SYSTEM_TASK:>
Enter into config_mode.
<END_TASK>
<USER_TASK:>
Description:
def config_mode(self, config_command="", pattern=""):
"""Enter into config_mode.
:param config_command: Configuration command to send to the device
:type config_command: str
:param pattern: Pattern to terminate... |
output = ""
if not self.check_config_mode():
self.write_channel(self.normalize_cmd(config_command))
output = self.read_until_pattern(pattern=pattern)
if not self.check_config_mode():
raise ValueError("Failed to enter configuration mode.")
retu... |
<SYSTEM_TASK:>
Send configuration commands down the SSH channel from a file.
<END_TASK>
<USER_TASK:>
Description:
def send_config_from_file(self, config_file=None, **kwargs):
"""
Send configuration commands down the SSH channel from a file.
The file is processed line-by-line and each command is... |
with io.open(config_file, "rt", encoding="utf-8") as cfg_file:
return self.send_config_set(cfg_file, **kwargs) |
<SYSTEM_TASK:>
Send configuration commands down the SSH channel.
<END_TASK>
<USER_TASK:>
Description:
def send_config_set(
self,
config_commands=None,
exit_config_mode=True,
delay_factor=1,
max_loops=150,
strip_prompt=False,
strip_command=False,
config_mod... |
delay_factor = self.select_delay_factor(delay_factor)
if config_commands is None:
return ""
elif isinstance(config_commands, string_types):
config_commands = (config_commands,)
if not hasattr(config_commands, "__iter__"):
raise ValueError("Invalid ar... |
<SYSTEM_TASK:>
Try to gracefully close the SSH connection.
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
"""Try to gracefully close the SSH connection.""" |
try:
self.cleanup()
if self.protocol == "ssh":
self.paramiko_cleanup()
elif self.protocol == "telnet":
self.remote_conn.close()
elif self.protocol == "serial":
self.remote_conn.close()
except Exception:
... |
<SYSTEM_TASK:>
For all telnet options, re-implement the default telnetlib behaviour
<END_TASK>
<USER_TASK:>
Description:
def _process_option(self, tsocket, command, option):
"""
For all telnet options, re-implement the default telnetlib behaviour
and refuse to handle any options. If the server e... |
if command == DO and option == TTYPE:
tsocket.sendall(IAC + WILL + TTYPE)
tsocket.sendall(IAC + SB + TTYPE + b"\0" + b"xterm" + IAC + SE)
elif command in (DO, DONT):
tsocket.sendall(IAC + WONT + option)
elif command in (WILL, WONT):
tsocket.sendal... |
<SYSTEM_TASK:>
Disable paging is only available with specific roles so it may fail.
<END_TASK>
<USER_TASK:>
Description:
def disable_paging(self, delay_factor=1):
"""Disable paging is only available with specific roles so it may fail.""" |
check_command = "get system status | grep Virtual"
output = self.send_command_timing(check_command)
self.allow_disable_global = True
self.vdoms = False
self._output_mode = "more"
if "Virtual domain configuration: enable" in output:
self.vdoms = True
... |
<SYSTEM_TASK:>
Save the state of the output mode so it can be reset at the end of the session.
<END_TASK>
<USER_TASK:>
Description:
def _retrieve_output_mode(self):
"""Save the state of the output mode so it can be reset at the end of the session.""" |
reg_mode = re.compile(r"output\s+:\s+(?P<mode>.*)\s+\n")
output = self.send_command("get system console")
result_mode_re = reg_mode.search(output)
if result_mode_re:
result_mode = result_mode_re.group("mode").strip()
if result_mode in ["more", "standard"]:
... |
<SYSTEM_TASK:>
Prepare the session after the connection has been established.
<END_TASK>
<USER_TASK:>
Description:
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
""" |
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
count = 1
while count <= 30:
output += self.read_channel()
if "any key to continue" in output:
self.write_channel(self.RETURN)
break
else:
... |
<SYSTEM_TASK:>
tmsh command is equivalent to config command on F5.
<END_TASK>
<USER_TASK:>
Description:
def tmsh_mode(self, delay_factor=1):
"""tmsh command is equivalent to config command on F5.""" |
delay_factor = self.select_delay_factor(delay_factor)
self.clear_buffer()
command = "{}tmsh{}".format(self.RETURN, self.RETURN)
self.write_channel(command)
time.sleep(1 * delay_factor)
self.clear_buffer()
return None |
<SYSTEM_TASK:>
Remove the > when navigating into the different config level.
<END_TASK>
<USER_TASK:>
Description:
def set_base_prompt(self, *args, **kwargs):
"""Remove the > when navigating into the different config level.""" |
cur_base_prompt = super(AlcatelSrosSSH, self).set_base_prompt(*args, **kwargs)
match = re.search(r"(.*)(>.*)*#", cur_base_prompt)
if match:
# strip off >... from base_prompt
self.base_prompt = match.group(1)
return self.base_prompt |
<SYSTEM_TASK:>
Enter into configuration mode on SROS device.
<END_TASK>
<USER_TASK:>
Description:
def config_mode(self, config_command="configure", pattern="#"):
""" Enter into configuration mode on SROS device.""" |
return super(AlcatelSrosSSH, self).config_mode(
config_command=config_command, pattern=pattern
) |
<SYSTEM_TASK:>
Extreme attaches an id to the prompt. The id increases with every command.
<END_TASK>
<USER_TASK:>
Description:
def set_base_prompt(self, *args, **kwargs):
"""
Extreme attaches an id to the prompt. The id increases with every command.
It needs to br stripped off to match the promp... |
cur_base_prompt = super(ExtremeExosBase, self).set_base_prompt(*args, **kwargs)
# Strip off any leading * or whitespace chars; strip off trailing period and digits
match = re.search(r"[\*\s]*(.*)\.\d+", cur_base_prompt)
if match:
self.base_prompt = match.group(1)
... |
<SYSTEM_TASK:>
Extreme needs special handler here due to the prompt changes.
<END_TASK>
<USER_TASK:>
Description:
def send_command(self, *args, **kwargs):
"""Extreme needs special handler here due to the prompt changes.""" |
# Change send_command behavior to use self.base_prompt
kwargs.setdefault("auto_find_prompt", False)
# refresh self.base_prompt
self.set_base_prompt()
return super(ExtremeExosBase, self).send_command(*args, **kwargs) |
<SYSTEM_TASK:>
Strip Juniper-specific output.
<END_TASK>
<USER_TASK:>
Description:
def strip_context_items(self, a_string):
"""Strip Juniper-specific output.
Juniper will also put a configuration context:
[edit]
and various chassis contexts:
{master:0}, {backup:1}
This... |
strings_to_strip = [
r"\[edit.*\]",
r"\{master:.*\}",
r"\{backup:.*\}",
r"\{line.*\}",
r"\{primary.*\}",
r"\{secondary.*\}",
]
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
... |
<SYSTEM_TASK:>
Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text.
<END_TASK>
<USER_TASK:>
Description:
def normalize_linefeeds(self, a_string):
"""Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text.""" |
newline = re.compile(r"(\r\r\n|\r\n)")
# NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS)
return newline.sub(self.RESPONSE_RETURN, a_string).replace("\r", "\n") |
<SYSTEM_TASK:>
Send command to network device retrieve output until router_prompt or expect_string
<END_TASK>
<USER_TASK:>
Description:
def send_command(self, *args, **kwargs):
"""
Send command to network device retrieve output until router_prompt or expect_string
By default this method will ke... |
if len(args) >= 2:
expect_string = args[1]
else:
expect_string = kwargs.get("expect_string")
if expect_string is None:
expect_string = r"(OK|ERROR|Command not recognized\.)"
expect_string = self.RETURN + expect_string + self.RETURN
... |
<SYSTEM_TASK:>
Use processes and Netmiko to connect to each of the devices. Execute
<END_TASK>
<USER_TASK:>
Description:
def main():
"""
Use processes and Netmiko to connect to each of the devices. Execute
'show version' on each device. Record the amount of time required to do this.
""" |
start_time = datetime.now()
procs = []
for a_device in devices:
my_proc = Process(target=show_version, args=(a_device,))
my_proc.start()
procs.append(my_proc)
for a_proc in procs:
print(a_proc)
a_proc.join()
print("\nElapsed time: " + str(datetime.now() - ... |
<SYSTEM_TASK:>
Get an item from the Row by column name.
<END_TASK>
<USER_TASK:>
Description:
def get(self, column, default_value=None):
"""Get an item from the Row by column name.
Args:
column: Tuple of column names, or a (str) column name, or positional
column number, 0-indexed.
defaul... |
if isinstance(column, (list, tuple)):
ret = []
for col in column:
ret.append(self.get(col, default_value))
return ret
# Perhaps we have a range like '1', ':-1' or '1:'.
try:
return self._values[column]
except (IndexError, T... |
<SYSTEM_TASK:>
Sets row's colour attributes to a list of values in terminal.SGR.
<END_TASK>
<USER_TASK:>
Description:
def _SetColour(self, value_list):
"""Sets row's colour attributes to a list of values in terminal.SGR.""" |
if value_list is None:
self._color = None
return
colors = []
for color in value_list:
if color in terminal.SGR:
colors.append(color)
elif color in terminal.FG_COLOR_WORDS:
colors += terminal.FG_COLOR_WORDS[color]
... |
<SYSTEM_TASK:>
Inserts new values at a specified offset.
<END_TASK>
<USER_TASK:>
Description:
def Insert(self, key, value, row_index):
"""Inserts new values at a specified offset.
Args:
key: string for header value.
value: string for a data value.
row_index: Offset into row for data.
... |
if row_index < 0:
row_index += len(self)
if not 0 <= row_index < len(self):
raise IndexError('Index "%s" is out of bounds.' % row_index)
new_row = Row()
for idx in self.header:
if self.index(idx) == row_index:
new_row[key] = value
... |
<SYSTEM_TASK:>
Applies the function to every row in the table.
<END_TASK>
<USER_TASK:>
Description:
def Map(self, function):
"""Applies the function to every row in the table.
Args:
function: A function applied to each row.
Returns:
A new TextTable()
Raises:
TableError: When tra... |
new_table = self.__class__()
# pylint: disable=protected-access
new_table._table = [self.header]
for row in self:
filtered_row = function(row)
if filtered_row:
new_table.Append(filtered_row)
return new_table |
<SYSTEM_TASK:>
Sorts rows in the texttable.
<END_TASK>
<USER_TASK:>
Description:
def sort(self, cmp=None, key=None, reverse=False):
"""Sorts rows in the texttable.
Args:
cmp: func, non default sort algorithm to use.
key: func, applied to each element before sorting.
reverse: bool, reverse... |
def _DefaultKey(value):
"""Default key func is to create a list of all fields."""
result = []
for key in self.header:
# Try sorting as numerical value if possible.
try:
result.append(float(value[key]))
exce... |
<SYSTEM_TASK:>
Extends all rows in the texttable.
<END_TASK>
<USER_TASK:>
Description:
def extend(self, table, keys=None):
"""Extends all rows in the texttable.
The rows are extended with the new columns from the table.
Args:
table: A texttable, the table to extend this table by.
keys: A s... |
if keys:
for k in keys:
if k not in self._Header():
raise IndexError("Unknown key: '%s'", k)
extend_with = []
for column in table.header:
if column not in self.header:
extend_with.append(column)
if not extend_... |
<SYSTEM_TASK:>
Removes a row from the table.
<END_TASK>
<USER_TASK:>
Description:
def Remove(self, row):
"""Removes a row from the table.
Args:
row: int, the row number to delete. Must be >= 1, as the header
cannot be removed.
Raises:
TableError: Attempt to remove nonexistent or he... |
if row == 0 or row > self.size:
raise TableError("Attempt to remove header row")
new_table = []
# pylint: disable=E1103
for t_row in self._table:
if t_row.row != row:
new_table.append(t_row)
if t_row.row > row:
... |
<SYSTEM_TASK:>
Returns the current row as a tuple.
<END_TASK>
<USER_TASK:>
Description:
def _GetRow(self, columns=None):
"""Returns the current row as a tuple.""" |
row = self._table[self._row_index]
if columns:
result = []
for col in columns:
if col not in self.header:
raise TableError("Column header %s not known in table." % col)
result.append(row[self.header.index(col)])
ro... |
<SYSTEM_TASK:>
Sets the current row to new list.
<END_TASK>
<USER_TASK:>
Description:
def _SetRow(self, new_values, row=0):
"""Sets the current row to new list.
Args:
new_values: List|dict of new values to insert into row.
row: int, Row to insert values into.
Raises:
TableError: If n... |
if not row:
row = self._row_index
if row > self.size:
raise TableError("Entry %s beyond table size %s." % (row, self.size))
self._table[row].values = new_values |
<SYSTEM_TASK:>
Sets header of table to the given tuple.
<END_TASK>
<USER_TASK:>
Description:
def _SetHeader(self, new_values):
"""Sets header of table to the given tuple.
Args:
new_values: Tuple of new header values.
""" |
row = self.row_class()
row.row = 0
for v in new_values:
row[v] = v
self._table[0] = row |
<SYSTEM_TASK:>
Finds the largest indivisible word of a string.
<END_TASK>
<USER_TASK:>
Description:
def _SmallestColSize(self, text):
"""Finds the largest indivisible word of a string.
...and thus the smallest possible column width that can contain that
word unsplit over rows.
Args:
text: A ... |
if not text:
return 0
stripped = terminal.StripAnsiText(text)
return max(len(word) for word in stripped.split()) |
<SYSTEM_TASK:>
Retrieves the first non header row with the column of the given value.
<END_TASK>
<USER_TASK:>
Description:
def RowWith(self, column, value):
"""Retrieves the first non header row with the column of the given value.
Args:
column: str, the name of the column to check.
value: str, ... |
for row in self._table[1:]:
if row[column] == value:
return row
return None |
<SYSTEM_TASK:>
Appends a new column to the table.
<END_TASK>
<USER_TASK:>
Description:
def AddColumn(self, column, default="", col_index=-1):
"""Appends a new column to the table.
Args:
column: A string, name of the column to add.
default: Default value for entries. Defaults to ''.
col_in... |
if column in self.table:
raise TableError("Column %r already in table." % column)
if col_index == -1:
self._table[0][column] = column
for i in range(1, len(self._table)):
self._table[i][column] = default
else:
self._table[0].Insert... |
<SYSTEM_TASK:>
Fetches a new, empty row, with headers populated.
<END_TASK>
<USER_TASK:>
Description:
def NewRow(self, value=""):
"""Fetches a new, empty row, with headers populated.
Args:
value: Initial value to set each row entry to.
Returns:
A Row() object.
""" |
newrow = self.row_class()
newrow.row = self.size + 1
newrow.table = self
headers = self._Header()
for header in headers:
newrow[header] = value
return newrow |
<SYSTEM_TASK:>
Parses buffer into tabular format.
<END_TASK>
<USER_TASK:>
Description:
def CsvToTable(self, buf, header=True, separator=","):
"""Parses buffer into tabular format.
Strips off comments (preceded by '#').
Optionally parses and indexes by first line (header).
Args:
buf: String f... |
self.Reset()
header_row = self.row_class()
if header:
line = buf.readline()
header_str = ""
while not header_str:
# Remove comments.
header_str = line.split("#")[0].strip()
if not header_str:
... |
<SYSTEM_TASK:>
Make sure paging is disabled.
<END_TASK>
<USER_TASK:>
Description:
def disable_paging(self, command="pager off", delay_factor=1):
"""Make sure paging is disabled.""" |
return super(PluribusSSH, self).disable_paging(
command=command, delay_factor=delay_factor
) |
<SYSTEM_TASK:>
Print out inventory devices and groups.
<END_TASK>
<USER_TASK:>
Description:
def display_inventory(my_devices):
"""Print out inventory devices and groups.""" |
inventory_groups = ["all"]
inventory_devices = []
for k, v in my_devices.items():
if isinstance(v, list):
inventory_groups.append(k)
elif isinstance(v, dict):
inventory_devices.append((k, v["device_type"]))
inventory_groups.sort()
inventory_devices.sort(key=... |
<SYSTEM_TASK:>
Dynamically create 'all' group.
<END_TASK>
<USER_TASK:>
Description:
def obtain_all_devices(my_devices):
"""Dynamically create 'all' group.""" |
new_devices = {}
for device_name, device_or_group in my_devices.items():
# Skip any groups
if not isinstance(device_or_group, list):
new_devices[device_name] = device_or_group
return new_devices |
<SYSTEM_TASK:>
Ensure directory exists. Create if necessary.
<END_TASK>
<USER_TASK:>
Description:
def ensure_dir_exists(verify_dir):
"""Ensure directory exists. Create if necessary.""" |
if not os.path.exists(verify_dir):
# Doesn't exist create dir
os.makedirs(verify_dir)
else:
# Exists
if not os.path.isdir(verify_dir):
# Not a dir, raise an exception
raise ValueError("{} is not a directory".format(verify_dir)) |
<SYSTEM_TASK:>
Write Python2 and Python3 compatible byte stream.
<END_TASK>
<USER_TASK:>
Description:
def write_bytes(out_data, encoding="ascii"):
"""Write Python2 and Python3 compatible byte stream.""" |
if sys.version_info[0] >= 3:
if isinstance(out_data, type("")):
if encoding == "utf-8":
return out_data.encode("utf-8")
else:
return out_data.encode("ascii", "ignore")
elif isinstance(out_data, type(b"")):
return out_data
else:... |
<SYSTEM_TASK:>
Given a file name to a valid file returns the file object.
<END_TASK>
<USER_TASK:>
Description:
def file_contents(file_name):
"""Given a file name to a valid file returns the file object.""" |
curr_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(curr_dir, file_name)) as the_file:
contents = the_file.read()
return contents |
<SYSTEM_TASK:>
Handles using .title if the given object is a troposphere resource.
<END_TASK>
<USER_TASK:>
Description:
def depends_on_helper(obj):
""" Handles using .title if the given object is a troposphere resource.
If the given object is a troposphere resource, use the `.title` attribute
of that resou... |
if isinstance(obj, AWSObject):
return obj.title
elif isinstance(obj, list):
return list(map(depends_on_helper, obj))
return obj |
<SYSTEM_TASK:>
Imports userdata from a file.
<END_TASK>
<USER_TASK:>
Description:
def from_file(filepath, delimiter='', blanklines=False):
"""Imports userdata from a file.
:type filepath: string
:param filepath The absolute path to the file.
:type delimiter: string
:param: delimiter Delimiter ... |
data = []
try:
with open(filepath, 'r') as f:
for line in f:
if blanklines and line.strip('\n\r ') == '':
continue
data.append(line)
except IOError:
raise IOError('Error opening or reading file: {}'.format(filepath))
ret... |
<SYSTEM_TASK:>
Return a list of validators specified in the override file
<END_TASK>
<USER_TASK:>
Description:
def get_validator_list(self):
"""Return a list of validators specified in the override file""" |
ignore = [
'dict',
]
vlist = []
if not self.override:
return vlist
for k, v in list(self.override['classes'].items()):
if 'validator' in v:
validator = v['validator']
if validator not in ignore and validator no... |
<SYSTEM_TASK:>
Look for a Tags object to output a Tags import
<END_TASK>
<USER_TASK:>
Description:
def _output_tags(self):
"""Look for a Tags object to output a Tags import""" |
for class_name, properties in sorted(self.resources.items()):
for key, value in sorted(properties.items()):
validator = self.override.get_validator(class_name, key)
if key == 'Tags' and validator is None:
print("from troposphere import Tags")
... |
<SYSTEM_TASK:>
Decode a properties type looking for a specific type.
<END_TASK>
<USER_TASK:>
Description:
def _check_type(self, check_type, properties):
"""Decode a properties type looking for a specific type.""" |
if 'PrimitiveType' in properties:
return properties['PrimitiveType'] == check_type
if properties['Type'] == 'List':
if 'ItemType' in properties:
return properties['ItemType'] == check_type
else:
return properties['PrimitiveItemType'] =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.