Skip to content

Instantly share code, notes, and snippets.

@AlexTalker
Created January 30, 2016 18:13
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 AlexTalker/a72068e39724c755968e to your computer and use it in GitHub Desktop.
Save AlexTalker/a72068e39724c755968e to your computer and use it in GitHub Desktop.
#!/usr/bin/python
from sys import argv
from os.path import basename
from ftplib import FTP, error_perm, error_reply
import configparser
import netrc
def _parse_config(filename):
config = configparser.ConfigParser({
'port': '0',
'user': '',
'password': '',
'use_netrc': 'false'})
config.read(filename)
c = config['FTP']
if 'host' not in c:
raise configparser.NoOptionError()
if c.getboolean('use_netrc'):
rc = netrc.netrc()
data = rc.authenticators(c['host'])
if data is not None:
c['user'], c['password'] = data[1:]
return c['host'], c['port'], c['user'], c['password']
def ftpush(roots, push_files, config, remove_mode=False):
host, port, user, password = _parse_config(config)
with FTP() as ftp:
print('Connect to server...')
ftp.connect(host, int(port))
ftp.login(user, password)
for root, files in zip(roots, push_files):
ftp.cwd(root)
print('Change working directory to %s' % root)
for f in files:
name = basename(f)
if remove_mode:
print('Start removing %s as %s' % (f, name))
try:
ftp.delete(name)
print('Successful removed %s' % name)
except error_perm:
print('Cannot delete file %s: permission error' % name)
except error_reply:
print('Cannot delete file %s: server error' % name)
else:
print('Start pushing %s as %s' % (f, name))
ftp.storbinary('STOR ' + name, open(f, 'rb'))
print('File %s successful pushed' % name)
print('Quit server...')
ftp.quit()
if __name__ == '__main__':
config = 'ftpush.ini'
roots = []
files = []
remove_mode = False
i = -1
set_root = False
args = argv[1:]
if args[0] == '--help':
print('''
Tool that help you push files to FTP server from scripts
%s [-r] [--config config] --set-root root [files] [...] -- HELP:
-r -- enables remove mode(default: False) when files removing instead of uploading to server
--set-root root -- set root directory(on ftp server through cwd command) for files next in argumets to push
--config config -- set path to config file(default: ftpush.ini)
Example of config file:
[FTP]
host = localhost
user = alextalker # Optional
password = my_cool_password # Optional
use_netrc = true # Optional, default: false
port = 666 # Optional
''' % argv[0])
exit()
if args[0] == '-r':
remove_mode = True
args = args[1:]
if args[0] == '--config':
config = args[1]
args = args[2:]
for v in args:
if set_root:
set_root = False
roots.append(v)
files.append([])
continue
if v == '--set-root':
set_root = True
i += 1
continue
files[i].append(v)
ftpush(roots, files, config, remove_mode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment