1

I'm trying to create a Python script for getting files from FTP. It is working right now but I tested it on free hosting page https://hosting.miarroba.com. If I connect it with my dedicated server FTP service, it fails with

500 Command not understood

The command I think fails is ftp.mlsd(). I don't know if I need and special configuration on my server.

Code Python 3.5

def realizarConexion():
a_server = ""
a_user = ""
a_pass = ""
a_port = 

# Conectarse con los métodos connect y login
try:
    ftp = FTP() 
    ftp.connect(a_server, a_port, -999) 
    ftp.login(a_user, a_pass)
    #ftp.dir()
    estado = validaFecha()
    if estado:
        descargarFicheros(ftp)
    else:
        print("No existe una anterior fecha de respaldo configurada")
    ftp.close()
except Exception as e:
    print("Fallo al conectar con FTP %s: %s" %(a_server, e))

def obtenerFecha():
ultFecha = ""
try:
    fDate = open("date.txt","r")
    if fDate.mode == 'r':
        ultFecha = fDate.read()
except Exception as e:
    print("Sin fecha asignada!")
return ultFecha

def validaFecha():
estadoFecha = True
try:
    fDate = open("date.txt","r")
    if fDate.mode == 'r':
        ultFecha = fDate.read()
        print("fecha: %s" %ultFecha)
except Exception as e:
    respaldo = input('No hay fechas configuradas, desea tomar la fecha actual como fecha de ultimo respaldo! - (Y / N): ')
    if respaldo.lower() == "y":
       asignarFechaCopia()
       print("La asignación de la fecha se a ha generado con exito")
       estadoFecha = True
    elif respaldo.lower()  == "n":
        print("Copia de seguridad detenida!") 
        estadoFecha = False
    else:
        print("Copia de seguridad detenida!")
        estadoFecha = False
return estadoFecha

def descargarFicheros(ftp): 
try:
    for file, parametros in ftp.mlsd():
        if file != '.' and file != '..':
            fechaCopia = obtenerFecha()[0:10]
            horaCopia = obtenerFecha()[11:19]
            fechaModif = datetime.datetime.strptime(parametros["modify"][0:-6],"%Y%m%d").date()
            horaModif = datetime.datetime.strptime(parametros["modify"][8:14],"%H%M%S").time()
            f1 = time.strptime(str(fechaCopia) + " " + str(horaCopia), "%Y-%m-%d %H:%M:%S")
            f2 = time.strptime(str(fechaModif) + " " + str(horaModif), "%Y-%m-%d %H:%M:%S")
            if f2 > f1:
                print("Se ha actualizado el fichero => %s" %file)
                ftp.retrbinary("RETR " + file ,open(file, 'wb').write)
            else:
                print("%s Archivo sin cambios %s %s " %(fechaCopia,fechaModif,file))
    print("Proceso finalizado!! Se ha actualzado la fecha de copiado de archivos.")
    asignarFechaCopia()                     
except Exception as e:
    print("Error: %s" %e)    

def asignarFechaCopia():
t = time.strftime("%Y-%m-%d %H:%M:%S")
fDate = open("date.txt","w+")
fDate.write(t)
fDate.close()

#Inicialización del Script     
realizarConexion()
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
krlosruiz
  • 113
  • 3
  • 11

2 Answers2

0

Many servers do not support MLSD command, as it's a relatively new command (in FTP terms). And particularly IIS does not.


If you need just filenames, use FTP.nlst instead.

If you need file attributes, you have to use FTP.dir (or FTP.retrlines) instead and parse the returned listing.

See also How do I parse a listing of files to get just the filenames in Python?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • Thank for corrections and your answer!!, If I need a file timestamp does FTP.nlst works? – krlosruiz Jun 15 '18 at 15:02
  • No `nlst` won't give you timestamps (unless you call `MDTM` for each file returned by `nlst`, see also https://stackoverflow.com/q/29026709/850848). For a listing with timestamps on a server that does not support `MLSD`, you need `dir` (`LIST` command). – Martin Prikryl Jun 15 '18 at 17:14
-1

You can use wireshark or tcpdump to see what is being sent to the server in plaintext by filtering for port 21. You should be able to see exactly what's going on and where the "500 Command not understood" comes from.

mottek
  • 929
  • 5
  • 12