私の答えはftplib
に関連していません。そのpexpect
方法。別のftpサーバごとに異なります
#!/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 "",
ftp
プロンプト以下のコードを参照してください。手作業で一度だけ試してみてください。expect
はコード内で同じです。さらにエラーケースを追加することもできます。 log_file
を使用しました。私はls -lrt
の出力をftp内でパイプして直接ファイル名を抽出することはできません。
私のコードは効率的ではありません。必要な場合は編集してください。しかし、これは動作します!歓声
[python ftpの最新のファイルを日付で取得](https://stackoverflow.com/questions/8990598/python-ftp-get-the-most-recent-file-by-date) –