Skip to content

Instantly share code, notes, and snippets.

@mouuff
Last active February 24, 2018 16:10
Show Gist options
  • Save mouuff/3738e31b08ef68239772a53b6fb12c76 to your computer and use it in GitHub Desktop.
Save mouuff/3738e31b08ef68239772a53b6fb12c76 to your computer and use it in GitHub Desktop.
from ftplib import FTP
import os.path
class FtpWalk:
def __init__(self, ftp, *path):
self._ftp = ftp
for c in path:
self._ftp.cwd(c)
self._path = self._ftp.pwd()
def listdir(self, _path):
file_list, dirs, nondirs = [], [], []
old_directory = self._ftp.pwd()
self._ftp.cwd(_path)
self._ftp.retrlines('LIST', lambda x: file_list.append(x.split()))
for info in file_list:
ls_type, name = info[0], info[-1]
if ls_type.startswith('d'):
if name != '..' and name != '.':
dirs.append(name)
else:
nondirs.append(name)
self._ftp.cwd(old_directory)
return dirs, nondirs
def cwd(self):
return self._path
def walk(self, path=None):
if not path:
path = self._path
dirs, nondirs = self.listdir(path)
yield path, dirs, nondirs
for name in dirs:
# using cwd is the only cross platform solution I have found so far
self._ftp.cwd(path)
self._ftp.cwd(name)
path = self._ftp.pwd()
yield from self.walk(path)
path = os.path.dirname(path)
def ftp_walk(ftp, *path):
walk = FtpWalk(ftp, *path)
tree = list(walk.walk())
def relpath(w): return (os.path.relpath(w[0], walk.cwd()), w[1], w[2])
res = map(relpath, tree)
return res
ftp = FTP()
freebox = True
if (freebox):
ftp.connect("mafreebox.freebox.fr")
ftp.login()
else:
ftp.connect('localhost', 12344)
ftp.login('user')
for x in ftp_walk(ftp, 'Disque dur','autres', 'OpenHardwareMonitor'):
print(x)
print(ftp.pwd())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment