ecerulm commented on issue #16738: URL: https://github.com/apache/airflow/issues/16738#issuecomment-872055759
> there is not any real way around this well as @potiuk suggested you can catch it at https://github.com/apache/airflow/blob/a2d6aa07c9de83278eef14a228eb4a02ad43205c/airflow/providers/ssh/hooks/ssh.py#L268 when you are actually trying to use the key. Or introduce a IMHO more correct `private_key_type` in connection extras, that is the approach I use now. I did my own impl of SFTPToS3Operator and SSHHook to overcome this problem ``` # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import posixpath import stat from io import StringIO from tempfile import NamedTemporaryFile from typing import Optional from urllib.parse import urlparse import paramiko from airflow import AirflowException from airflow.models import BaseOperator from airflow.providers.amazon.aws.hooks.s3 import S3Hook from airflow.providers.ssh.hooks.ssh import SSHHook as AirflowSSHHook class SSHHook(AirflowSSHHook): def __init__( # pylint: disable=too-many-statements self, ssh_conn_id: Optional[str] = None, remote_host: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, key_file: Optional[str] = None, port: Optional[int] = None, timeout: int = 10, keepalive_interval: int = 30, ) -> None: # Use connection to override defaults self.private_key_type = None if ssh_conn_id is not None: conn = self.get_connection(ssh_conn_id) if conn.extra is not None: extra_options = conn.extra_dejson self.private_key_type = extra_options.get("private_key_type") super().__init__(ssh_conn_id, remote_host, username, password, key_file, port, timeout, keepalive_interval) def _pkey_from_private_key(self, private_key: str, passphrase: Optional[str] = None) -> paramiko.PKey: """ Creates appropriate paramiko key for given private key :param private_key: string containing private key :return: `paramiko.PKey` appropriate for given key :raises AirflowException: if key cannot be read """ allowed_pkey_types = self._default_pkey_mappings.values() if self.private_key_type: allowed_pkey_types = [self._default_pkey_mappings[self.private_key_type]] for pkey_type in allowed_pkey_types: try: key = pkey_type.from_private_key(StringIO(private_key), password=passphrase) return key except paramiko.ssh_exception.SSHException: continue raise AirflowException( 'Private key provided cannot be read by paramiko.' 'Ensure key provided is valid for one of the following' 'key formats: RSA, DSS, ECDSA, or Ed25519' ) class SFTPToS3Operator(BaseOperator): """ This operator enables the transferring of files from a SFTP server to Amazon S3. :param sftp_conn_id: The sftp connection id. The name or identifier for establishing a connection to the SFTP server. :type sftp_conn_id: str :param sftp_path: The sftp remote path. This is the specified file path for downloading the file from the SFTP server. :type sftp_path: str :param s3_conn_id: The s3 connection id. The name or identifier for establishing a connection to S3 :type s3_conn_id: str :param s3_bucket: The targeted s3 bucket. This is the S3 bucket to where the file is uploaded. :type s3_bucket: str :param s3_key: The targeted s3 key. This is the specified path for uploading the file to S3. :type s3_key: str """ template_fields = ('s3_key', 'sftp_path') def __init__( self, *, s3_bucket: str, s3_key: str, sftp_path: str, sftp_conn_id: str = 'ssh_default', s3_conn_id: str = 'aws_default', **kwargs, ) -> None: super().__init__(**kwargs) self.sftp_conn_id = sftp_conn_id self.sftp_path = sftp_path self.s3_bucket = s3_bucket self.s3_key = s3_key self.s3_conn_id = s3_conn_id @staticmethod def get_s3_key(s3_key: str) -> str: """This parses the correct format for S3 keys regardless of how the S3 url is passed.""" parsed_s3_key = urlparse(s3_key) return parsed_s3_key.path.lstrip('/') def execute(self, context) -> None: self.s3_key = self.get_s3_key(self.s3_key) ssh_hook = SSHHook(ssh_conn_id=self.sftp_conn_id) s3_hook = S3Hook(self.s3_conn_id) self.sftp_client = ssh_hook.get_conn().open_sftp() self.sftp_list_client = ssh_hook.get_conn().open_sftp() for path,s3_key in self._walk(self.sftp_path): with NamedTemporaryFile("w") as f: self.sftp_client.get(path, f.name) self.log.info(f"Uploading SFTP file ({path}) to S3 bucket ({self.s3_bucket} and S3 key ({s3_key})") s3_hook.load_file(filename=f.name, key=s3_key, bucket_name=self.s3_bucket, replace=True) self.log.info(f"File uploaded to S3 {s3_key}") self.sftp_client.close() self.sftp_list_client.close() def _walk(self, path): if not stat.S_ISDIR(self.sftp_list_client.lstat(path).st_mode): yield (path, self.s3_key) else: yield from self._walkdir(path) def _walkdir(self, path): # Recurse into dir for x in self.sftp_list_client.listdir_iter(path): sftp_full_path = f"{path}/{x.filename}" if not stat.S_ISDIR(x.st_mode): s3_rel_path = posixpath.relpath(sftp_full_path, self.sftp_path) s3_full_path = posixpath.normpath(f"{self.s3_key}/{s3_rel_path}") yield (sftp_full_path, s3_full_path) else: yield from self._walkdir(sftp_full_path) ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
