How to use the paramiko.SSHException function in paramiko

To help you get started, we’ve selected a few paramiko examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gc3pie / gc3pie / gc3utils / gc3utils / SshLRMS.py View on Github external
or a new instance of the `Job` class if `job` is `None` (default).

        On the backend, the command will look something like this:
        # ssh user@remote_frontend 'cd unique_token ; $gamess_location -n cores input_file'
        """
        # Establish an ssh connection.
        (ssh, sftp) = self._connect_ssh(self._resource.frontend,self._ssh_username)

        # Create the remote unique_token directory. 
        try:
            _command = 'mkdir -p $HOME/.gc3utils_jobs; mktemp -p $HOME/.gc3utils_jobs -d lrms_job.XXXXXXXXXX'
            exit_code, stdout, stderr = self._execute_command(ssh, _command)
            if exit_code == 0:
                ssh_remote_folder = stdout.split('\n')[0]
            else:
                raise paramiko.SSHException('Failed while executing remote command')
        except:
            gc3utils.log.critical("Failed creating remote temporary folder: command '%s' returned exit code %d)"
                                  % (_command, exit_code))

            if not ssh  is None:
                ssh.close()
            raise

        # Copy the input file to remote directory.
        for input in application.inputs.items():
            local_path, remote_path = input
            remote_path = os.path.join(ssh_remote_folder, remote_path)

            gc3utils.log.debug("Transferring file '%s' to '%s'" % (local_path, remote_path))
            try:
                sftp.put(local_path, remote_path)
github austind / iosfw / iosfw / iosfw.py View on Github external
self.napalm_args = {
            "hostname": self.hostname,
            "username": self.username,
            "password": self.password,
            "timeout": self.timeout,
            "optional_args": self.optional_args,
        }
        self.napalm = self.napalm_driver(**self.napalm_args)
        self.log.info("===============================================")
        self.log.info(
            f"Opening connection to {self.hostname} via {primary_transport}..."
        )
        #self.log.debug(pprint.pprint(self.napalm_args))
        try:
            self.napalm.open()
        except (socket.timeout, SSHException, ConnectionRefusedError):
            if len(self.config["ctl_transport"]) > 1:
                secondary_transport = self.config["ctl_transport"][1]
                self.log.warning(
                    f"Unable to connect via {primary_transport}, attempting {secondary_transport}."
                )
                self._swap_transport(secondary_transport)
            else:
                self.log.critical(
                    f"Unable to connect via {primary_transport} and no alternate given. Cannot continue."
                )
                exit(1)

        # Aliases and info
        self.device = self.napalm.device  # Netmiko session
        self.facts = self.napalm.get_facts()  # NAPALM facts
        self.os_version = self.facts["os_version"]
github muccg / yabi / yabibe / yabibe / utils / protocol / ssh / paramiko-ssh.py View on Github external
def missing_host_key(self, client, hostname, key):
                add_rejected_key_to_admin(hostname, key)
                raise paramiko.SSHException("Remote host key is denied. Please verify fingerprint and mark as allowed in admin to allow a connection to the host.")
github Parsl / parsl / parsl / channels / ssh / ssh.py View on Github external
password=password,
                port=port,
                allow_agent=True,
                gss_auth=gssapi_auth,
                gss_kex=gssapi_auth,
            )
            t = self.ssh_client.get_transport()
            self.sftp_client = paramiko.SFTPClient.from_transport(t)

        except paramiko.BadHostKeyException as e:
            raise BadHostKeyException(e, self.hostname)

        except paramiko.AuthenticationException as e:
            raise AuthException(e, self.hostname)

        except paramiko.SSHException as e:
            raise SSHException(e, self.hostname)

        except Exception as e:
            raise SSHException(e, self.hostname)
github muccg / yabi / yabibe / yabibe / utils / protocol / ssh / paramiko-ssh.py View on Github external
raise paramiko.SSHException("Trying to connect to unknown host. Remote host key not found in %s" % (KNOWN_HOSTS_FILE))

        return ssh

    elif options.password:
        # establish connection
        ssh.connect(username=options.username, password=options.password)

        if CHECK_KNOWN_HOSTS:
            remote_key = ssh.get_remote_server_key()
            known = known_hosts.check(options.hostname, remote_key)

            if not known:
                add_rejected_key_to_admin(options.hostname, remote_key)
                if yabiadmin:
                    raise paramiko.SSHException("Remote host key is denied. Please verify fingerprint and mark as allowed in admin to allow a connection to the host.")
                else:
                    raise paramiko.SSHException("Trying to connect to unknown host. Remote host key not found in %s" % (KNOWN_HOSTS_FILE))

        return ssh

    raise Exception("Unknown login method. Both identity and password are unset")
github guardicore / monkey / monkey / infection_monkey / exploit / sshexec.py View on Github external
def exploit_with_ssh_keys(self, port, ssh):
        user_ssh_key_pairs = self._config.get_exploit_user_ssh_key_pairs()

        exploited = False

        for user, ssh_key_pair in user_ssh_key_pairs:
            # Creating file-like private key for paramiko
            pkey = StringIO.StringIO(ssh_key_pair['private_key'])
            ssh_string = "%s@%s" % (ssh_key_pair['user'], ssh_key_pair['ip'])
            try:
                pkey = paramiko.RSAKey.from_private_key(pkey)
            except(IOError, paramiko.SSHException, paramiko.PasswordRequiredException):
                LOG.error("Failed reading ssh key")
            try:
                ssh.connect(self.host.ip_addr,
                            username=user,
                            pkey=pkey,
                            port=port,
                            timeout=None)
                LOG.debug("Successfully logged in %s using %s users private key",
                          self.host, ssh_string)
                exploited = True
                self.report_login_attempt(True, user, ssh_key=ssh_string)
                break
            except Exception as exc:
                LOG.debug("Error logging into victim %r with %s"
                          " private key", self.host,
                          ssh_string)
github hequan2017 / autoops / webssh / main.py View on Github external
def get_specific_pkey(self, pkeycls, privatekey, password):
        logging.info('Trying {}'.format(pkeycls.__name__))
        try:
            pkey = pkeycls.from_private_key(io.StringIO(privatekey),
                                            password=password)
        except paramiko.PasswordRequiredException:
            raise ValueError('Need password to decrypt the private key.')
        except paramiko.SSHException:
            pass
        else:
            return pkey
github allegro / ralph / src / ralph / discovery / plugins / ssh_onstor.py View on Github external
return False, 'no credentials.', kwargs
    if 'nx-os' in kwargs.get('snmp_name', '').lower():
        return False, 'incompatible Nexus found.', kwargs
    ip = str(kwargs['ip'])
    if kwargs.get('http_family') not in ('sscccc',):
        return False, 'no match.', kwargs
    if not network.check_tcp_port(ip, 22):
        DiscoveryWarning(
            message="Port 22 closed on an Onstor device.",
            plugin=__name__,
            ip=ip,
        ).save()
        return False, 'closed.', kwargs
    try:
        name = _run_ssh_onstor(ip)
    except (network.Error, Error, paramiko.SSHException) as e:
        DiscoveryWarning(
            message="This is an Onstor, but: " + str(e),
            plugin=__name__,
            ip=ip,
        ).save()
        return False, str(e), kwargs
    return True, name, kwargs
github stewartadam / fwbackups / src / fwbackups / operations / restore.py View on Github external
return False
      elif type(thread.exception) == paramiko.AuthenticationException:
        self.logger.logmsg('ERROR', _('A connection was established, but authentication ' + \
                        'failed. Please verify the username and password ' + \
                        'and try again.'))
        return False
      elif type(thread.exception) == socket.gaierror or type(thread.exception) == socket.error:
        self.logger.logmsg('ERROR', _('A connection to the server could not be established.\n' + \
                        'Error %(a)s: %(b)s' % {'a': type(thread.exception), 'b': str(thread.exception)} + \
                        '\nPlease verify your settings and try again.'))
        return False
      elif type(thread.exception) == socket.timeout:
        self.logger.logmsg('ERROR', _('A connection to the server has timed out. ' + \
                        'Please verify your settings and try again.'))
        return False
      elif type(thread.exception) == paramiko.SSHException:
        self.logger.logmsg('ERROR', _('A connection to the server could not be established ' + \
                        'because an error occurred: %s' % str(thread.exception) + \
                        '\nPlease verify your settings and try again.'))
        return False
    # source types:     'set' 'local archive' 'local folder'
    #                   'remote archive (SSH)', 'remote folder (SSH)'

    # We don't want to raise a hard error, that's already in the log.
    # So we settle for a simple return false.
    # don't need source type logic, /destination/ is always a folder
    if not self.prepareDestinationFolder(self.options['Destination']):
      return False
    # Receive files from remote server
    if self.options['RemoteSource']:
      self.logger.logmsg('INFO', _('Receiving files from server'))
      self._status = STATUS_RECEIVING_FROM_REMOTE # receiving files
github funcx-faas / funcX / funcx / executor / parsl / channels / ssh / ssh.py View on Github external
username=username,
                password=password,
                allow_agent=True,
                gss_auth=gssapi_auth,
                gss_kex=gssapi_auth,
            )
            t = self.ssh_client.get_transport()
            self.sftp_client = paramiko.SFTPClient.from_transport(t)

        except paramiko.BadHostKeyException as e:
            raise BadHostKeyException(e, self.hostname)

        except paramiko.AuthenticationException as e:
            raise AuthException(e, self.hostname)

        except paramiko.SSHException as e:
            raise SSHException(e, self.hostname)

        except Exception as e:
            raise SSHException(e, self.hostname)