SFTP 업로드/다운로드 모듈 만들기

DM·2023년 1월 14일
0
post-thumbnail

타 기관과 파일을 주고받기 위해 SFTP를 사용하기로 했는데
서버를 제공받기 전, 직접 만들어 Dev서버에서 테스트 해봤습니다.

SFTP란?

FTP는 File Transfer Protocol. 말 그대로 파일을 전송하는 통신 규약입니다.

원격에 있는 서버에 파일을 주고 받을 때 사용하는 인터넷 통신 규약으로, 여기에 보안이 추가된 SFTP가 있습니다.

Secure File Transfer Protocol 의 약자로, FTP 와 달리 클라이언트와 서버간의 데이터 전송을 암호화하기 때문에 해킹이나 보안상의 문제점을 방지합니다.

SFTP 서버 만들기

AWS Transfer Family SFTP 서버를 사용했고, 미리 만들어놓은 S3로 업로드/다운로드 합니다.

생성

사용자 추가 (s3)

FileZilla 를 통해 서버 접속이 유효한지 확인했습니다.

잘동작하네요~

paramiko

이제 수동이 아니라 코드로 파일을 업로드/다운로드를 구현하기만 하면 됩니다.
저는 Python/Django 를 사용하고 있고, python 에는 paramiko 라는 SSH 사용이 가능한 패키지가 있습니다!

# sftp.py

class Sftp:
    client: SSHClient = SSHClient()
    sftp: SFTPClient

    def __init__(self, host: str, user: str, key_file: str):
        if not os.path.exists(key_file):
            raise FileNotFoundError("Sftp.pem file not found")

        key = RSAKey.from_private_key_file(key_file) # pem key file 경로
        self.client.set_missing_host_key_policy(AutoAddPolicy())
        try:
            self.client.connect(host, username=user, pkey=key) # 유저이름과 키를 확인하고 connection
        except socket.error:
            raise SSHException('Connection error')

        self.sftp = self.client.open_sftp()

    def upload(self, local_path, remote_path):
        if not os.path.exists(local_path):
            self.client.close()
            raise FileNotFoundError("File not found")

        self.sftp.put(local_path, remote_path) # 파일 업로드
        self.client.close() # connetion close

    def download(self, local_path, remote_path):
        try:
            self.sftp.get(remote_path, local_path) # 파일 다운로드
        except IOError as e:
            raise e('Failed to find remote file')
        finally:
            self.client.close() # connetion close

구현한 클래스를 통해 파일을 업로드 해보겠습니다.

# execute.py

sftp = Sftp(host=settings.SFTP_HOST,
            user=settings.SFTP_USER,
            key_file=settings.SFTP_PEM_FILE_PATH,
        )
sftp.upload(file_path, 'test_sftp.txt')

S3에서 업로드가 잘 된것을 확인할 수 있습니다.

profile
BE

0개의 댓글