def connect(self, host, **kwargs): transport = kwargs.get("transport") or "http" # cert=None, port=None, auth=None, # protocol="http", timeout=(5, 300), verify=True sess_args = {} if "cert" in kwargs: sess_args["cert"] = kwargs["cert"] elif "creds" in kwargs: sess_args["auth"] = kwargs["creds"].auth if "port" in kwargs: sess_args["port"] = kwargs["port"] if "timeout" in kwargs: sess_args["timeout"] = kwargs["timeout"] if "verify" in kwargs: sess_args["verify"] = kwargs["verify"] self._session = eapi_.Session(host, transport=transport, **sess_args) if self._session.auth: try: self._session.login() except eapi_.EapiAuthenticationFailure as exc: raise AuthenticationFailed(str(exc)) except eapi_.EapiError as exc: raise ConnectFailed(str(exc))
async def _asend(filtered, commands, **kwargs): loop = asyncio.get_event_loop() tasks = [] def _send_until(sess, commands, **kwargs): # default will match on anything condition = r".*" timeout = 30 sleep = 1 exclude = None start_time = time.time() check_time = start_time # handle the 'until' arg. it can be a dict... if "until" in kwargs: until = kwargs["until"] del (kwargs["until"]) if isinstance(until, dict): if "condition" not in until: raise ValueError("'condition' expected") condition = until["condition"] timeout = until.get("timeout") or timeout sleep = until.get("sleep") or sleep exclude = until.get("exclude") else: condition = until while (check_time - timeout) < start_time: response = sess.send(commands, **kwargs) match = re.search(condition, "\n".join([r.text for r in response])) if exclude: if not match: return response elif match: return response time.sleep(sleep) check_time = time.time() raise ValueError("condition did not match withing timeout period") for session in filtered: sess = eapi.Session(session.endpoint, **session.eapi_params) part = functools.partial(_send_until, sess, commands, **kwargs) tasks.append(loop.run_in_executor(None, part)) completed, _ = await asyncio.wait(tasks) return [task.result() for task in completed]
def _worker(switch, args): try: sess = eapi.Session(switch, auth=(args.username, args.password), transport=args.transport, verify=args.verify_ssl_cert, timeout=args.timeout) hostaddr = sess.hostaddr response = sess.send([ "enable", "show boot-config", "bash timeout 30 ls -1 /mnt/flash/*.swi" ], encoding="json") if (response[1]["softwareImage"] == ""): print("{}: Boot image is not set! Aborting") return boot = response[1]["softwareImage"].split("/")[-1] print("{}: Boot image is {}".format(switch, boot)) images = list( map(os.path.basename, response[2]["messages"][0].splitlines())) if len(images) == 0: print("{}: No EOS images found") return keep = [] cleanup = [] for image in images: if image == boot: print("{}: Keeping {}".format(switch, image)) keep.append(image) else: print("{}: Deleting {}".format(switch, image)) cleanup.append(image) if not keep: print("{}: did not find any keeper images. Aborting") return response = sess.send( list(map(lambda x: "delete flash:%s" % x, cleanup))) if len(cleanup) > 0: print("%s: Deleted %d images" % (switch, len(cleanup))) return except OSError as exc: print("%s: %s" % (hostaddr, exc.strerror)) except Exception as exc: print("%s: %s" % (hostaddr, str(exc)))
def _worker(switch, args): try: sess = eapi.Session(switch, auth=(args.username, args.password), transport=args.transport, verify=args.verify_ssl_cert, timeout=args.timeout) hostaddr = sess.hostaddr if not image_loaded(sess, args.name): print("{}: {} is not present on flash. Copying...".format( switch, args.name)) response = sess.send([ "enable", "routing-context vrf {}".format(args.vrf), "copy {} flash:/{}".format(args.image, args.name) ], encoding="json") if not image_loaded(sess, args.name): print("{}: Image is still not present. Something went wrong". format(hostaddr)) return #Verify Copy response = sess.send(["verify /sha512 flash:{}".format(args.name)], encoding="text") sha512 = str(response[0]).strip().split(" ")[-1] if get_sha512(args.sha512) == sha512: print( "{}: SHA512 check passed. Copy Verified.".format(hostaddr)) else: print( "{}: SHA512 check failed. Image may be corrupted.".format( hostaddr)) # sess.send(["delete flash:{}".format(args.name)]) else: print("{}: {} is present on flash. Skipping...".format( hostaddr, args.name)) return except OSError as exc: print("%s: %s" % (hostaddr, exc.strerror)) except Exception as exc: print("%s: %s" % (hostaddr, str(exc)))
def test_context(server, auth): target = str(server.url) with eapi.Session() as sess: sess.login(target, auth=auth) sess.call(target, ["show hostname"])