Python Forum
A working code to upload a file using sftp?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A working code to upload a file using sftp?
#1
Can anyone share a presently working Python code that uploads a local file to a publicly accessible FTP server for testing purposes? I have tried several codes published in various web pages, and each time some exception was raised.
Reply
#2
Well, I found too many codes for the same thing, can you try the below code, I hope you can get an idea of what you are looking for.

Quote:from ftplib import FTP

# FTP server details
ftp_host = 'ftp.example.com' # Replace with your FTP server address
ftp_user = 'your_username' # Replace with your FTP username
ftp_pass = 'your_password' # Replace with your FTP password

# Local file to upload
local_file_path = 'local_file.txt' # Replace with the path to your local file

# Remote directory where you want to upload the file
remote_directory = '/public_html/' # Replace with the desired remote directory

try:
# Connect to the FTP server
ftp = FTP(ftp_host)
ftp.login(user=ftp_user, passwd=ftp_pass)

# Change to the target directory on the server
ftp.cwd(remote_directory)

# Open the local file in binary mode for uploading
with open(local_file_path, 'rb') as local_file:
# Upload the file to the FTP server
ftp.storbinary('STOR ' + local_file_path, local_file)

print(f"File '{local_file_path}' uploaded successfully to '{remote_directory}'")

# Close the FTP connection
ftp.quit()

except Exception as e:
print(f"An error occurred: {e}")

Thanks
Reply
#3
Usually, I just spawn a subprocess that calls the lftp command.
Reply
#4
Why not just use Filezilla?

Filezilla uses sftp.

When I make my pathetically simple little webpages, I always make them and test them on this laptop. When everything works the way I want, I upload with Filezilla!

Unless you are are serial uploader!?!
Reply
#5
I've come upon this source which gives a working solution for interfacing with a SSH File Transfer Protocol server:
https://docs.couchdrop.io/walkthroughs/u...-with-sftp
Reply
#6
An example with paramiko:

from getpass import getpass
from stat import S_IFDIR 
from paramiko import SSHClient, AutoAddPolicy, SFTPAttributes


FILE = "/home/public/test.txt"
DIR = "/home/public"
HOST = "server.domain.tld"


def by_mtime(file: SFTPAttributes) -> float:
    return file.st_mtime, file.filename


with SSHClient() as client:
    client.set_missing_host_key_policy(AutoAddPolicy)
    print("Opening ssh connection")
    client.connect(HOST, username="public", password=getpass())
    print("Connected")
    print("opening sftp")
    with client.open_sftp() as sftp:
        print("Open file for writing")
        with sftp.open(FILE, "wb") as fd:
            fd.write(b"Hello World\n")
        
        print("Reading written file")
        with sftp.open(FILE, "rb") as fd:
            text = fd.read().decode()
            print(text, end="")

        print("Setting chmod to 777")        
        sftp.chmod(FILE, 0o777)
        print("Setting atime and mtime to 0 => 1970-01-01T00:00:00")
        sftp.utime(FILE, (0,0))

        # list all files, sorted by size
        for file in sorted(sftp.listdir_iter(DIR), key=by_mtime):
            # skipping directories
            if file.st_mode & S_IFDIR:
                continue

            # only files bigger than 0 bytes
            if file.st_size > 0:
                print(f"{file.filename} => {file.st_size / 1024 ** 1:.1} KiB")

    print("\nSFTP connection closed")
    stdin, stdout, stderr = client.exec_command("uname -a")
    print(stdout.read().decode())
    
Larz60+ and Gribouillis like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  HTTP, python size e upload file it6 0 1,139 Jun-06-2024, 01:06 PM
Last Post: it6

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020