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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
from pyftpdlib import ftpserver
from datetime import datetime
import ConfigParser, os, shutil

class Connection:
    "Handles the connection variables specified in the configuration file."
    def __init__(self):
        "Gets the variables from the configuration file"
        config = ConfigParser.RawConfigParser()
        config.read('config.cfg')

        self.ip = config.get('FTP Section', 'hostname')
        self.port = config.getint('FTP Section', 'port')
        self.directory = config.get('FTP Section', 'directory')
        self.user = config.get('FTP Section', 'user')
        self.password = config.get('FTP Section', 'pass')
        self.logname = config.get('FTP Section', 'logname')
        self.archive = config.get('FTP Section', 'archive')
        self.remain = config.get('FTP Section', 'remain')

        # Create ftp root if not exists
        self.CreateRootDirectory()

    def getip(self):
        "Returns the hostname"
        return self.ip
    def getport(self):
        "Returns the port number"
        return self.port
    def getdir(self):
        "Returns the root directory of the ftp-server"
        return self.directory
    def getuser(self):
        "Returns the user"
        return self.user
    def getpw(self):
        "Returns the password"
        return self.password
    def getlogname(self):
        "Returns the name of the log file"
        return self.logname
    def getarchive(self):
        "Returns true/false if the program should archive log files or not."
        return self.archive
    def getremain(self):
        "Returns true/false if the logfile should remain after logout."
        return self.remain

    def CreateRootDirectory(self):
        "Creates ftp root if not exist"
        try:
            os.makedirs(self.directory)
        except OSError:
            if os.path.exists(self.directory):
                # We are nearly safe
                print 'Could not create root folder, it exists'
                pass
            else:
                # There was an error on creation, so make sure we know about it
                raise
    def CreateArchiveDirectory(self):
        "Creates archive directory in ftp root if not exist"
        try:
            os.makedirs(self.directory + ".archive")
        except OSError:
            if os.path.exists(self.directory + ".archive"):
                # We are nearly safe
                print 'Could not create root folder, it exists'
                pass
            else:
                # There was an error on creation, so make sure we know about it
                raise

class ArchiveHandler(ftpserver.FTPHandler):

    def on_login(self, username):
        # do something when user login
        pass

    def on_logout(self, username):
        # do something when user logs out
        pass

    
    def on_file_sent(self, file):
        "What to do when retrieved the file the class is watching over"
        attr = Connection()
        if attr.getarchive() == 'true':
            t = datetime.now()
	    if file.name == "log.log":
		
            	try:
                	shutil.copy2(file, attr.getdir() + ".archive/" + str(t.strftime("%Y-%m-%d_%H:%M:%S") + '.log'))
            	except OSError:
                	print 'Could not copy file'
                	raise

        	if attr.getremain() == 'false':
            		try:
                		os.remove(file)
            		except OSError:
                		print 'Could not remove file'
                		raise

    def on_incomplete_file_received(self, file):
        # remove partially uploaded files
        import os
        os.remove(file)

    def on_file_received(self, file):
        # do something when a file has been received
        pass
            
    def on_incomplete_file_sent(self, file):
        # do something when a file is partially sent
        pass


        
    
    


def main():
    #Read configs from the FTP section in the config file
    #Put the data into variables used to create the ftp-connection
    # Open a new connection object
    conn = Connection()

    #Check if we are going to archive files, if true, create an archive folder.
    if(conn.getarchive() == 'true'):
        conn.CreateArchiveDirectory()
    
    # Instantiate a dummy authorizer for managing 'virtual' users
    authorizer = ftpserver.DummyAuthorizer()

    # Define a new user having full r/w permissions and a read-only
    # anonymous user
    authorizer.add_user(conn.getuser(), conn.getpw(), conn.getdir(), perm='elradfmwM')
    # Remove # below to add an anonymous user with only read access.
    # authorizer.add_anonymous(homedir='.')

    # Instantiate FTP handler class
    handler = ArchiveHandler
    handler.authorizer = authorizer

    # Define a customized banner (string returned when client connects)
    handler.banner = "Session started, ftp-server api version %s" %ftpserver.__ver__

    # Specify a masquerade address and the range of ports to use for
    # passive connections.  Decomment in case you're behind a NAT.
    #ftp_handler.masquerade_address = '151.25.42.11'
    #ftp_handler.passive_ports = range(60000, 65535)

    # Instantiate FTP server class and listen to 0.0.0.0:21
    address = ('', conn.getport())
    server = ftpserver.FTPServer(address, handler)

    # set a limit for connections
    server.max_cons = 256
    server.max_cons_per_ip = 5

    # start ftp server
    server.serve_forever()
    

if __name__ == '__main__':
    main()