コード例 #1
0
    def write_redirects_to_sftp(self, from_path, to_path, cron):
        try:
            ssh_key_object = RSAKey(filename=app.config['SFTP_SSH_KEY_PATH'],
                                    password=app.config['SFTP_SSH_KEY_PASSPHRASE'])

            remote_server_public_key = HostKeyEntry.from_line(app.config['SFTP_REMOTE_HOST_PUBLIC_KEY']).key
            # This will throw a warning, but the (string, int) tuple will automatically be parsed into a Socket object
            remote_server = Transport((app.config['SFTP_REMOTE_HOST'], 22))
            remote_server.connect(hostkey=remote_server_public_key, username=app.config['SFTP_USERNAME'], pkey=ssh_key_object)

            sftp = SFTPClient.from_transport(remote_server)
            sftp.put(from_path, to_path)
            if cron:
                return 'SFTP publish from %s to %s succeeded' % (from_path, to_path)
            else:
                return fjson.dumps({
                    'type': 'success',
                    'message': 'Redirect updates successful'
                })
        except:
            if cron:
                return 'SFTP publish from %s to %s failed' % (from_path, to_path)
            else:
                return fjson.dumps({
                    'type': 'danger',
                    'message': 'Redirect updates failed'
                })
コード例 #2
0
    def __getHostKey(self):
        if self.__hostKey == 'any':
            return None

        hostKeyEntry = HostKeyEntry.from_line(self.__hostKey)
            
        return hostKeyEntry.key
コード例 #3
0
    def load(self, filename):
        """Loads all known host keys from the storage backend."""
        self._entries = []

        lines = self.storage.read_host_keys()

        for line in lines:
            entry = HostKeyEntry.from_line(line)

            if entry is not None:
                self._entries.append(entry)
コード例 #4
0
def create_key(keytype, key):
    """
    Create an ssh-rsa, ssh-dss or ssh-ed25519 key.
    """
    l = "{hostname} {keytype} {key}".format(hostname="x",
                                            keytype=keytype,
                                            key=key)

    ke = HostKeyEntry.from_line(l)
    assert ke, f'invalid host key "{keytype} {key}"'
    return ke.key
コード例 #5
0
ファイル: commands.py プロジェクト: sberkun/ocfweb
def commands(request: HttpRequest) -> HttpResponse:
    command_to_run = ''
    output = ''
    error = ''
    if request.method == 'POST':
        form = CommandForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            command_to_run = form.cleaned_data['command_to_run']

            ssh = SSHClient()

            host_keys = ssh.get_host_keys()
            entry = HostKeyEntry.from_line(
                'ssh.ocf.berkeley.edu ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAqMkHVVoMl8md25iky7e2Xe3ARaC4H1PbIpv5Y+xT4KOT17gGvFSmfjGyW9P8ZTyqxq560iWdyELIn7efaGPbkUo9retcnT6WLmuh9nRIYwb6w7BGEEvlblBmH27Fkgt7JQ6+1sr5teuABfIMg22WTQAeDQe1jg0XsPu36OjbC7HjA3BXsiNBpxKDolYIXWzOD+r9FxZLP0lawh8dl//O5FW4ha1IbHklq2i9Mgl79wAH3jxf66kQJTvLmalKnQ0Dbp2+vYGGhIjVFXlGSzKsHAVhuVD6TBXZbxWOYoXanS7CC43MrEtBYYnc6zMn/k/rH0V+WeRhuzTnr/OZGJbBBw==',  # noqa
            )
            host_keys.add(
                'ssh.ocf.berkeley.edu',
                'ssh-rsa',
                entry.key,
            )

            try:
                ssh.connect(
                    'ssh.ocf.berkeley.edu',
                    username=username,
                    password=password,
                )
            except AuthenticationException:
                error = 'Authentication failed. Did you type the wrong username or password?'

            if not error:
                _, ssh_stdout, ssh_stderr = ssh.exec_command(command_to_run,
                                                             get_pty=True)
                output = ssh_stdout.read().decode()
                error = ssh_stderr.read().decode()
    else:
        form = CommandForm()

    return render(
        request,
        'account/commands/index.html',
        {
            'title': 'Account commands',
            'form': form,
            'command': command_to_run,
            'output': output,
            'error': error,
        },
    )
コード例 #6
0
ファイル: commands.py プロジェクト: tmochida/ocfweb
def commands(request):
    command_to_run = ''
    output = ''
    error = ''
    if request.method == 'POST':
        form = CommandForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            command_to_run = form.cleaned_data['command_to_run']

            ssh = SSHClient()

            host_keys = ssh.get_host_keys()
            entry = HostKeyEntry.from_line(
                'ssh.ocf.berkeley.edu ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAqMkHVVoMl8md25iky7e2Xe3ARaC4H1PbIpv5Y+xT4KOT17gGvFSmfjGyW9P8ZTyqxq560iWdyELIn7efaGPbkUo9retcnT6WLmuh9nRIYwb6w7BGEEvlblBmH27Fkgt7JQ6+1sr5teuABfIMg22WTQAeDQe1jg0XsPu36OjbC7HjA3BXsiNBpxKDolYIXWzOD+r9FxZLP0lawh8dl//O5FW4ha1IbHklq2i9Mgl79wAH3jxf66kQJTvLmalKnQ0Dbp2+vYGGhIjVFXlGSzKsHAVhuVD6TBXZbxWOYoXanS7CC43MrEtBYYnc6zMn/k/rH0V+WeRhuzTnr/OZGJbBBw==',  # noqa
            )
            host_keys.add(
                'ssh.ocf.berkeley.edu',
                'ssh-rsa',
                entry.key,
            )

            try:
                ssh.connect(
                    'ssh.ocf.berkeley.edu',
                    username=username,
                    password=password,
                )
            except AuthenticationException:
                error = 'Authentication failed. Did you type the wrong username or password?'

            if not error:
                _, ssh_stdout, ssh_stderr = ssh.exec_command(command_to_run)
                output = ssh_stdout.read()
                error = ssh_stderr.read()
    else:
        form = CommandForm()

    return render(
        request,
        'account/commands/index.html', {
            'title': 'Account commands',
            'form': form,
            'command': command_to_run,
            'output': output,
            'error': error,
        },
    )
コード例 #7
0
def __validate_known_hosts(knownhost_data):
    knownhost_str = __from_base64(knownhost_data).decode('utf-8')
    lines = knownhost_str.split('\n')
    for line in lines:
        line = line.strip(' ')
        line_len = len(line)
        if (line_len == 0) or (line[0] == "#"):
            continue
        try:
            host_key = HostKeyEntry.from_line(line)
            if not host_key:
                raise Exception('not enough fields found in known_hosts line')
        except Exception as ex:
            raise CLIError('Error! ssh known_hosts provided in wrong format, ensure your '
                           'known_hosts provided is valid') from ex
コード例 #8
0
 def set_up_connection_options(prefix: str, host: str) -> CnOpts:
     connection_options = CnOpts()
     try:
         connection_options.get_hostkey(host)
     except SSHException as s:
         hostkey = secrets.get_secret(f"{prefix}_hostkey")
         if hostkey is None:
             raise ValueError(
                 f"Unable to find hostkey for secret key {prefix}_hostkey"
             ) from s
         hostkeyEntry = HostKeyEntry.from_line(hostkey)
         if hostkeyEntry:
             key = hostkeyEntry.key
             name, keytype, _ = hostkey.split(" ")
             connection_options.hostkeys.add(name, keytype, key)
         else:
             raise ValueError(
                 f"Unable to add hostkey to connection_options for secret key {prefix}_hostkey"
             ) from s
     return connection_options
コード例 #9
0
ファイル: ssh_client.py プロジェクト: PravinRanjan10/delfin
 def set_host_key(self, host_key):
     """
     Set public key,because input kwargs parameter host_key is string,
     not a file path,we can not use load file to get public key,so we set
     it as a string.
     :param str host_key: the public key which as a string
     """
     if (len(host_key) == 0) or (host_key[0] == "#"):
         return
     try:
         e = HostKeyEntry.from_line(host_key)
     except exception.SSHException:
         return
     if e is not None:
         host_names = e.hostnames
         for h in host_names:
             if self.ssh._host_keys.check(h, e.key):
                 e.hostnames.remove(h)
         if len(e.hostnames):
             self.ssh._host_keys._entries.append(e)
コード例 #10
0
def validate_known_hosts(knownhost_data):
    try:
        knownhost_str = from_base64(knownhost_data).decode('utf-8')
    except Exception as ex:
        raise InvalidArgumentValueError(
            'Error! ssh known_hosts is not a valid utf-8 base64 encoded string',
            'Verify that the string provided safely decodes into a valid utf-8 format') from ex
    lines = knownhost_str.split('\n')
    for line in lines:
        line = line.strip(' ')
        line_len = len(line)
        if (line_len == 0) or (line[0] == "#"):
            continue
        try:
            host_key = HostKeyEntry.from_line(line)
            if not host_key:
                raise Exception('not enough fields found in known_hosts line')
        except Exception as ex:
            raise InvalidArgumentValueError(
                'Error! ssh known_hosts provided in wrong format',
                'Verify that all lines in the known_hosts contents are provided in a valid sshd(8) format') from ex
コード例 #11
0
def validate_known_hosts(knownhost_data):
    try:
        knownhost_str = from_base64(knownhost_data).decode('utf-8')
    except Exception as ex:
        raise InvalidArgumentValueError(
            consts.KNOWN_HOSTS_BASE64_ENCODING_ERROR,
            consts.KNOWN_HOSTS_BASE64_ENCODING_HELP) from ex
    lines = knownhost_str.split('\n')
    for line in lines:
        line = line.strip(' ')
        line_len = len(line)
        if (line_len == 0) or (line[0] == "#"):
            continue
        try:
            host_key = HostKeyEntry.from_line(line)
            if not host_key:
                raise Exception('not enough fields found in known_hosts line')
        except Exception as ex:
            raise InvalidArgumentValueError(
                consts.KNOWN_HOSTS_FORMAT_ERROR,
                consts.KNOWN_HOSTS_FORMAT_HELP) from ex