Commit e080dab9 authored by Hanno Schlichting's avatar Hanno Schlichting

flake8 Zope2/utilities.

parent 4903e67c
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
# #
############################################################################## ##############################################################################
def run(): def run():
""" Start a Zope instance """ """ Start a Zope instance """
import Zope2.Startup import Zope2.Startup
...@@ -25,6 +26,7 @@ def run(): ...@@ -25,6 +26,7 @@ def run():
raise raise
starter.run() starter.run()
def configure(configfile): def configure(configfile):
""" Provide an API which allows scripts like zopectl to configure """ Provide an API which allows scripts like zopectl to configure
Zope before attempting to do 'app = Zope2.app(). Should be used as Zope before attempting to do 'app = Zope2.app(). Should be used as
...@@ -38,6 +40,7 @@ def configure(configfile): ...@@ -38,6 +40,7 @@ def configure(configfile):
starter.dropPrivileges() starter.dropPrivileges()
return starter return starter
def _setconfig(configfile=None): def _setconfig(configfile=None):
""" Configure a Zope instance based on ZopeOptions. Optionally """ Configure a Zope instance based on ZopeOptions. Optionally
accept a configfile argument (string path) in order to specify accept a configfile argument (string path) in order to specify
...@@ -56,6 +59,7 @@ def _setconfig(configfile=None): ...@@ -56,6 +59,7 @@ def _setconfig(configfile=None):
App.config.setConfiguration(opts.configroot) App.config.setConfiguration(opts.configroot)
return opts return opts
def make_wsgi_app(global_config, zope_conf): def make_wsgi_app(global_config, zope_conf):
from App.config import setConfiguration from App.config import setConfiguration
from Zope2.Startup import get_starter from Zope2.Startup import get_starter
...@@ -72,6 +76,6 @@ def make_wsgi_app(global_config, zope_conf): ...@@ -72,6 +76,6 @@ def make_wsgi_app(global_config, zope_conf):
starter.prepare() starter.prepare()
return publish_module return publish_module
if __name__ == '__main__': if __name__ == '__main__':
run() run()
...@@ -28,18 +28,18 @@ def main(argv=sys.argv): ...@@ -28,18 +28,18 @@ def main(argv=sys.argv):
try: try:
user, pwd = argv[1], argv[2] user, pwd = argv[1], argv[2]
except IndexError: except IndexError:
print "%s <username> <password>" % argv[0] print("%s <username> <password>" % argv[0])
sys.exit(255) sys.exit(255)
finder = ZopeFinder(argv) finder = ZopeFinder(argv)
finder.filter_warnings() finder.filter_warnings()
app = finder.get_app() app = finder.get_app()
result = adduser(app, user, pwd) result = adduser(app, user, pwd)
if result: if result:
print "User %s created." % user print("User %s created." % user)
else: else:
print "Got no result back. User creation may have failed." print("Got no result back. User creation may have failed.")
print "Maybe the user already exists and nothing is done then." print("Maybe the user already exists and nothing is done then.")
print "Or the implementation does not give info when it succeeds." print("Or the implementation does not give info when it succeeds.")
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -65,18 +65,21 @@ import shutil ...@@ -65,18 +65,21 @@ import shutil
import sys import sys
import getopt import getopt
CVS_DIRS = [os.path.normcase("CVS"), os.path.normcase(".svn")]
def main(): def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], opts, args = getopt.getopt(
sys.argv[1:],
"hs:t:u:g:r:", "hs:t:u:g:r:",
["help", "sourcedir=", "targetdir=", "uid=", "gid=", ["help", "sourcedir=", "targetdir=", "uid=", "gid=",
"replace="] "replace="]
) )
except getopt.GetoptError, msg: except getopt.GetoptError as msg:
usage(sys.stderr, msg) usage(sys.stderr, msg)
sys.exit(2) sys.exit(2)
script = os.path.abspath(sys.argv[0])
sourcedir = None sourcedir = None
targetdir = None targetdir = None
uid = None uid = None
...@@ -120,7 +123,7 @@ def main(): ...@@ -120,7 +123,7 @@ def main():
sys.exit(2) sys.exit(2)
except (ImportError, AttributeError): except (ImportError, AttributeError):
usage(sys.stderr, usage(sys.stderr,
"Your system does not support the gid or uid options") "Your system does not support the gid or uid options")
sys.exit(2) sys.exit(2)
if opt in ("-g", "--gid"): if opt in ("-g", "--gid"):
if not arg: if not arg:
...@@ -143,7 +146,7 @@ def main(): ...@@ -143,7 +146,7 @@ def main():
sys.exit(2) sys.exit(2)
except (ImportError, AttributeError): except (ImportError, AttributeError):
usage(sys.stderr, usage(sys.stderr,
"Your system does not support the gid or uid options") "Your system does not support the gid or uid options")
sys.exit(2) sys.exit(2)
if opt in ("-r", "--replace"): if opt in ("-r", "--replace"):
...@@ -162,6 +165,7 @@ def main(): ...@@ -162,6 +165,7 @@ def main():
copyskel(sourcedir, targetdir, uid, gid, **replacements) copyskel(sourcedir, targetdir, uid, gid, **replacements)
def copyskel(sourcedir, targetdir, uid, gid, **replacements): def copyskel(sourcedir, targetdir, uid, gid, **replacements):
""" This is an independent function because we'd like to """ This is an independent function because we'd like to
import and call it from mkzopeinstance """ import and call it from mkzopeinstance """
...@@ -180,7 +184,7 @@ def copyskel(sourcedir, targetdir, uid, gid, **replacements): ...@@ -180,7 +184,7 @@ def copyskel(sourcedir, targetdir, uid, gid, **replacements):
(targetdir, replacements, uid, gid)) (targetdir, replacements, uid, gid))
finally: finally:
os.chdir(pwd) os.chdir(pwd)
except (IOError, OSError), msg: except (IOError, OSError) as msg:
print >>sys.stderr, msg print >>sys.stderr, msg
sys.exit(1) sys.exit(1)
...@@ -191,9 +195,8 @@ def copyskel(sourcedir, targetdir, uid, gid, **replacements): ...@@ -191,9 +195,8 @@ def copyskel(sourcedir, targetdir, uid, gid, **replacements):
os.chmod(fullname, 0700) os.chmod(fullname, 0700)
CVS_DIRS = [os.path.normcase("CVS"), os.path.normcase(".svn")] def copydir(args, sourcedir, names):
targetdir, replacements, uid, gid = args
def copydir((targetdir, replacements, uid, gid), sourcedir, names):
# Don't recurse into CVS directories: # Don't recurse into CVS directories:
for name in names[:]: for name in names[:]:
if os.path.normcase(name) in CVS_DIRS: if os.path.normcase(name) in CVS_DIRS:
...@@ -227,6 +230,7 @@ def copydir((targetdir, replacements, uid, gid), sourcedir, names): ...@@ -227,6 +230,7 @@ def copydir((targetdir, replacements, uid, gid), sourcedir, names):
if uid is not None: if uid is not None:
os.chown(dn, uid, gid) os.chown(dn, uid, gid)
def copyin(src, dst, replacements, uid, gid): def copyin(src, dst, replacements, uid, gid):
ifp = open(src) ifp = open(src)
text = ifp.read() text = ifp.read()
...@@ -240,12 +244,13 @@ def copyin(src, dst, replacements, uid, gid): ...@@ -240,12 +244,13 @@ def copyin(src, dst, replacements, uid, gid):
if uid is not None: if uid is not None:
os.chown(dst, uid, gid) os.chown(dst, uid, gid)
def usage(stream, msg=None): def usage(stream, msg=None):
if msg: if msg:
print >>stream, msg stream.write(msg)
print >>stream stream.write('\n')
program = os.path.basename(sys.argv[0]) program = os.path.basename(sys.argv[0])
print >>stream, __doc__ % {"program": program} stream.write(__doc__ % {"program": program})
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
import os import os
class ZopeFinder: class ZopeFinder(object):
def __init__(self, argv): def __init__(self, argv):
self.cmd = argv[0] self.cmd = argv[0]
......
...@@ -31,13 +31,18 @@ import os ...@@ -31,13 +31,18 @@ import os
import sys import sys
import copyzopeskel import copyzopeskel
if sys.version_info > (3, 0):
raw_input = input
def main(): def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], opts, args = getopt.getopt(
sys.argv[1:],
"hu:d:s:p:", "hu:d:s:p:",
["help", "user=", "dir=", "skelsrc=", "python="] ["help", "user=", "dir=", "skelsrc=", "python="]
) )
except getopt.GetoptError, msg: except getopt.GetoptError as msg:
usage(sys.stderr, msg) usage(sys.stderr, msg)
sys.exit(2) sys.exit(2)
...@@ -74,7 +79,7 @@ def main(): ...@@ -74,7 +79,7 @@ def main():
if not arg: if not arg:
usage(sys.stderr, "user must not be empty") usage(sys.stderr, "user must not be empty")
sys.exit(2) sys.exit(2)
if not ":" in arg: if ":" not in arg:
usage(sys.stderr, "user must be specified as name:password") usage(sys.stderr, "user must be specified as name:password")
sys.exit(2) sys.exit(2)
user, password = arg.split(":", 1) user, password = arg.split(":", 1)
...@@ -85,10 +90,9 @@ def main(): ...@@ -85,10 +90,9 @@ def main():
# to skeltarget. # to skeltarget.
skeltarget = instancehome = os.path.abspath( skeltarget = instancehome = os.path.abspath(
os.path.expanduser(get_skeltarget()) os.path.expanduser(get_skeltarget())
) )
instancehome = skeltarget instancehome = skeltarget
configfile = os.path.join(instancehome, 'etc', 'zope.conf')
if skelsrc is None: if skelsrc is None:
# default to using stock Zope skeleton source # default to using stock Zope skeleton source
skelsrc = os.path.join(os.path.dirname(__file__), "skel") skelsrc = os.path.join(os.path.dirname(__file__), "skel")
...@@ -105,14 +109,14 @@ def main(): ...@@ -105,14 +109,14 @@ def main():
# need be used. # need be used.
if python is None: if python is None:
python = sys.executable python = sys.executable
psplit = os.path.split(python) psplit = os.path.split(python)
exedir = os.path.join(*psplit[:-1]) exedir = os.path.join(*psplit[:-1])
pythonexe = os.path.join(exedir, 'python.exe') pythonexe = os.path.join(exedir, 'python.exe')
pythonwexe = os.path.join(exedir, 'pythonw.exe') pythonwexe = os.path.join(exedir, 'pythonw.exe')
if ( os.path.isfile(pythonwexe) and os.path.isfile(pythonexe) and if (os.path.isfile(pythonwexe) and os.path.isfile(pythonexe) and
(python in [pythonwexe, pythonexe]) ): (python in [pythonwexe, pythonexe])):
# we're using a Windows build with both python.exe and pythonw.exe # we're using a Windows build with both python.exe and pythonw.exe
# in the same directory # in the same directory
PYTHON = pythonexe PYTHON = pythonexe
...@@ -124,17 +128,18 @@ def main(): ...@@ -124,17 +128,18 @@ def main():
zope2path = get_zope2path(PYTHON) zope2path = get_zope2path(PYTHON)
kw = { kw = {
"PYTHON":PYTHON, "PYTHON": PYTHON,
"PYTHONW":PYTHONW, "PYTHONW": PYTHONW,
"INSTANCE_HOME": instancehome, "INSTANCE_HOME": instancehome,
"ZOPE_SCRIPTS": script_path, "ZOPE_SCRIPTS": script_path,
"ZOPE2PATH": zope2path, "ZOPE2PATH": zope2path,
} }
copyzopeskel.copyskel(skelsrc, skeltarget, None, None, **kw) copyzopeskel.copyskel(skelsrc, skeltarget, None, None, **kw)
if user and password: if user and password:
write_inituser(inituser, user, password) write_inituser(inituser, user, password)
def usage(stream, msg=None): def usage(stream, msg=None):
if msg: if msg:
print >>stream, msg print >>stream, msg
...@@ -142,25 +147,27 @@ def usage(stream, msg=None): ...@@ -142,25 +147,27 @@ def usage(stream, msg=None):
program = os.path.basename(sys.argv[0]) program = os.path.basename(sys.argv[0])
print >>stream, __doc__ % {"program": program} print >>stream, __doc__ % {"program": program}
def get_skeltarget(): def get_skeltarget():
print 'Please choose a directory in which you\'d like to install' print('Please choose a directory in which you\'d like to install')
print 'Zope "instance home" files such as database files, configuration' print('Zope "instance home" files such as database files, configuration')
print 'files, etc.' print('files, etc.')
print print
while 1: while 1:
skeltarget = raw_input("Directory: ").strip() skeltarget = raw_input("Directory: ").strip()
if skeltarget == '': if skeltarget == '':
print 'You must specify a directory' print('You must specify a directory')
continue continue
else: else:
break break
return skeltarget return skeltarget
def get_inituser(): def get_inituser():
import getpass import getpass
print 'Please choose a username and password for the initial user.' print('Please choose a username and password for the initial user.')
print 'These will be the credentials you use to initially manage' print('These will be the credentials you use to initially manage')
print 'your new Zope instance.' print('your new Zope instance.')
print print
user = raw_input("Username: ").strip() user = raw_input("Username: ").strip()
if user == '': if user == '':
...@@ -172,9 +179,10 @@ def get_inituser(): ...@@ -172,9 +179,10 @@ def get_inituser():
break break
else: else:
passwd = verify = '' passwd = verify = ''
print "Password mismatch, please try again..." print("Password mismatch, please try again...")
return user, passwd return user, passwd
def write_inituser(fn, user, password): def write_inituser(fn, user, password):
import binascii import binascii
try: try:
...@@ -185,7 +193,8 @@ def write_inituser(fn, user, password): ...@@ -185,7 +193,8 @@ def write_inituser(fn, user, password):
pw = binascii.b2a_base64(sha(password).digest())[:-1] pw = binascii.b2a_base64(sha(password).digest())[:-1]
fp.write('%s:{SHA}%s\n' % (user, pw)) fp.write('%s:{SHA}%s\n' % (user, pw))
fp.close() fp.close()
os.chmod(fn, 0644) os.chmod(fn, 0o644)
def check_buildout(script_path): def check_buildout(script_path):
""" Are we running from within a buildout which supplies 'zopepy'? """ Are we running from within a buildout which supplies 'zopepy'?
...@@ -197,6 +206,7 @@ def check_buildout(script_path): ...@@ -197,6 +206,7 @@ def check_buildout(script_path):
parser.read(buildout_cfg) parser.read(buildout_cfg)
return 'zopepy' in parser.sections() return 'zopepy' in parser.sections()
def get_zope2path(python): def get_zope2path(python):
""" Get Zope2 path from selected Python interpreter. """ Get Zope2 path from selected Python interpreter.
""" """
......
This diff is collapsed.
...@@ -37,13 +37,22 @@ for all necessary information. The available options are: ...@@ -37,13 +37,22 @@ for all necessary information. The available options are:
Filename is required and should be the name of the file to store the Filename is required and should be the name of the file to store the
information in (usually "inituser" or "access"). information in (usually "inituser" or "access").
""" """
import sys, sha, binascii, random, getopt, getpass, os import binascii
import getopt
import getpass
import os
import random
import sha
import sys
try: try:
from crypt import crypt from crypt import crypt
except ImportError: except ImportError:
crypt = None crypt = None
if sys.version_info > (3, 0):
raw_input = input
PROGRAM = sys.argv[0] PROGRAM = sys.argv[0]
COMMASPACE = ', ' COMMASPACE = ', '
...@@ -53,10 +62,11 @@ def generate_salt(): ...@@ -53,10 +62,11 @@ def generate_salt():
salt_choices = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" salt_choices = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz"
"0123456789./") "0123456789./")
return random.choice(salt_choices)+random.choice(salt_choices) return random.choice(salt_choices) + random.choice(salt_choices)
def generate_passwd(password, encoding): def generate_passwd(password, encoding):
encoding=encoding.upper() encoding = encoding.upper()
if encoding == 'SHA': if encoding == 'SHA':
pw = '{SHA}' + binascii.b2a_base64(sha.new(password).digest())[:-1] pw = '{SHA}' + binascii.b2a_base64(sha.new(password).digest())[:-1]
elif encoding == 'CRYPT': elif encoding == 'CRYPT':
...@@ -68,26 +78,28 @@ def generate_passwd(password, encoding): ...@@ -68,26 +78,28 @@ def generate_passwd(password, encoding):
return pw return pw
def write_generated_password(home, ac_path, username): def write_generated_password(home, ac_path, username):
pw_choices = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" pw_choices = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz"
"0123456789!") "0123456789!")
acfile=open(ac_path, 'w') acfile = open(ac_path, 'w')
pw = '' pw = ''
for i in range(8): for i in range(8):
pw = pw + random.choice(pw_choices) pw = pw + random.choice(pw_choices)
acfile.write('%s:%s\n' % (username, generate_passwd(pw, 'SHA'))) acfile.write('%s:%s\n' % (username, generate_passwd(pw, 'SHA')))
acfile.close() acfile.close()
os.chmod(ac_path, 0644) os.chmod(ac_path, 0o644)
return pw return pw
def write_access(home, user='', group=''): def write_access(home, user='', group=''):
ac_path=os.path.join(home, 'access') ac_path = os.path.join(home, 'access')
if not os.path.exists(ac_path): if not os.path.exists(ac_path):
print '-'*78 print('-' * 78)
print 'creating default access file' print('creating default access file')
pw = write_generated_password(home, ac_path, 'emergency') pw = write_generated_password(home, ac_path, 'emergency')
print """Note: print("""Note:
The emergency user name and password are 'emergency' The emergency user name and password are 'emergency'
and '%s'. and '%s'.
...@@ -95,9 +107,11 @@ def write_access(home, user='', group=''): ...@@ -95,9 +107,11 @@ def write_access(home, user='', group=''):
zpasswd script. To find out more, type: zpasswd script. To find out more, type:
%s zpasswd.py %s zpasswd.py
""" % (pw, sys.executable) """ % (pw, sys.executable))
import do
do.ch(ac_path, user, group)
import do; do.ch(ac_path, user, group)
def get_password(): def get_password():
while 1: while 1:
...@@ -107,29 +121,31 @@ def get_password(): ...@@ -107,29 +121,31 @@ def get_password():
return password return password
else: else:
password = verify = '' password = verify = ''
print "Password mismatch, please try again..." print("Password mismatch, please try again...")
def write_inituser(home, user='', group=''): def write_inituser(home, user='', group=''):
ac_path=os.path.join(home, 'inituser') ac_path = os.path.join(home, 'inituser')
if not os.path.exists(ac_path): if not os.path.exists(ac_path):
print '-'*78 print('-' * 78)
print 'creating default inituser file' print('creating default inituser file')
pw = write_generated_password(home, ac_path, 'admin') pw = write_generated_password(home, ac_path, 'admin')
print """Note: print("""Note:
The initial user name and password are 'admin' The initial user name and password are 'admin'
and '%s'. and '%s'.
You can change the name and password through the web You can change the name and password through the web
interface or using the 'zpasswd.py' script. interface or using the 'zpasswd.py' script.
""" % pw """ % pw)
import do; do.ch(ac_path, user, group) import do
do.ch(ac_path, user, group)
def usage(code, msg=''): def usage(code, msg=''):
print >> sys.stderr, __doc__ % globals() sys.stderr.write(__doc__ % globals())
if msg: if msg:
print >> sys.stderr, msg sys.stderr.write(msg)
sys.exit(code) sys.exit(code)
...@@ -143,7 +159,7 @@ def main(): ...@@ -143,7 +159,7 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], shortopts, longopts) opts, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
except getopt.error, msg: except getopt.error as msg:
usage(1, msg) usage(1, msg)
# Defaults # Defaults
...@@ -183,15 +199,15 @@ def main(): ...@@ -183,15 +199,15 @@ def main():
break break
password = get_password() password = get_password()
while 1: while 1:
print """ print("""
Please choose a format from: Please choose a format from:
SHA - SHA-1 hashed password (default) SHA - SHA-1 hashed password (default)
CRYPT - UNIX-style crypt password CRYPT - UNIX-style crypt password
CLEARTEXT - no protection CLEARTEXT - no protection
""" """)
encoding = raw_input("Encoding: ") encoding = raw_input("Encoding: ")
if encoding == '': if encoding == '':
encoding = 'SHA' encoding = 'SHA'
...@@ -210,5 +226,5 @@ CLEARTEXT - no protection ...@@ -210,5 +226,5 @@ CLEARTEXT - no protection
# If called from the command line # If called from the command line
if __name__=='__main__': if __name__ == '__main__':
main() main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment