Python Basics (37 Part Series)
1 Determining Python Version using the sys Library
2 Terminating a Python Program Using the Exit Function
… 33 more parts…
3 Python: A Guide to Variables
4 Python: Interacting with Users and Handling Sensitive Information
5 Python: Understanding Boolean Values and Operators
6 Introduction to the Python Math Library
7 Introduction to the Python Random Library
8 Working with Bytes in Python
9 Working with Tuples in Python
10 Working with Named Tuples in Python
11 Exploring Deques in Python
12 Python: A Guide to For and While Loops
13 Python: A Guide to Functions
14 Python: A Guide to Lambda Functions
15 Introduction to Classes in Python
16 Introduction to Python Modules and Libraries
17 Handling Exceptions in Python
18 Conditional Statements in Python
19 Disassembling Python Bytecode with the dis Library
20 Datetime Manipulation in Python
21 Using tomllib for Configuration in Python
22 Exploring the os Library With Python
23 Exploring API Requests in Python with the Official Joke API
24 Exploring Alice in Wonderland through Text Files in Python
25 Embracing the Zen of Python: A Guide to Pythonic Programming
26 Exploring the Antigravity Library in Python
27 Working with CSV Files in Python
28 Python Script Structure
29 Introduction to Logging in Python
30 Understanding Dataclasses in Python
31 Understanding the map Function in Python
32 Exploring (Some) Python Integrated Development Environments
33 Conversions in Python
34 Working with XlsxWriter in Python
35 Fortanix Library: Authentication and Security Object Retrieval
36 Interacting with SFTP Repositories: A Paramiko Integration
37 Exploring SharePoint with Microsoft Graph API
Introduction
This article explores a Python library designed to interact with Secure File Transfer Protocol (SFTP) repositories. Specifically, it integrates with Fortanix, a cryptographic operations platform. The library leverages Paramiko, a Python implementation of the SSH protocol, to facilitate secure communication with remote servers. Through this article, we’ll delve into the functionalities provided by this library, examining its core components and demonstrating their usage.
Index
- Configuration Dataclass
- SFTP Class Initialisation
- Authentication Process
- File Operations
- Listing Files
- Changing Directory
- Deleting Files
- Downloading Files
- Uploading Files
- Cleanup Process
Code Examples
Configuration Dataclass
import base64
from dataclasses import dataclass
import logging
import paramiko
@dataclass
class Configuration:
""" Dataclass to store SFTP configuration details. Attributes: host (str): The hostname or IP address of the SFTP server. port (int): The port number of the SFTP server. username (str): The username used for authentication. password (str): The password used for authentication. """
host: str = None
port: int = None
username: str = None
password: str = None
Enter fullscreen mode Exit fullscreen mode
SFTP Class Initialisation
class SFTP(object):
""" Class to interact with SFTP repositories. Methods: __init__: Initializes variables and performs authentication. auth: Performs authentication process. list_dir: Lists all files in the current directory. change_dir: Changes current directory. delete_file: Deletes a file from the current directory. download: Downloads a file from the SFTP server. upload: Uploads a file to the SFTP server. __del__: Cleans up resources upon object deletion. """
def __init__(self, credentials: dict) -> None:
""" Initializes variables and performs authentication. Args: credentials (dict): Credentials. """
# Logging configuration logging.basicConfig(level=logging.INFO, format="%(asctime)s %(module)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
# Credentials/configuration self.sftp_client: paramiko.sftp_client.SFTPClient = None
self.__transport: paramiko.transport.Transport = None
self.__transport, self.sftp_client = self.auth(credentials=credentials)
Enter fullscreen mode Exit fullscreen mode
Authentication Process
def auth(self, credentials: dict) -> tuple:
""" Authenticate (On-Premise). Performs the authentication process. Args: credentials (dict): A dictionary containing SFTP credentials. Returns: tuple: A tuple containing the Transport and SFTPClient objects. """
logging.info(msg="Opens session")
# Initialize local dataclass configuration = Configuration()
# Extract credentials configuration.host = credentials["custom_metadata"]["host"]
configuration.port = int(credentials["custom_metadata"]["port"])
configuration.username = credentials["custom_metadata"]["username"]
configuration.password = base64.b64decode(credentials["value"]).decode("utf-8")
# Establish connection transport = paramiko.Transport((configuration.host, configuration.port))
transport.connect(username=configuration.username, password=configuration.password)
sftp_client = paramiko.SFTPClient.from_transport(transport)
return transport, sftp_client
Enter fullscreen mode Exit fullscreen mode
File Operations
def list_dir(self, path: str = ".") -> list:
""" Lists all files in the current directory. Args: path (str, optional): The path to the target directory. Defaults to ".". Returns: list: A list of files in the specified directory. """
logging.info(msg="List files")
return self.sftp_client.listdir(path)
def change_dir(self, path: str = ".") -> None:
""" Changes the current directory. Args: path (str, optional): The path to the target directory. Defaults to ".". """
logging.info(msg="Change current directory")
self.sftp_client.chdir(path)
def delete_file(self, path: str) -> None:
""" Deletes a file from the current directory. Args: path (str): The path of the file to delete. """
logging.info(msg=f"Delete file {path}")
self.sftp_client.remove(path)
def download(self, remotepath: str, localpath: str) -> None:
""" Downloads a file from the SFTP server. Args: remotepath (str): The path of the file on the SFTP server. localpath (str): The destination path on the local host. """
logging.info(msg=f"Download file {remotepath}")
self.sftp_client.get(remotepath, localpath)
def upload(self, localpath: str, remotepath: str) -> None:
""" Uploads a file to the SFTP server. Args: localpath (str): The path of the file on the local host. remotepath (str): The destination path on the SFTP server. """
logging.info(msg=f"Upload file {localpath}")
self.sftp_client.put(localpath, remotepath)
Enter fullscreen mode Exit fullscreen mode
Cleanup Process
def __del__(self) -> None:
""" Cleans up resources upon object deletion. """
logging.info(msg="Closes session")
self.__transport.close()
self.sftp_client.close()
Enter fullscreen mode Exit fullscreen mode
Conclusion
This library provides a convenient interface for interacting with SFTP repositories, offering functionalities such as listing files, navigating directories, deleting, downloading, and uploading files. Leveraging the Paramiko library, it ensures secure communication with remote servers, making it suitable for various applications requiring file transfer capabilities over SSH connections.
Python Basics (37 Part Series)
1 Determining Python Version using the sys Library
2 Terminating a Python Program Using the Exit Function
… 33 more parts…
3 Python: A Guide to Variables
4 Python: Interacting with Users and Handling Sensitive Information
5 Python: Understanding Boolean Values and Operators
6 Introduction to the Python Math Library
7 Introduction to the Python Random Library
8 Working with Bytes in Python
9 Working with Tuples in Python
10 Working with Named Tuples in Python
11 Exploring Deques in Python
12 Python: A Guide to For and While Loops
13 Python: A Guide to Functions
14 Python: A Guide to Lambda Functions
15 Introduction to Classes in Python
16 Introduction to Python Modules and Libraries
17 Handling Exceptions in Python
18 Conditional Statements in Python
19 Disassembling Python Bytecode with the dis Library
20 Datetime Manipulation in Python
21 Using tomllib for Configuration in Python
22 Exploring the os Library With Python
23 Exploring API Requests in Python with the Official Joke API
24 Exploring Alice in Wonderland through Text Files in Python
25 Embracing the Zen of Python: A Guide to Pythonic Programming
26 Exploring the Antigravity Library in Python
27 Working with CSV Files in Python
28 Python Script Structure
29 Introduction to Logging in Python
30 Understanding Dataclasses in Python
31 Understanding the map Function in Python
32 Exploring (Some) Python Integrated Development Environments
33 Conversions in Python
34 Working with XlsxWriter in Python
35 Fortanix Library: Authentication and Security Object Retrieval
36 Interacting with SFTP Repositories: A Paramiko Integration
37 Exploring SharePoint with Microsoft Graph API
原文链接:Interacting with SFTP Repositories: A Paramiko Integration
暂无评论内容