python实现简单的ftp
LiuSw Lv6

python实现简单的ftp

会自动生成配置文件,下次启动会读取配置文件内的参数。

ini内容

1
2
3
4
5
6
7
8
9
[FTP]
#ftp用户
user=ftp
#密码
password=1
#端口号
port=23
#路径
path=F:\ftp\

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# -*- coding: utf-8 -*-

from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer
import configparser,os,sys

#########################################################################################
# Variable needs to be modified
# 需要修改的变量
#########################################################################################
def getVariable():

global user ,password ,path ,port
user = str(config.get('FTP', 'user'))
password = str(config.get('FTP', 'password'))
path = str(config.get('FTP', 'path'))
port = config.get('FTP', 'port')
print("###############################################################")
print("# [FTP]")
print("# user="+user+"\n"+"# password="+password+"\n"+"# port"+port+"\n"+"# path"+path)
print("###############################################################\n")


#########################################################################################
# Reading configuration Files
# 读取配置文件
#########################################################################################
global config
# 生成ConfigParser对象
config = configparser.ConfigParser()
os.chdir(os.path.abspath(sys.path[0]))
filename = 'config.ini'#os.path.join(os.path.abspath(sys.path[0]),'config.ini')
iniExists=os.path.exists(os.path.join(os.path.abspath(sys.path[0]),'config.ini'))
print(filename)
print(iniExists)
if iniExists == False:
with open(filename, mode='w') as file_ini:
file_ini.write("[FTP]\n")
file_ini.write("#ftp用户\n")
file_ini.write("user=ftp\n")
file_ini.write("#密码\n")
file_ini.write("password=1\n")
file_ini.write("#端口号\n")
file_ini.write("port=23\n")
file_ini.write("#路径\n")
file_ini.write("path="+os.path.dirname(__file__))


#print(os.path.abspath(sys.path[0]))
# 获取Variable变量
config.read(filename, encoding='utf-8')
getVariable()

authorizer = DummyAuthorizer()
authorizer.add_user(user, password, path, perm='elradfmwM')
handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(('0.0.0.0', str(port)), handler)
server.serve_forever()

执行报错需要安装pyftpdlib与configparser模块

1
2
pip install pyftpdlib
pip install configparser
 评论