Python ftplib,通过ftp获取最新文件

Python ftplib,通过ftp获取最新文件,python,Python,我知道如何设置下载这样的文件,但大多数文件都没有命名为file LATEST。我怎样才能下载最新的文件 通过: 修改日期 时间戳 如果version.current文件名”) fd=open(“file_name”,“r”)#for循环在这里不需要,因为只有一行 对于fd中的行: 如果行: 最新的_文件=line.strip() 打破 其他: 打印“未找到文件” 系统出口(1) fd.close() child.logfile=sys.stdout 操作系统(“rm临时文件名”) child.

我知道如何设置下载这样的文件,但大多数文件都没有命名为file LATEST。我怎样才能下载最新的文件

通过:

  • 修改日期
  • 时间戳
  • 如果version.current
以下是我目前掌握的情况:

#!/usr/bin/env python

import ftplib
import os
import socket

HOST = 'ftp.site.org'
DIRN = 'dir/'
FILE = 'filename-LATEST.tar.gz'

def main():
    try:
    f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
    print 'ERROR: cannot reach "%s"' % HOST
    return
print '*** Connected to host "%s"' % HOST

try:
    f.login()
except ftplib.error_perm:
    print 'ERROR:: cannot login anonymously'
    f.quit()
    return
print '*** Logged in as "anonymous"'

try:
    f.cwd(DIRN)
except ftplib.error_perm:
    print 'ERROR: cannot CD to "%s"' % DIRN
    f.quit()
    return
print '*** Changed to "%s" folder' % DIRN

try:
    f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
except ftplib.error_perm:
    print 'ERROR: cannot read file "%s"' % FILE
    os.unlink(FILE)
else:
    print '*** Downloaded "%s" to CWD' % FILE
f.quit()
return

if __name__ == '__main__':
main()

你必须像ftplib的文档那样做
ftp.retrlines('LIST',callback)
并解析结果你必须像ftplib的文档那样做
ftp.retrlines('LIST',callback)
并解析结果我的答案与
ftplib
无关。这是
pexpect
的方式。请参见下面的代码

#!/usr/bin/python -B

#Program to download latest file from a FTP directory specified

import sys
import os
import pexpect

if len(sys.argv)!=5:
    print "Usage:"
    print "\t",sys.argv[0],"<IP Address> <Username> <Password> <Directory-Path>"
    print "\t","Use \"\" if there is no password"
    sys.exit(1)

ip=str(sys.argv[1])
usr=str(sys.argv[2])
pswd=str(sys.argv[3])
path=str(sys.argv[4])
timeout=10
log_file=file("temp",'w')

try:
    try:
        child=pexpect.spawn("ftp "+ip)
    except:
        print "failed to connect "+sys.exc_function()
        sys.exit(1)

    x=child.expect(['Name',pexpect.EOF,pexpect.TIMEOUT],timeout)
    if x!=0:
        print "No \"Name\" prompt"
        sys.exit(1)

    child.sendline(usr)
    x=child.expect(["[pP]assword","[lL]ogin [sS]ucess","logged in",
            pexpect.EOF,pexpect.TIMEOUT],timeout)
    if x==0:
        child.sendline(pswd)   #Add case for no password
        y=child.expect(["[lL]ogin [sS]uccess","User "+usr+" logged in", 
        "[iI]correct [lLogin]",pexpect.EOF,pexpect.TIMEOUT],timeout) 
        if y!=0 and y!=1:
            print "Login Failed"
            sys.exit(1)
    elif x!=1 and x!=2:
        print "Authentication Timed Out!!"
        sys.exit(1) 

    child.sendline("cd "+path)
    x=child.expect(["[dD]irectory successfully changed","CWD command successful",
            pexpect.EOF,pexpect.TIMEOUT],timeout) 
    if x!=0 and x!=1:
        print "cd Failed!!!"
        sys.exit(1)

    child.logfile=log_file

    child.sendline("ls -lrt")
    x=child.expect(["[dD]irectory send OK","[tT]ransfer [cC]omplete",
            pexpect.EOF,pexpect.TIMEOUT],timeout)
    if x!=0 and x!=1:
        print "listing failed" 
        sys.exit(1)

    os.system("cat temp | grep '^-' |"+\
         "sed -n '$p' | awk '{print $NF}' > file_name") 

    fd=open("file_name","r")   #for loop is not needed here since there'll be only one line
    for line in fd:
        if line:
             latest_file=line.strip()
             break
        else:
             print "No file found"
             sys.exit(1)
    fd.close()
    child.logfile=sys.stdout
    os.system("rm temp file_name")

    child.sendline("bi")
    child.expect("ftp>")
    child.sendline("ha")
    child.expect("ftp>")

    child.sendline("get "+latest_file)
    x=child.expect(["[tT]ransfer [cC]omplete",
            pexpect.EOF,pexpect.TIMEOUT],200) #Add more error cases here
    if x!=0:
        print "Copy Failed" 
        sys.exit(1)

    child.close()
    sys.exit(0)
except KeyboardInterrupt:
    print "",
#/usr/bin/python-B
#从指定的FTP目录下载最新文件的程序
导入系统
导入操作系统
导入预期
如果len(sys.argv)=5:
打印“用法:”
打印“\t”,sys.argv[0],“”
打印“\t”,“如果没有密码,则使用\”
系统出口(1)
ip=str(sys.argv[1])
usr=str(sys.argv[2])
pswd=str(sys.argv[3])
path=str(sys.argv[4])
超时=10
log_file=file(“temp”,“w”)
尝试:
尝试:
child=pexpect.spawn(“ftp”+ip)
除:
打印“连接失败”+sys.exc_函数()
系统出口(1)
x=child.expect(['Name',pexpect.EOF,pexpect.TIMEOUT],TIMEOUT)
如果x=0:
打印“否”“名称”“提示”
系统出口(1)
child.sendline(usr)
x=child.expect([“[pP]assword”、“[lL]ogin[sS]ucess”、“登录”,
pexpect.EOF,pexpect.TIMEOUT],超时)
如果x==0:
child.sendline(pswd)#添加无密码的大小写
y=child.expect([“[lL]ogin[sS]uccess”,“用户”+usr+“登录”,
“[iI]更正[lLogin]”,pexpect.EOF,pexpect.TIMEOUT],超时)
如果你是我的话=0和y=1:
打印“登录失败”
系统出口(1)
伊里夫x=1和x=2:
打印“身份验证超时!!”
系统出口(1)
发送行(“cd”+路径)
x=child.expect([“[dD]目录成功更改”,“CWD命令成功”,
pexpect.EOF,pexpect.TIMEOUT],超时)
如果x=0和x=1:
打印“cd失败!!!”
系统出口(1)
child.logfile=log\u文件
子发送线(“ls-lrt”)
x=child.expect([“[dD]目录发送确定”,“[tT]传输[cC]完成”,
pexpect.EOF,pexpect.TIMEOUT],超时)
如果x=0和x=1:
打印“列表失败”
系统出口(1)
操作系统(“cat temp | grep'^-'|”+\
“sed-n'$p'| awk'{print$NF}'>文件名”)
fd=open(“file_name”,“r”)#for循环在这里不需要,因为只有一行
对于fd中的行:
如果行:
最新的_文件=line.strip()
打破
其他:
打印“未找到文件”
系统出口(1)
fd.close()
child.logfile=sys.stdout
操作系统(“rm临时文件名”)
child.sendline(“bi”)
expect(“ftp>”)
child.sendline(“ha”)
expect(“ftp>”)
sendline(“get”+最新的_文件)
x=子项。预期([“[tT]传输[cC]完成”,
peexpect.EOF,peexpect.TIMEOUT],200)#在此处添加更多错误案例
如果x=0:
打印“复制失败”
系统出口(1)
child.close()
系统出口(0)
除键盘中断外:
打印“”,
ftp
提示对于不同的ftp服务器是不同的。手动尝试一次,并在代码中预期相同。您还可以添加更多错误案例。我使用了
log\u文件
,因为我无法在ftp中通过管道将
ls-lrt
的输出直接提取文件名


我知道我的代码效率不高。请在必要时进行编辑。然而,这将工作!!干杯

我的答案与
ftplib
无关。这是
pexpect
的方式。请参见下面的代码

#!/usr/bin/python -B

#Program to download latest file from a FTP directory specified

import sys
import os
import pexpect

if len(sys.argv)!=5:
    print "Usage:"
    print "\t",sys.argv[0],"<IP Address> <Username> <Password> <Directory-Path>"
    print "\t","Use \"\" if there is no password"
    sys.exit(1)

ip=str(sys.argv[1])
usr=str(sys.argv[2])
pswd=str(sys.argv[3])
path=str(sys.argv[4])
timeout=10
log_file=file("temp",'w')

try:
    try:
        child=pexpect.spawn("ftp "+ip)
    except:
        print "failed to connect "+sys.exc_function()
        sys.exit(1)

    x=child.expect(['Name',pexpect.EOF,pexpect.TIMEOUT],timeout)
    if x!=0:
        print "No \"Name\" prompt"
        sys.exit(1)

    child.sendline(usr)
    x=child.expect(["[pP]assword","[lL]ogin [sS]ucess","logged in",
            pexpect.EOF,pexpect.TIMEOUT],timeout)
    if x==0:
        child.sendline(pswd)   #Add case for no password
        y=child.expect(["[lL]ogin [sS]uccess","User "+usr+" logged in", 
        "[iI]correct [lLogin]",pexpect.EOF,pexpect.TIMEOUT],timeout) 
        if y!=0 and y!=1:
            print "Login Failed"
            sys.exit(1)
    elif x!=1 and x!=2:
        print "Authentication Timed Out!!"
        sys.exit(1) 

    child.sendline("cd "+path)
    x=child.expect(["[dD]irectory successfully changed","CWD command successful",
            pexpect.EOF,pexpect.TIMEOUT],timeout) 
    if x!=0 and x!=1:
        print "cd Failed!!!"
        sys.exit(1)

    child.logfile=log_file

    child.sendline("ls -lrt")
    x=child.expect(["[dD]irectory send OK","[tT]ransfer [cC]omplete",
            pexpect.EOF,pexpect.TIMEOUT],timeout)
    if x!=0 and x!=1:
        print "listing failed" 
        sys.exit(1)

    os.system("cat temp | grep '^-' |"+\
         "sed -n '$p' | awk '{print $NF}' > file_name") 

    fd=open("file_name","r")   #for loop is not needed here since there'll be only one line
    for line in fd:
        if line:
             latest_file=line.strip()
             break
        else:
             print "No file found"
             sys.exit(1)
    fd.close()
    child.logfile=sys.stdout
    os.system("rm temp file_name")

    child.sendline("bi")
    child.expect("ftp>")
    child.sendline("ha")
    child.expect("ftp>")

    child.sendline("get "+latest_file)
    x=child.expect(["[tT]ransfer [cC]omplete",
            pexpect.EOF,pexpect.TIMEOUT],200) #Add more error cases here
    if x!=0:
        print "Copy Failed" 
        sys.exit(1)

    child.close()
    sys.exit(0)
except KeyboardInterrupt:
    print "",
#/usr/bin/python-B
#从指定的FTP目录下载最新文件的程序
导入系统
导入操作系统
导入预期
如果len(sys.argv)=5:
打印“用法:”
打印“\t”,sys.argv[0],“”
打印“\t”,“如果没有密码,则使用\”
系统出口(1)
ip=str(sys.argv[1])
usr=str(sys.argv[2])
pswd=str(sys.argv[3])
path=str(sys.argv[4])
超时=10
log_file=file(“temp”,“w”)
尝试:
尝试:
child=pexpect.spawn(“ftp”+ip)
除:
打印“连接失败”+sys.exc_函数()
系统出口(1)
x=child.expect(['Name',pexpect.EOF,pexpect.TIMEOUT],TIMEOUT)
如果x=0:
打印“否”“名称”“提示”
系统出口(1)
child.sendline(usr)
x=child.expect([“[pP]assword”、“[lL]ogin[sS]ucess”、“登录”,
pexpect.EOF,pexpect.TIMEOUT],超时)
如果x==0:
child.sendline(pswd)#添加无密码的大小写
y=child.expect([“[lL]ogin[sS]uccess”,“用户”+usr+“登录”,
“[iI]更正[lLogin]”,pexpect.EOF,pexpect.TIMEOUT],超时)
如果你是我的话=0和y=1:
打印“登录失败”
系统出口(1)
伊里夫x=1和x=2:
打印“身份验证超时!!”
系统出口(1)
发送行(“cd”+路径)
x=child.expect([“[dD]目录成功更改”,“CWD命令成功”,
pexpect.EOF,pexpect.TIMEOUT],超时)
如果x=0和x=1:
打印“cd失败!!!”
系统出口(1)
child.logfile=log\u文件
子发送线(“ls-lrt”)
x=child.expect([“[dD]目录发送确定”,“[tT]传输[cC]完成”,
pexpect.EOF,pexpect.TIMEOUT],超时)
如果x=0和x=1:
打印“列表失败”
系统出口(1)
操作系统(“cat temp | grep'^-'|”+\
“sed-n'$p'| awk'{print$NF}'>文件名”)
fd=open(“file_name”,“r”)#for循环在这里不需要,因为只有一行
对于fd中的行:
如果行:
最新的_文件=line.strip()
打破
其他:
打印“未找到文件”
系统出口(1)
fd.close()
child.logfile=sys.stdout
操作系统(“rm临时文件名”)
child.sendline(“bi”)
expect(“ftp>”)
child.sendline(“ha”)
expect(“ftp>”)
sendline(“get”+最新的_文件)
x=子项。期望([“[tT]转移[