/
Main.py
188 lines (162 loc) · 5.52 KB
/
Main.py
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python
import os, sys, mounter, logging, lock
from optparse import OptionParser
from StaticGlobals import global_log_file, default_log_level
#Checks if the user running the script is root
def isRoot():
# root uid=0, so anything else is NOT root
if os.getuid():
print "You must be root to run this script."
print "Use 'su' to become root first, then try again, or run with 'sudo'."
return False
return True
def initializeParser():
parser = OptionParser(
usage = "usage: %prog [options]",
description = "Remote Server Backup GUI")
parser.add_option( "-a",
"--all",
action = "store_false",
dest = "use_filter",
help = "Runs the script withOUT a filter (runs on ALL files and folders specified).")
parser.add_option( "-e",
"--external-path",
dest = "external_path",
help = "Specifies a location other than the backup server for the backups to be stored/restored from.")
parser.add_option( "--filter",
action = "store_true",
dest = "use_filter",
default = True,
help = "Runs the script with a filter (default).")
parser.add_option( "-g",
"--gui",
action = "store_true",
dest = "useGUI",
default = False,
help = "Run with a graphical user interface (GUI).")
parser.add_option( "-l",
"--log",
dest = "loglevel",
help = "The threshold for logging purposes. Use \"DEBUG\" for high verbosity.")
parser.add_option( "-m",
"--mount",
action = "store_true",
dest = "mount",
default = False,
help = "Runs 'mounter' to help mount/unmount partitions before backing up/restoring. r00t priviliges required!!!")
parser.add_option( "-n",
"--appointment-number",
dest = "appointment_number",
help = "An Appointment Number (e.g. 001234)")
parser.add_option( "-r",
"--restore",
action = "store_true",
dest = "restore",
default = False,
help = "Restore backups (use \"-e\" to specify an external location to restore from.)")
parser.add_option( "-s",
"--server",
dest = "server",
help = "Specifies a server for the backup/restore.")
"""
parser.add_option("-t",
"--test",
action="store_true",
dest = "testMode",
default = False,
help = "Run in test mode, for use while developing.")
"""
parser.add_option( "-u",
"--username",
dest = "username",
help = "Server Username.")
return parser
def checkArgs(options, args):
"""Given a list of options from the arguments (through an Optionparser),
check them and act approriately
"""
# Handle varying log levels
setupLogging(options.loglevel)
# Create a lock object
lk = lock.lock()
# and acquire the lock
lk.acquire()
# Automount stuff
mounter.autoMount()
#If we're running the GUI
if options.useGUI:
logging.debug("Attempting to setup GUI.")
try: #importing the gtk libraries
import pygtk
pygtk.require("2.0")
import gobject
except:
pass
try:
import gtk
import gtk.glade
import gobject
except:
logging.error("Unable to start the GUI!")
sys.exit("Cannot start GUI because Gtk is not available! Please make sure you are running in a graphical environment and that Gtk is installed.")
# Now add a console logging handler
addConsoleHandler()
#Now that the libraries are imported, start the GUI
logging.debug("Importing BackupGui for gui.")
from backupgui import BackupGui
hwg = BackupGui()
logging.debug("Initializing gobject threading.")
gobject.threads_init()
logging.debug("Starting gtk.main().")
gtk.main()
#Otherwise, we're running the command line interface (CLI)
else:
#Import important methods for the CLI
logging.debug("Importing BackupCLI for command-line environment.")
from backupcli import BackupCLI
logging.debug("Parsing input for CLI.")
hwg = BackupCLI(options, args)
logging.debug("Starting cli.")
hwg.start()
print "\n\n**********\nLog will be located at: %s \n**********\n\n" % global_log_file
print "**********\nPLEASE SAVE THE LOG\n**********\n\n"
# Release the lock file
lk.release()
def setupLogging(lvl):
loglevel = getattr(logging, default_log_level.upper(), None)
if not isinstance(loglevel, int):
raise ValueError('Invalid DEFAULT log level: %s' % default_log_level)
if lvl:
loglevel = getattr(logging, lvl.upper(), None)
if not isinstance(loglevel, int):
raise ValueError('Invalid log level: %s' % lvl)
logging.basicConfig(
format='%(asctime)s %(name)-18s: %(levelname)-8s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
filename=global_log_file,
filemode='a', # This will append to any previous log that exists, instead of overwriting
level=loglevel
)
logging.info("\n\n\n\n\n\n\n\n\n\n")
logging.info("Logging initialized.")
def addConsoleHandler():
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-18s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logging.info("Console handler for logging initialized.")
def start():
"""Create an OptionParser, and try to interpret the command line arguments"""
parser = initializeParser()
(options, args) = parser.parse_args()
checkArgs(options, args)
if __name__ == "__main__":
print
if not isRoot():
sys.exit("\nExiting: need r00t priviliges!\n")
start()