python ftp upload

To upload a file to an FTP server using Python, you can use the built-in ftplib library. Below is an example of how to upload a file to an FTP server.

Code Example for FTP Upload

from ftplib import FTP

def upload_file(ftp_host, ftp_user, ftp_password, file_path, remote_path):
    try:
        # Connect to the FTP server
        ftp = FTP(ftp_host)
        ftp.login(user=ftp_user, passwd=ftp_password)
        print(f"Connected to {ftp_host}")

        # Open the file in binary mode
        with open(file_path, 'rb') as f:
            # Upload the file to the specified path on the FTP server
            ftp.storbinary(f'STOR {remote_path}', f)
            print(f"Successfully uploaded {file_path} to {remote_path}")

        # Close the connection
        ftp.quit()
    except Exception as e:
        print(f"Error: {e}")

# Example usage
ftp_host = 'ftp.example.com'
ftp_user = 'your_username'
ftp_password = 'your_password'
file_path = 'local_file.txt'  # Path to the local file you want to upload
remote_path = 'remote_directory/remote_file.txt'  # Path on the server

upload_file(ftp_host, ftp_user, ftp_password, file_path, remote_path)

Explanation

  1. Importing the library:
    We import the FTP class from ftplib to handle the FTP connection.

  2. Connecting to the FTP server:
    We use ftp.login() to log in using the provided credentials.

  3. Uploading the file:

    • We open the file in binary mode ('rb').
    • We use the ftp.storbinary() method to upload the file. The first parameter is the FTP command ('STOR'), followed by the remote path where the file will be uploaded.
    • The second parameter is the file object to upload.
  4. Handling exceptions:
    We wrap the code in a try...except block to catch any connection or file transfer errors.

  5. Closing the connection:
    After the transfer is complete, the FTP connection is closed using ftp.quit().

Notes:

  • Make sure the paths are correct: Ensure both file_path and remote_path are valid.
  • Firewall and permissions: Ensure the FTP server allows uploads and that you have the necessary permissions.
  • FTP in passive mode: If you encounter connection issues, you can switch to passive mode using ftp.set_pasv(True). This might be necessary if the server is behind a firewall.

This code will help you upload files via FTP easily using Python. If your server supports SFTP (secure FTP), you'll need to use a different library, such as paramiko. Let me know if you need help with that!

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

vsftpd default directory

[Ubuntu] *.deb 파일 설치 방법

Offset out of range error in Kafka, 카프카 트러블슈팅

리눅스 (cron - 주기적 작업실행 데몬)

리눅스 (하드링크&소프트링크)

CDPEvents in puppeteer

Using venv in Python