Skip to content

Instantly share code, notes, and snippets.

@daVinci13
Forked from aleroddepaz/ftpuploader.py
Last active August 29, 2015 14:06
Show Gist options
  • Save daVinci13/4d626dc824c81e0a4426 to your computer and use it in GitHub Desktop.
Save daVinci13/4d626dc824c81e0a4426 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import os
import ftplib
import socket
import getpass
try:
input = raw_input
except NameError:
pass
join = lambda *arg: '/'.join(arg)
class FTPUploader(ftplib.FTP):
"""Class to upload directories and containing files"""
def chdir(self, path):
"""Change the current working directory in the FTP server,
or creates it if it does not exist
"""
try:
self.cwd(path)
except:
self.mkd(path)
self.cwd(path)
def uploaddir(self, localpath, ftppath):
"""Upload a local directory to a path in the FTP server"""
subdirectories = []
for name in os.listdir(localpath):
localname = os.path.join(localpath, name)
ftpname = join(ftppath, name)
if os.path.isdir(localname):
subdirectories.append((localname, ftpname))
else:
self.uploadfile(localname, ftpname)
for localdir, ftpdir in subdirectories:
self.chdir(ftpdir)
self.uploaddir(localdir, ftpdir)
def uploadfile(self, localfile, ftpfile):
"""Upload a file to the current working directory in the FTP server"""
print('Uploading {}...'.format(localfile))
self.storlines('STOR {}'.format(ftpfile), open(localfile, 'rb'))
self.sendcmd('SITE CHMOD 755 {}'.format(ftpfile))
def main(path):
try:
host = input('Host: ')
user = input('User: ')
password = getpass.getpass()
ftp = FTPUploader(host)
ftp.login(user, password)
for newdir in filter(bool, os.path.split(path)):
ftp.chdir(newdir)
except socket.gaierror:
print("ERROR: Not able to connect to the server")
sys.exit(1)
except ftplib.error_perm:
print("ERROR: Not able to login or reach path to upload")
print("Check you are using a valid username and password combination")
sys.exit(1)
else:
print('You are uploading to this folder: {}'.format(path))
print('Starting upload')
ftp.uploaddir(os.getcwd(), path)
ftp.quit()
print('Done')
if __name__ == "__main__":
if len(sys.argv) != 2:
print('USAGE: {} <path>'.format(os.path.basename(__file__)))
sys.exit(1)
else:
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment