Skip to content

Instantly share code, notes, and snippets.

@nst
Created September 22, 2021 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nst/6703da0b26f796fd2429310c7dda13cf to your computer and use it in GitHub Desktop.
Save nst/6703da0b26f796fd2429310c7dda13cf to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# Nicolas Seriot
# 2021-09-22
# https://gist.github.com/nst/6703da0b26f796fd2429310c7dda13cf
# - Upload some local directoy contents to a remote FTP directory.
# - Upload only files modified since last upload.
# - Touch a local file to remember timestamp of last upload.
# - Plays well with Mowgli https://github.com/nst/Mowgli
# - Eg. python3 mowgli.py -m && python3 kaa.py
import ftplib
import os
def upload_files(ftp, local_dir, remote_dir, kaa_ts):
#print("\nCWD", remote_dir)
ftp.cwd(remote_dir)
for name in os.listdir(local_dir):
if name.startswith("."):
continue
local_path = os.path.join(local_dir, name)
if os.path.isfile(local_path):
file_ts = os.path.getmtime(local_path)
if file_ts >= kaa_ts:
ftp.storbinary('STOR ' + name, open(local_path,'rb'))
print("STOR", remote_dir, name)
else:
pass
#print("SKIP", name)
elif os.path.isdir(local_path):
try:
ftp.mkd(name)
print("MKDIR" + name)
# ignore "directory already exists"
except ftplib.error_perm as e:
if not e.args[0].startswith('550'):
raise
upload_files(ftp, local_path, name, kaa_ts)
ftp.cwd("..")
#print("CWD ..\n")
def main():
KAA_FILE = "kaa.txt"
if os.path.isfile(KAA_FILE):
kaa_ts = os.path.getmtime(KAA_FILE)
#print("-- kaa_ts:", kaa_ts)
with ftplib.FTP('ftp.example.com', 'username', 'password') as ftp:
#ftp.set_debuglevel(2)
#print(ftp.getwelcome())
upload_files(ftp, "dst", "/httpdocs", kaa_ts)
open(KAA_FILE, 'w').close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment