Seite 3 von 4

Verfasst: Donnerstag 21. Januar 2010, 10:08
von Manne_Manta

Code: Alles auswählen

>>> ftp.sendcmd('MDTM ' + 'test.dat')
'213 20100119140243'
>>> 
Wie gesagt mit Deinem überarbeiteten Code gehts.
Danke.

Verfasst: Donnerstag 21. Januar 2010, 10:14
von snafu
Achso, weil du halt vorher sowas komisches gepostet hast. Naja, schwere Geburt. ;)

Verfasst: Donnerstag 29. April 2010, 14:20
von Manne_Manta
Hallo zusammen,

ich hab jetzt noch ein kleines Problem. Ich wollte das Programm dahingegen optimieren, dass die Files den Timestap vom Server haben.
dazu hab ich get_last_modified so angepasst:

Code: Alles auswählen

def get_last_modified(ftp_addr, pattern='*', no=1, dest='.', user='', pw=''):
    parsed = urlparse.urlparse(ftp_addr)
    ftp = TimeFTP(parsed.netloc, user, pw)


    if parsed.path:
        ftp.cwd(parsed.path)
    for filename, timestruct in list(ftp.last_modified(pattern))[-no:]:
        with open(os.path.join(dest, filename), 'wb') as outfile:
            ftp.retrbinary('RETR ' + filename, outfile.write)



    strptime=timestruct
    atime= time.mktime(strptime)
    pfad=os.path.join(dest, filename)
    print pfad
    times = (atime,atime)
    print times
    os.utime(pfad,times)
Es gibt keine Fehlermeldung aber die Files haben weiterhin das aktuelle Datum des Clients.
Geht das gar nicht mit os.time?

Verfasst: Donnerstag 29. April 2010, 22:28
von snafu
Wenn du das für jede Datei machen willst, dann solltest du es natürlich auch in einen Ebene unterhalb der For-Schleife machen, denn sonst arbeitest du nur mit den Werten, die nach dem letzten Durchlauf der Schleife rauskommen.

Verfasst: Freitag 30. April 2010, 05:42
von Manne_Manta
Kaum macht mans richtig, schon gehts. :oops:
Vielen Dank.

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 12:44
von Manne_Manta
Hallo zusammen,

nach langer Zeit habe ich die Aufgabe bekommen mein FTP-Programm auf SFTP umzustellen.
Hierzu habe ich den Code mal teilweise angepasst:

Code: Alles auswählen

import pysftp
from operator import itemgetter
import os.path
import time
import urlparse

class TimeFTP(pysftp.Connection):

    def mdtm(self, filename):
        retcode, timestamp = self.sendcmd('MDTM ' + filename).split()
        return timestamp

    def last_modified(self, pattern):
        results = []
        for filename in self.nlst(pattern):
            timestamp = self.mdtm(filename)
            results.append((filename, timestamp))
        for filename, timestamp in sorted(results, key=itemgetter(1)):
            timestruct = time.strptime(timestamp, '%Y%m%d%H%M%S')
            yield filename, timestruct


def get_last_modified(ftp_addr, pattern='*', no=1, dest='.', user='', pw=''):
    parsed = urlparse.urlparse(ftp_addr)
    FTP = TimeFTP(parsed.netloc, user, pw)
    if parsed.path:
        ftp.cwd(parsed.path)
    for filename, timestruct in list(ftp.last_modified(pattern))[-no:]:
        with open(os.path.join(dest, filename), 'wb') as outfile:
            ftp.retrbinary('RETR ' + filename, outfile.write)
Das das so natürlich noch nicht funktioniert ist mir schon klar, da dass pysftp z.B. retrbinary nicht kennt.

Was mir jetzt nicht klar ist,was will mir die Fehlermeldung sagen:

Code: Alles auswählen

Traceback (most recent call last):
  File "C:/Python_Test/Sourcecode/testmini", line 4, in <module>
    timeftpx.get_last_modified(ftp_addr, '*.dat', 2, 'C:\user', 'login','pass')
  File "C:\Python27\lib\timeftpx.py", line 25, in get_last_modified
    FTP = TimeFTP(parsed.netloc, user, pw)
  File "build\bdist.win32\egg\pysftp.py", line 74, in __init__
    xSx_key = paramiko.RSAKey.from_private_key_file(private_key_file,private_key_pass)
  File "build\bdist.win32\egg\paramiko\pkey.py", line 198, in from_private_key_file
    key = cls(filename=filename, password=password)
  File "build\bdist.win32\egg\paramiko\rsakey.py", line 51, in __init__
    self._from_private_key_file(filename, password)
  File "build\bdist.win32\egg\paramiko\rsakey.py", line 163, in _from_private_key_file
    data = self._read_private_key_file('RSA', filename, password)
  File "build\bdist.win32\egg\paramiko\pkey.py", line 279, in _read_private_key_file
    f = open(filename, 'r')
IOError: [Errno 2] No such file or directory: 'pass'
Für mich sieht das so aus, wie wenn er unter "def get_last_modified" andere Parameter erwarten würde,bzw. in anderer Reihenfolge.

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 12:57
von sparrow
Ein

Code: Alles auswählen

help(timeftpx.get_last_modified)
an der entsprechenden Stelle wird dir sicherlich die entsprechenden Parameter zeigen, die erwartet werden.

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 13:00
von BlackJack
@Manne_Manta: Vielleicht ja nicht die `get_last_modified()`, wobei ich jetzt mal davon ausgehe, dass die a) von Dir ist und b) nicht verändert wurde. Aber was *hast* Du denn verändert und wo betrifft das die genannte Funktion. Das ist doch eigentlich ziemlich offensichtlich.

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 13:08
von Manne_Manta
Die timeftp wurde von Snafu in einem der älteren Posts geschrieben.
Ich habe anstelle der ftplib die pysftp importiert.

@sparrow: Wenn ich

Code: Alles auswählen

help(timeftpx.get_last_modified
vor

Code: Alles auswählen

def get_last_modified
einfüge bringt er mir

Code: Alles auswählen

    import timeftpx
  File "C:\Python27\lib\timeftpx.py", line 24
    def get_last_modified(ftp_addr, pattern='*', no=1, dest='.', user='', pw=''):
      ^
SyntaxError: invalid syntax

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 13:13
von sparrow
Schließen die Klammer du musst!

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 13:41
von Manne_Manta
Natürlich die Klammer.

Aber das kann ich wohl so nur nur im Hauptprogramm einfügen und dabei kommt nichts vernünftiges raus.

Code: Alles auswählen

Help on function get_last_modified in module timeftpx:

get_last_modified(ftp_addr, pattern='*', no=1, dest='.', user='', pw='')

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 13:54
von BlackJack
@Manne_Manta: Das war ja schon vorher klar. Du hast den Quelltext von dieser Funktion ja gezeigt.

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 14:01
von sparrow
Achso, das ist die Funktion von oben? Dann hat mich der TraceBack verwirrt, weil da die Datei in einem lib-Verzeichnis von Python liegt.

In dem Fall solltest du prüfen, was denn pysftp.Connection für Parameter bei der Initialisierung erwartet.

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 14:12
von Manne_Manta
Dann kommt dass hier:

Code: Alles auswählen

Help on class Connection in module pysftp:

class Connection(__builtin__.object)
 |  Connects and logs into the specified hostname. 
 |  Arguments that are not given are guessed from the environment.
 |      host             - The Hostname of the remote machine.
 |      username         - Your username at the remote machine.(None)
 |      private_key      - Your private key file.(None)
 |      password         - Your password at the remote machine.(None)
 |      port             - The SSH port of the remote machine.(22)
 |      private_key_pass - password to use if your private_key is encrypted(None)
 |      log              - log connection/handshake details (False)
 |  returns a connection to the requested machine
 |  
 |  srv = pysftp.Connection('example.com')
 |  
 |  Methods defined here:
 |  
 |  __del__(self)
 |      Attempt to clean up if not explicitly closed.
 |  
 |  __init__(self, host, username=None, private_key=None, password=None, port=22, private_key_pass=None, log=False)
 |  
 |  chdir(self, path)
 |      change the current working directory on the remote
 |  
 |  close(self)
 |      Closes the connection and cleans up.
 |  
 |  execute(self, command)
 |      Execute the given commands on a remote machine.
 |  
 |  get(self, remotepath, localpath=None)
 |      Copies a file between the remote host and the local host.
 |  
 |  getcwd(self)
 |      return the current working directory on the remote
 |  
 |  listdir(self, path='.')
 |      return a list of files for the given path
 |  
 |  put(self, localpath, remotepath=None)
 |      Copies a file between the local host and the remote host.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Re: FTP Download nach Datum

Verfasst: Montag 4. Februar 2013, 14:19
von sparrow
Genau, da stehen die Argumente die erwartet werden.
Wenn du das jetzt mit dem vergleichst, was du übergibst, siehst du ja schon den Fehler.

Re: FTP Download nach Datum

Verfasst: Dienstag 5. Februar 2013, 08:50
von Manne_Manta
Die Argumente habe ich mal angepasst.
Nur ist mir die folgende Fehlermeldung wieder etwas suspekt.
Hat da das parsen in

Code: Alles auswählen

FTP = TimeFTP(parsed.netloc, username, password)
den fehler verursacht oder liegt es daran, dass Paramiko mit den Argumenten nicht klar kommt.

Code: Alles auswählen

Traceback (most recent call last):
  File "C:\PASU_FTP_Export\Sourcecode\testmini", line 7, in <module>
    timeftpx.get_last_modified('host', '*.dat', 2, 'C:\user', 'username','password')
  File "C:\Python27\lib\timeftpx.py", line 29, in get_last_modified
    FTP = TimeFTP(parsed.netloc, username, password)
  File "build\bdist.win32\egg\pysftp.py", line 55, in __init__
    self._transport = paramiko.Transport((host, port))
  File "build\bdist.win32\egg\paramiko\transport.py", line 298, in __init__
    'Unable to connect to %s: %s' % (hostname, reason))
SSHException: Unable to connect to : [Errno 10049] Die angeforderte Adresse ist in diesem Kontext ungültig

Re: FTP Download nach Datum

Verfasst: Dienstag 5. Februar 2013, 09:13
von sparrow
Hast du jetzt nur die Namen der Variablen angepasst, die übergeben werden?
Das kann man aus dem Schnipsel leider nicht erkennen.

Re: FTP Download nach Datum

Verfasst: Dienstag 5. Februar 2013, 09:42
von BlackJack
@Manne_Manta: Die Fehlermeldung lässt vermuten, dass Paramiko mit einer leeren Zeichenkette als `host` aufgerufen wird. Was ja auch stimmt wenn die Daten im Stapelabzug (Traceback) stimmen:

Code: Alles auswählen

In [2]: urlparse.urlparse('host').netloc
Out[2]: ''
Das nächste Problem wird deutlich wenn Du noch einmal vergleichst mit welchen Argumenten Du `TimeFTP` aufrufst und was `pyftp.Connection` eigentlich erwartet. Das Passwort ist dort *nicht* an *der* Stelle in den Argumenten.

Re: FTP Download nach Datum

Verfasst: Dienstag 5. Februar 2013, 11:09
von Manne_Manta
Aber so funktioniert es doch auch:

Code: Alles auswählen

import pysftp

srv = pysftp.Connection(host='testserver',username='usr', password='test')
srv.execute('ls -al')
srv.chdir('/dat3')
srv.get('hb.txt')

#srv.put('hb.txt')
srv.close()
Was ist an der Anordnung der Argumente da anderst?

Re: FTP Download nach Datum

Verfasst: Dienstag 5. Februar 2013, 12:07
von BlackJack
@Manne_Manta: Hier gibt es im Grunde gar keine Ordnung auf den Argumenten weil die ja *namentlich* und per Position bestimmt werden. Wenn Du die Namen *nicht* angibst, sondern nur die Werte, dann überlege doch mal wie Python die zuordnet.