def exec_cmd(self, command): print "Executing command " + command + " on host " + self.host lib = SSHLibrary() lib.open_connection(self.host) lib.login(username=self.user,password=self.password) lib.execute_command(command) lib.close_connection()
def copy_file(self, src, dest): lib = SSHLibrary() lib.open_connection(self.host) lib.login(username=self.user, password=self.password) print "Copying " + src + " to " + dest + " on " + self.host lib.put_file(src, dest) lib.close_connection()
def execute_ssh_command(ip, username, password, command): print "executing ssh command" lib = SSHLibrary() lib.open_connection(ip) lib.login(username=username, password=password) print "login done" lib.execute_command(command) print "command executed : " + command lib.close_connection()
def execute_ssh_command(ip, username, password, command): print "executing ssh command" lib = SSHLibrary() lib.open_connection(ip) lib.login(username=username,password=password) print "login done" lib.execute_command(command) print "command executed : " + command lib.close_connection()
def execute_ssh_command(ip, username, password, command): """Execute SSH Command use username and password of controller server for ssh and need karaf distribution location like /root/Documents/dist """ print("executing ssh command") lib = SSHLibrary() lib.open_connection(ip) lib.login(username=username, password=password) print("login done") cmd_response = lib.execute_command(command) print("command executed : " + command) lib.close_connection() return cmd_response
def execute_ssh_command(ip, username, password, command): """Execute SSH Command use username and password of controller server for ssh and need karaf distribution location like /root/Documents/dist """ print "executing ssh command" lib = SSHLibrary() lib.open_connection(ip) lib.login(username=username, password=password) print "login done" cmd_response = lib.execute_command(command) print "command executed : " + command lib.close_connection() return cmd_response
class RemoteHost: def __init__(self, host, user, password, rootdir, keyfile=None): self.host = host self.user = user self.password = password self.rootdir = rootdir self.keyfile = keyfile self.lib = SSHLibrary() self.lib.open_connection(self.host) if self.keyfile is not None: self.lib.login_with_public_key(username=self.user, keyfile=self.keyfile) else: self.lib.login(username=self.user, password=self.password) def __del__(self): self.lib.close_connection() def exec_cmd(self, command): print "Executing command " + command + " on host " + self.host rc = self.lib.execute_command(command, return_rc=True) if rc[1] != 0: raise Exception('remote command failed [{0}] with exit code {1}.' 'For linux-based vms, Please make sure requiretty is disabled in the /etc/sudoers file' .format(command, rc)) def mkdir(self, dir_name): self.exec_cmd("mkdir -p " + dir_name) def copy_file(self, src, dest): if src is None: print "src is None not copy anything to " + dest return if os.path.exists(src) is False: print "Src file " + src + " was not found" return print "Copying " + src + " to " + dest + " on " + self.host self.lib.put_file(src, dest) def kill_controller(self): self.exec_cmd("sudo ps axf | grep karaf | grep -v grep " "| awk '{print \"kill -9 \" $1}' | sudo sh") def start_controller(self, dir_name): self.exec_cmd(dir_name + "/odl/bin/start")
def RSA_ssh_copy_key(self, host, username, password): """ Login With Public Key(username, keyLocations['privateKey'], 'passphrase') """ sshLibSession = SSHLibrary(loglevel='WARN') fo = open(os.path.join(self.keyStore, self.opensshKeyName), "rb") sshKey = fo.read() fo.close() sshLibSession.open_connection(host) sshLibSession.login(username, password) sshLibSession.execute_command("mkdir .ssh") sshLibSession.execute_command((("echo %s > .ssh/authorized_keys") % (sshKey))) sshLibSession.execute_command("chmod 700 .ssh") sshLibSession.execute_command("chmod 600 .ssh/authorized_keys") sshLibSession.close_connection()
def wait_for_controller_stopped(ip, username, password, karafHome): lib = SSHLibrary() lib.open_connection(ip) lib.login(username=username, password=password) # Wait 1 minute for the controller to stop gracefully tries = 20 i = 1 while i <= tries: stdout = lib.execute_command("ps -axf | grep karaf | grep -v grep | wc -l") processCnt = stdout[0].strip('\n') print("processCnt: " + processCnt) if processCnt == '0': break i = i + 1 time.sleep(3) lib.close_connection() if i > tries: print("Killing controller") kill_controller(ip, username, password, karafHome)
def wait_for_controller_stopped(ip, username, password, karafHome): lib = SSHLibrary() lib.open_connection(ip) lib.login(username=username, password=password) # Wait 1 minute for the controller to stop gracefully tries = 20 i = 1 while i <= tries: stdout = lib.execute_command("ps -axf | grep karaf | grep -v grep | wc -l") # print "stdout: "+stdout processCnt = stdout[0].strip('\n') print("processCnt: " + processCnt) if processCnt == '0': break i = i + 1 time.sleep(3) lib.close_connection() if i > tries: print "Killing controller" kill_controller(ip, username, password, karafHome)
def issue_cmd_via_root(command, host, username=HOST_USER, pwd=HOST_PWD, timeout=300, prompt='$ ', sudo=False, sudo_password=None): """ The return value is ["standard output", "error output", return_value] """ sshLib = SSHLibrary() try: # print "[INFO] Begin to open the connection of", str(host) sshLib.open_connection(host) sshLib.login(username, pwd) # http://docs.paramiko.org/en/1.15/api/client.html#paramiko.client.SSHClient.connect except (SSHClientException, paramiko.SSHException, socket.error, socket.timeout) as se: errmsg = "[Error] Failed to connect to {host}".format(host=str(host)) print errmsg os.environ["OUTPUT"] = errmsg sshLib.close_connection() return ["", "", -1] ret = sshLib.execute_command(command, return_stdout=True, return_stderr=True, return_rc=True, sudo=sudo, sudo_password=sudo_password) sshLib.close_connection() if ret[2] == 0: os.environ["OUTPUT"] = ret[0] else: os.environ["OUTPUT"] = ret[1] return ret
class SshLibrary(SSHLibrary): def __init__(self): pass @classmethod def ssh_(self, host, user, password): self.ssh = SSHLibrary(timeout=10) try: self.ssh.open_connection(host) self.ssh.login(user, password) command = [ 'show card', 'paginate false', 'show run vlan', 'show version' ] self.session_command(command) except ValueError as e: raise e return self.ssh @classmethod def session_command(self, command): print("command: ", type(command), command) if isinstance(command, list): for com in command: self.ssh.write(com.encode('ascii')) result = self.ssh.read_until('# ') return result if isinstance(command, str): self.ssh.write(command.encode('ascii')) result = self.ssh.read_until('# ') return result else: raise RuntimeError('command type error') @classmethod def reconnection(self, host): if self.ssh: return self.ssh else: self.ssh.open_connection(host) self.ssh.login(b'sysadmin', b'seanwang') return self.ssh def __del__(self): return self.ssh.close_connection()
class FusionLibrary( FusionAPIKeywords, FusionAPIKeywords.ActiveUserSessionsKeywords, FusionAPIKeywords.AlertKeywords, FusionAPIKeywords.AuditLogKeywords, FusionAPIKeywords.AuthorizationsKeywords, FusionAPIKeywords.ApplianceDeviceReadCommunityKeywords, FusionAPIKeywords.ApplianceEulaKeywords, FusionAPIKeywords.ApplianceFactoryResetKeywords, FusionAPIKeywords.ApplianceFirmwareKeywords, FusionAPIKeywords.ApplianceHealthStatusKeywords, FusionAPIKeywords.ApplianceNetworkInterfacesKeywords, FusionAPIKeywords.ApplianceNodeInformationKeywords, FusionAPIKeywords.ApplianceShutdownKeywords, FusionAPIKeywords.ApplianceStateKeywords, FusionAPIKeywords.ApplianceSupportDumpKeywords, FusionAPIKeywords.ApplianceTimeAndLocaleConfigurationKeywords, FusionAPIKeywords.ApplianceTrapDestinationKeywords, FusionAPIKeywords.ApplianceSnmpv3TrapDestinationKeywords, FusionAPIKeywords.ApplianceSnmpv3TrapForwardingUserKeywords, FusionAPIKeywords.ApplianceUpgrade, FusionAPIKeywords.BackupKeywords, FusionAPIKeywords.CertificateAuthorityKeywords, FusionAPIKeywords.CertificateValidationConfigurationKeywords, FusionAPIKeywords.CertificateClientRabbitMqKeywords, FusionAPIKeywords.ClientCertificateKeywords, FusionAPIKeywords.ConnectionsKeywords, FusionAPIKeywords.ConnectionTemplateKeywords, FusionAPIKeywords.DatacenterKeywords, FusionAPIKeywords.DeviceManagerKeywords, FusionAPIKeywords.DeploymentManagerKeywords, FusionAPIKeywords.DriveEnclosureKeywords, FusionAPIKeywords.DomainsKeywords, FusionAPIKeywords.EmailNotificationKeywords, FusionAPIKeywords.EnclosureKeywords, FusionAPIKeywords.RackManagerKeywords, FusionAPIKeywords.EnclosureGroupKeywords, FusionAPIKeywords.EthernetNetworkKeywords, FusionAPIKeywords.EventKeywords, FusionAPIKeywords.FabricKeywords, FusionAPIKeywords.FabricManagerKeywords, FusionAPIKeywords.FcNetworkKeywords, FusionAPIKeywords.FcoeNetworkKeywords, FusionAPIKeywords.FirmwareBundleKeywords, FusionAPIKeywords.FirmwareDriverKeywords, FusionAPIKeywords.GlobalSettingsKeywords, FusionAPIKeywords.HaNodesKeywords, FusionAPIKeywords.HypervisorManagerKeywords, FusionAPIKeywords.HypervisorClusterProfileKeywords, FusionAPIKeywords.HypervisorHostProfileKeywords, FusionAPIKeywords.HypervisorHostKeywords, FusionAPIKeywords.HypervisorClustersKeywords, FusionAPIKeywords.IdPoolKeywords, FusionAPIKeywords.IdPoolsIpv4RangeKeywords, FusionAPIKeywords.IdPoolsIpv4SubnetKeywords, FusionAPIKeywords.IdPoolsVmacRangeKeywords, FusionAPIKeywords.IdPoolsVsnRangeKeywords, FusionAPIKeywords.IdPoolsVwwnRangeKeywords, FusionAPIKeywords.IndexAssociationKeywords, # FusionAPIKeywords.IndexResourceKeywords, FusionAPIKeywords.IndexResourceKeywords, # FusionAPIKeywords.IndexSearchSuggestionKeywords, # FusionAPIKeywords.IndexTreeKeywords, FusionAPIKeywords.InterconnectLinkTopologyKeywords, FusionAPIKeywords.InterconnectKeywords, FusionAPIKeywords.InterconnectTypesKeywords, FusionAPIKeywords.InternalLinkSetKeywords, # FusionAPIKeywords.LabelKeywords, FusionAPIKeywords.LicensesKeywords, FusionAPIKeywords.SecurityStandardsKeywords, FusionAPIKeywords.LoginDetailsKeywords, FusionAPIKeywords.LoginDomainKeywords, FusionAPIKeywords.LogicalDownlinkKeywords, FusionAPIKeywords.LoginDomainsGlobalSettingsKeywords, FusionAPIKeywords.LoginDomainsLoginCertificatesKeywords, FusionAPIKeywords.LoginDomainsGroupToRoleMappingKeywords, FusionAPIKeywords.LoginSessionKeywords, FusionAPIKeywords.LogicalInterconnectKeywords, FusionAPIKeywords.LogicalInterconnectGroupKeywords, FusionAPIKeywords.LogicalSwitchGroupKeywords, FusionAPIKeywords.LogicalSwitchKeywords, FusionAPIKeywords.LogicalEnclosureKeywords, FusionAPIKeywords.ManagedSanKeywords, FusionAPIKeywords.MetricStreamingKeywords, FusionAPIKeywords.NetworkSetKeywords, FusionAPIKeywords.MigratableVcDomainKeywords, FusionAPIKeywords.PingKeywords, FusionAPIKeywords.PowerDeviceKeywords, FusionAPIKeywords.ProviderKeywords, FusionAPIKeywords.RackKeywords, FusionAPIKeywords.RemoteSyslogKeywords, FusionAPIKeywords.RemoteSupportKeywords, FusionAPIKeywords.ConfigurationKeywords, FusionAPIKeywords.ReportKeywords, FusionAPIKeywords.RestoreKeywords, FusionAPIKeywords.RolesKeywords, FusionAPIKeywords.SasInterconnectsKeywords, FusionAPIKeywords.SasInterconnectTypesKeywords, FusionAPIKeywords.SasLogicalInterconnectGroupKeywords, FusionAPIKeywords.SasLogicalInterconnectKeywords, FusionAPIKeywords.ServerHardwareTypesKeywords, FusionAPIKeywords.ServerHardwareKeywords, FusionAPIKeywords.ServerProfileKeywords, FusionAPIKeywords.ServerProfileTemplateKeywords, FusionAPIKeywords.ServiceAccessKeywords, FusionAPIKeywords.SessionsKeywords, FusionAPIKeywords.StartupProgressKeywords, FusionAPIKeywords.StoragePoolKeywords, FusionAPIKeywords.StorageSystemKeywords, FusionAPIKeywords.StorageVolumeKeywords, FusionAPIKeywords.StorageVolumeTemplateKeywords, FusionAPIKeywords.StorageVolumeAttachmentKeywords, FusionAPIKeywords.SwitchKeywords, FusionAPIKeywords.SwitchTypesKeywords, FusionAPIKeywords.TaskKeywords, FusionAPIKeywords.UplinkSetKeywords, FusionAPIKeywords.UserKeywords, FusionAPIKeywords.VersionKeywords, FusionAPIKeywords.SasLogicalJbodsKeywords, FusionAPIKeywords.SasLogicalJbodAttachmentsKeywords, FusionAPIKeywords.WebServerCertificateKeywords, FusionAPIKeywords.HalAPIKeywords, FusionAPIKeywords.PermAPIKeywords, FusionAPIKeywords.ProxyServerKeywords, FusionAPIKeywords.IPKeywords, FusionAPIKeywords.ScopeKeywords, FusionAPIKeywords.RepositoryKeywords, FusionAPIKeywords.SshAccessKeywords, FusionAPIKeywords.ApplianceCertificateKeywords, FusionAPIKeywords.RemoteCertificateKeywords, FusionAPIKeywords.ServerCertificateKeywords, FusionAPIKeywords.CertificateStatusKeywords, FusionUIKeywords, MantraUIKeywords, FusionSRMOaApiKeywords, FusionSRMIloApiKeywords, FusionSanmanagerUIKeywords, FusionSanUIKeywords, DCSAPIKeywords, FusionPMSanUiKeywords, HellfireAPIKeywords.InfrastructureVmsKeywords, HellfireAPIKeywords.StoreVirtualVsaClusterKeywords, OACLIKeywords, FusionCLIKeywords, HellfireAPIKeywords, SVMCAPIKeywords, TrafficLibraryKeywords, TrafficLibraryKeywords.VspLibraryKeywords, TrafficLibraryKeywords.PingTrafficLibraryKeywords, TrafficLibraryKeywords.IPerfTrafficLibraryKeywords, TrafficLibraryKeywords.IOMeterLibraryKeywords, FusionAPIKeywords.OSDeploymentServerKeywords, TRUKeywords, CptPayloadGenerator, NetworkConfigGenerator): """ Main FusionLibrary keyword class definition """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = __version__ ROBOT_LISTENER_API_VERSION = 2 FILTER_LIBRARIES = ['BuiltIn', 'Collections', 'Dialogs', 'OperatingSystem', 'SSHLibrary', 'String', 'XML'] MAX_QUEUE = 1000 # max elk data queue size # Elk data encapsulation object ElkItem = namedtuple("ElkItem", "obj_type, data") def _gather_repo_info(self): """ Private method to initialize variables pertaining to Test repository :return: None """ try: # Invalid error would be thrown if path is not source_root repo = Repo(os.path.dirname(THIS_DIR)) self.repo_commit = str(repo.rev_parse('HEAD')) self.repo_branch_name = repo.git.rev_parse('--abbrev-ref', '--symbolic-full-name', '@{u}') del repo except: # noqa pass def __init__(self): self.ROBOT_LIBRARY_LISTENER = self self.elk_queue_writer = None self.hostname = socket.gethostname() self.uuid = str(uuid.uuid1()) self._ov = None self._ssh = None self.activity_queue = None self.log_activity = False self.log_activity_to_cidebug_log = False self.queue_writer = None self.repo_commit = 'Not Found' self.repo_branch_name = 'Not identified' self._gather_repo_info() logger._log_to_console_and_log_file("Fusion library version %s" % __version__) for base in FusionLibrary.__bases__: base.__init__(self) def __logging_activity(self): """ This private method handles writing to the ElkWriter thread if logging is enabled. Note: log activity with -v LOG_ACTIVITY:True """ # initialize and start the activity logging queue self.log_activity = BuiltIn().get_variable_value("${LOG_ACTIVITY}") if self.log_activity == 'False': return False # initialize queue and queue writer if not self.activity_queue: self.activity_queue = Queue(maxsize=self.MAX_QUEUE) if not self.queue_writer: host = BuiltIn().get_variable_value("${ACTIVITY_LOGGING_SERVER}") index = BuiltIn().get_variable_value("${ACTIVITY_INDEX_NAME}") if not host: host = DEFAULT_ACTIVITY_LOGGING_SERVER if not index: index = DEFAULT_ACTIVITY_INDEX_NAME self.queue_writer = ElkQueueWriter(host, index, self.activity_queue) self.queue_writer.start() return True def __logging_activity_to_cidebug_log(self): """ This private method handles writing to the /ci/logs/ciDebug.log file on the appliance if logging is enabled. Note: log activity with -v LOG_ACTIVITY_TO_CIDEBUG:True """ # initialize and start the activity logging queue self.log_activity_to_cidebug_log = BuiltIn().get_variable_value("${LOG_ACTIVITY_TO_CIDEBUG}") if not self.log_activity_to_cidebug_log: return False # get the appliance host and open ssh session if not self._ov: self._ov = _get_host_variable() if not self._ssh: self.__create_ssh_connection_and_login(self._ov) return True def __create_ssh_connection_and_login(self, host, username='******', password='******'): """ Create a new SSH connection and log in """ try: self._ssh = SSHLibrary() self._ssh.set_default_configuration(timeout='15 seconds', term_type='xterm', prompt='#') self._ssh.open_connection(host) self._ssh.login(username, password) except: # noqa e = sys.exc_info()[0] logger._log_to_console_and_log_file("unable to connect ssh: {} {}".format(host, e)) self._ssh = None def __run_ssh_commands(self, cmds): """ Run an SSH command """ if self._ssh is not None: if self._ssh.get_connection(host=True) is not None: try: self._ssh.write(cmds) except: # noqa e = sys.exc_info()[0] logger._log_to_console_and_log_file("unable to write to ssh: {} {}".format(cmds, e)) self._ssh.close_connection() self._ssh = None else: logger.info("no ssh: session {}".format(cmds)) self._ssh.close_connection() self._ssh = None def _write_log(self, ltype, stat, attrs): """ Write a log entry """ name = None if 'longname' in attrs: name = attrs['longname'] elif 'kwname' in attrs: name = attrs['kwname'] return """date +"%Y-%m-%d %H:%M:%S.%N %Z,INFO,ROBO,{},{},{},{}" >> /ci/logs/ciDebug.log""".format(self.uuid, ltype.upper(), name, stat.upper()) def _add_data_to_attrs(self, name, attrs): """ Add additional data to suite/test/keyword attributes for Elk logging. """ metadata = BuiltIn().get_variable_value("&{SUITE METADATA}") if not self._ov: self._ov = _get_host_variable() if 'kwname' in attrs: attrs['name'] = attrs['kwname'] del attrs['kwname'] else: attrs['name'] = name attrs['suiteName'] = BuiltIn().get_variable_value("${SUITE_NAME)") attrs['suiteSource'] = BuiltIn().get_variable_value("${SUITE_SOURCE)") attrs['testName'] = BuiltIn().get_variable_value("${TEST_NAME)") attrs['oneViewIp'] = self._ov attrs['oneViewVersion'] = metadata.get("OneView Version") if 'starttime' in attrs: attrs['starttime'] = parse_date(attrs['starttime']).replace(tzinfo=tz.tzlocal()).astimezone(tz.tzutc()).isoformat() if 'endtime' in attrs: attrs['endtime'] = parse_date(attrs['endtime']).replace(tzinfo=tz.tzlocal()).astimezone(tz.tzutc()).isoformat() attrs['@timestamp'] = attrs.get('starttime') attrs['hostname'] = self.hostname attrs['runId'] = self.uuid attrs['gitCommitId'] = self.repo_commit attrs['gitRemoteBranch'] = self.repo_branch_name return attrs def _start_suite(self, name, attrs): # pylint: disable=unused-argument """ This listener logs suite start """ if self.__logging_activity_to_cidebug_log(): self.__run_ssh_commands(self._write_log('suite', 'started', attrs)) BuiltIn().set_global_variable("${RUN_UUID}", self.uuid) def _end_suite(self, name, attrs): # pylint: disable=unused-argument """ This listener logs suite activity """ if self.__logging_activity_to_cidebug_log(): self.__run_ssh_commands(self._write_log('suite', 'ended', attrs)) self._ssh.close_connection() if self.__logging_activity(): # If the queue is full, don't write anything (since queue.put blocks, it would halt the test). # Otherwise, write the name and attrs to Elk if not self.activity_queue.full(): self.activity_queue.put_nowait(self.ElkItem('suite', self._add_data_to_attrs(name, attrs))) if attrs.get('id') == 's1': # In order to process all queue items before the test suite exits, # it's necessary to wait for the queue to become empty or until the timer expires. # Otherwise, the test will exit before the queue is fully written. start = datetime.datetime.now() while not self.activity_queue.empty() and (datetime.datetime.now() - start).total_seconds() < 10.0: sleep(1) def _start_test(self, name, attrs): # pylint: disable=unused-argument """ This listener logs test activity """ if self.__logging_activity_to_cidebug_log(): self.__run_ssh_commands(self._write_log('test case', 'started', attrs)) def _end_test(self, name, attrs): """ This listener logs test activity """ if self.__logging_activity_to_cidebug_log(): self.__run_ssh_commands(self._write_log('test case', 'ended', attrs)) # If the queue is full, don't write anything (since queue.put blocks, it would halt the test). # Otherwise, write the name and attrs to Elk if self.__logging_activity() and not self.activity_queue.full(): self.activity_queue.put_nowait(self.ElkItem('test', self._add_data_to_attrs(name, attrs))) def _start_keyword(self, name, attrs): # pylint: disable=unused-argument """ This listener logs keyword activity """ if self.__logging_activity_to_cidebug_log(): # filter out libraries and keyword types we're not interested in if attrs.get('libname') not in self.FILTER_LIBRARIES and attrs.get('type') not in ['For', 'For Item']: self.__run_ssh_commands(self._write_log('keyword', 'started', attrs)) def _end_keyword(self, name, attrs): """ This listener logs keyword activity """ if self.__logging_activity_to_cidebug_log(): # filter out libraries and keyword types we're not interested in if attrs.get('libname') not in self.FILTER_LIBRARIES and attrs.get('type') not in ['For', 'For Item']: self.__run_ssh_commands(self._write_log('keyword', 'ended', attrs)) if self.__logging_activity(): # filter out libraries and keyword types we're not interested in if attrs.get('libname') not in self.FILTER_LIBRARIES and attrs.get('type') not in ['For', 'For Item']: if not self.activity_queue.full(): self.activity_queue.put_nowait(self.ElkItem('keyword', self._add_data_to_attrs(name, attrs)))
print( "Virtual Machine: PSRV1 returned no response\nPowering On Virtual Machine: PSRV2\n" ) ssh.start_command("vim-cmd vmsvc/power.on 24") else: print("Ping successful") if "Powered on" in PSRV2: print("Virtual Machine: PSRV2 is Online") ssh.start_command("vim-cmd vmsvc/power.off 24") print("Powering Off Virtual Machine: PRSV2") if "100% packet loss" in pingResponse2: print("Attempting to restart Net Adapter on PSRV1") restartNetAdapter() # If PSRV1 is OFF: else: # If PSRV2 is ON: if "Powered on" in PSRV2: pass else: # If PSRV2" is OFF: print( "PSRV1 appears to be offline.\nPowering Up Virtual Machine: PSRV2" ) ssh.start_command("vim-cmd vmsvc/power.on 24") time.sleep(2) print("Waiting 10 seconds") time.sleep(10) ssh.close_connection()
ssh.write("_shell",loglevel="DEBUG") line = ssh.read_until_prompt(loglevel="DEBUG") m1 = re.search("^(?P<shellPrompt>\[\S+@\S+\s+\S+\]\s*#)\s*",line.strip(),re.MULTILINE) if m1: shellPrompt = m1.group("shellPrompt") print shellPrompt ssh.set_client_configuration(prompt=shellPrompt) ssh.write("echo 'show pm process'|/opt/tms/bin/cli -m config") output = ssh.read_until_prompt() #print output processes = [] state = [] process_state = {} output = str(output) for i in output.splitlines(): m1 = re.search('^Process\s(\S+)',i) m2 = re.search('^Current status:\s+(\w+)$',i.strip(),re.MULTILINE) if m1: processes.append(m1.group(1)) if m2: state.append(m2.group(1)) else: m2 = re.search('Current status:$',i.strip(),re.MULTILINE) if m2: state.append("No status") print dict(zip(processes,state)) ssh.close_connection()
class SSHLibraryPlugInWrapper(plugin_runner_abstract, metaclass=ABCMeta): def __init__(self, parameters: DotDict, data_handler, *user_args, **user_options): self._sudo_expected = is_truthy(user_options.pop('sudo', False)) self._sudo_password_expected = is_truthy( user_options.pop('sudo_password', False)) super().__init__(parameters, data_handler, *user_args, **user_options) self._execution_counter = 0 self._ssh = SSHLibrary() @property def content_object(self): return self._ssh @property def sudo_expected(self): return self._sudo_expected @property def sudo_password_expected(self): return self._sudo_password_expected def _close_ssh_library_connection_from_thread(self): try: with self._lock: self._ssh.close_connection() except RuntimeError: pass except Exception as e: if 'Logging background messages is only allowed from the main thread' in str( e): logger.warn(f"Ignore SSHLibrary error: '{e}'") return True raise def _evaluate_tolerance(self): if len(self._session_errors) == self._fault_tolerance: e = PlugInError( f"{self}", "PlugIn stop invoked; Errors count arrived to limit ({})". format( self.host_alias, self._fault_tolerance, ), *self._session_errors) logger.error(f"{e}") GlobalErrors().append(e) return False return True def login(self): host = self.parameters.host port = self.parameters.port username = self.parameters.username password = self.parameters.password certificate = self.parameters.certificate if len(self._session_errors) == 0: logger.info(f"Host '{self.host_alias}': Connecting") else: logger.warn( f"Host '{self.host_alias}': Restoring at {len(self._session_errors)} time" ) self._ssh.open_connection(host, repr(self), port) start_ts = datetime.now() while True: try: if certificate: logger.debug( f"Host '{self.host_alias}': Login with user/certificate" ) self._ssh.login_with_public_key(username, certificate, '') else: logger.debug( f"Host '{self.host_alias}': Login with user/password") self._ssh.login(username, password) except paramiko.AuthenticationException: raise except Exception as e: logger.warn( f"Host '{self.host_alias}': Connection failed; Reason: {e}" ) else: self._is_logged_in = True logger.info( f"Host '{self.host_alias}': Connection established") break finally: duration = (datetime.now() - start_ts).total_seconds() if duration >= self.parameters.timeout: raise TimeoutError( f"Cannot connect to '{self.host_alias}' during {self.parameters.timeout}s" ) def exit(self): if self._is_logged_in: self._ssh.switch_connection(repr(self)) self._close_ssh_library_connection_from_thread() self._is_logged_in = False logger.info( f"Host '{self.id}::{self.host_alias}': Connection closed") else: logger.info( f"Host '{self.id}::{self.host_alias}': Connection close not required (not opened)" )