本文整理汇总了Python中models.dbsession.add函数的典型用法代码示例。如果您正苦于以下问题:Python add函数的具体用法?Python add怎么用?Python add使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了add函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: initialize
def initialize(self, *args):
''' One time initialization, gathers system information '''
success = False
logging.info(
"Preforming weapon system initialization, please wait ... ")
ssh_keyfile = NamedTemporaryFile()
ssh_keyfile.write(self.ssh_key)
ssh_keyfile.seek(0)
try:
logging.info("Connectiong to remote ssh server at %s:%s" %
(self.ip_address, self.ssh_port))
ssh_context = SshContext(self.ip_address,
user=self.ssh_user, keyfile=ssh_keyfile.name)
rpc_connection = rpyc.ssh_connect(ssh_context, self.service_port)
capabilities = rpc_connection.root.exposed_get_capabilities()
self.lm_capable = 'LM' in capabilities
self.ntlm_capable = 'NTLM' in capabilities
self.md5_capable = 'MD5' in capabilities
self.cpu_count = rpc_connection.root.exposed_cpu_count()
self.initialized = True
dbsession.add(self)
dbsession.flush()
success = True
except ValueError:
logging.exception(
"Failed to initialize weapon system, check parameters")
except EOFError:
logging.exception(
"Failed to initialize weapon system, check parameters")
finally:
ssh_keyfile.close()
return success
开发者ID:brutalhonesty,项目名称:The-Planetary-Assault-System,代码行数:32,代码来源:WeaponSystem.py
示例2: stats_complexity
def stats_complexity(self):
''' Returns stats on solved hash's plain text complexity '''
if self.cached_complexity_analysis == None:
complexity = []
if 0 < len(self.lower_case_passwords):
complexity.append(
{'Lower Case': len(self.lower_case_passwords)})
if 0 < len(self.upper_case_passwords):
complexity.append(
{'Upper Case': len(self.upper_case_passwords)})
if 0 < len(self.numeric_passwords):
complexity.append({'Numeric': len(self.numeric_passwords)})
if 0 < len(self.mixed_case_passwords):
complexity.append(
{'Mixed Case': len(self.mixed_case_passwords)})
if 0 < len(self.lower_alpha_numeric_passwords):
complexity.append({'Lower Case Alpha-numeric':
len(self.lower_alpha_numeric_passwords)})
if 0 < len(self.upper_alpha_numeric_passwords):
complexity.append({'Upper Case Alpha-numeric':
len(self.upper_alpha_numeric_passwords)})
if 0 < len(self.mixed_alpha_numeric_passwords):
complexity.append({'Mixed Case Alpha-numeric':
len(self.mixed_alpha_numeric_passwords)})
self.cached_complexity_analysis = json.dumps(complexity)
dbsession.add(self)
dbsession.flush()
return self.cached_complexity_analysis
开发者ID:brutalhonesty,项目名称:The-Planetary-Assault-System,代码行数:28,代码来源:Job.py
示例3: create_file
def create_file(self, user):
""" Saves uploaded file """
file_name = os.path.basename(self.request.files["file_data"][0]["filename"])
char_white_list = ascii_letters + digits + "-._"
file_name = filter(lambda char: char in char_white_list, file_name)
content = guess_type(file_name)
if content[0] is None:
self.render(
"share_upload/share_files.html",
errors=["Unknown file content, please zip and upload"],
shares=user.team.files,
)
elif len(file_name) < 1:
self.render("share_upload/share_files.html", errors=["Invalid file name"])
else:
uuid = unicode(uuid4())
filePath = self.application.settings["shares_dir"] + "/" + uuid
save = open(filePath, "w")
data = b64encode(self.request.files["file_data"][0]["body"])
save.write(data)
save.close()
file_upload = FileUpload(
file_name=unicode(file_name),
content=unicode(str(content[0])),
uuid=uuid,
description=unicode(self.get_argument("description")),
byte_size=len(self.request.files["file_data"][0]["body"]),
team_id=user.team.id,
)
dbsession.add(file_upload)
dbsession.flush()
self.event_manager.team_file_share(user, file_upload)
开发者ID:brutalhonesty,项目名称:RootTheBox,代码行数:32,代码来源:ShareUploadHandlers.py
示例4: create_file
def create_file(self, user):
''' Saves uploaded file '''
file_name = os.path.basename(
self.request.files['file_data'][0]['filename']
)
char_white_list = ascii_letters + digits + "-._"
file_name = filter(lambda char: char in char_white_list, file_name)
content = guess_type(file_name)
if content[0] is None:
self.render("share_upload/share_files.html",
errors=["Unknown file content, please zip and upload"],
shares=user.team.files
)
elif len(file_name) < 1:
self.render("share_upload/share_files.html",
errors=["Invalid file name"]
)
else:
uuid = unicode(uuid4())
filePath = self.application.settings['shares_dir'] + '/' + uuid
save = open(filePath, 'w')
data = b64encode(self.request.files['file_data'][0]['body'])
save.write(data)
save.close()
file_upload = FileUpload(
file_name=unicode(file_name),
content=unicode(str(content[0])),
uuid=uuid,
description=unicode(self.get_argument('description', 'No description.')),
byte_size=len(self.request.files['file_data'][0]['body']),
team_id=user.team.id
)
dbsession.add(file_upload)
dbsession.flush()
return file_upload
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:35,代码来源:ShareUploadHandlers.py
示例5: post
def post(self, *args, **kwargs):
user_uuid = self.get_argument('uuid', '')
user = User.by_uuid(user_uuid)
if user is not None:
errors = []
username = self.get_argument('username', None)
password = self.get_argument('password', None)
if password is not None:
if 12 <= len(password) <= 100:
self.change_user_password(user)
else:
errors.append("Password invalid length (12-100)")
if username is not None and username != user.username:
if 3 <= len(username) <= 15:
if User.by_username(username) is None:
user.username = username
dbsession.add(user)
dbsession.flush()
else:
errors.append("Username already exists")
else:
errors.append("Username is an invalid length (3-15)")
self.render("admin/manage_users.html", errors=errors)
else:
self.render("admin/manage_users.html",
errors=["User does not exist"]
)
开发者ID:DJHartley,项目名称:The-Planetary-Assault-System,代码行数:27,代码来源:AdminHandlers.py
示例6: create_team
def create_team():
team = Team()
team.name = "TestTeam"
team.motto = "TestMotto"
dbsession.add(team)
dbsession.commit()
return team
开发者ID:AdaFormacion,项目名称:RootTheBox,代码行数:7,代码来源:Helpers.py
示例7: edit_ipv6
def edit_ipv6(self):
''' Add ipv6 addresses to a box (sorta edits the box object) '''
form = Form(box_uuid="Select a box", ipv6="Please provide a list of IPv6 addresses")
if form.validate(self.request.arguments):
errors = []
box = Box.by_uuid(self.get_argument('box_uuid'))
if box is not None:
ips_string = self.get_argument('ipv6').replace('\n', ',').lower()
ips = filter(lambda char: char in "1234567890abcdef:,", ips_string).split(",")
for ip in filter(lambda ip: 0 < len(ip), ips):
try:
box = Box.by_ip_address(ip)
if box is None:
addr = IpAddress(box_id=box.id, v6=ip)
dbsession.add(addr)
else:
errors.append(
"%s has already been assigned to %s." % (ip, box.name,)
)
except ValueError:
errors.append(
"'%s' is not a valid IPv6 address" % str(ip[:39])
)
dbsession.flush()
else:
errors.append("Box does not exist")
self.render("admin/view/game_objects.html", errors=errors)
else:
self.render("admin/view/game_objects.html", errors=form.errors)
开发者ID:mach327,项目名称:RootTheBox,代码行数:29,代码来源:AdminHandlers.py
示例8: edit_users
def edit_users(self):
''' Update user objects in the database '''
form = Form(
uuid="User not selected",
account="Please enter an account name",
handle="Please enter a handle name",
hash_algorithm="Please select a hash algorithm",
team_uuid="Please select a team",
)
if form.validate(self.request.arguments):
errors = []
user = User.by_uuid(self.get_argument('uuid'))
if user is not None:
# Update user account name
if user.account != self.get_argument('account'):
if User.by_account(self.get_argument('account')) is None:
logging.info("Updated user account %s -> %s" %
(user.account, self.get_argument('account'),))
user.account = unicode(self.get_argument('account'))
else:
errors.append("Account name is already in use")
# Update user handle
if user.handle != self.get_argument('handle'):
if User.by_handle(self.get_argument('handle')) is None:
logging.info("Updated user handle %s -> %s" %
(user.handle, self.get_argument('handle'),))
user.handle = unicode(self.get_argument('handle'))
else:
errors.append("Handle is already in use")
# Update hashing algoritm
if self.get_argument('hash_algorithm') in user.algorithms:
if user.algorithm != self.get_argument('hash_algorithm'):
if 0 < len(self.get_argument('password', '')):
logging.info("Updated %s's hashing algorithm %s -> %s" %
(user.handle, user.algorithm, self.get_argument('hash_algorithm'),)
)
user.algorithm = self.get_argument('hash_algorithm')
else:
errors.append("You must provide a password when updating the hashing algorithm")
else:
errors.append("Not a valid hash algorithm")
# Update password
if 0 < len(self.get_argument('password', '')):
user.password = self.get_argument('password')
# Update team
team = Team.by_uuid(self.get_argument('team_uuid'))
if team is not None:
if user.team_id != team.id:
logging.info("Updated %s's team %s -> %s" %
(user.handle, user.team_id, team.name))
user.team_id = team.id
else:
errors.append("Team does not exist in database")
dbsession.add(user)
dbsession.flush()
else:
errors.append("User does not exist")
self.render("admin/view/user_objects.html", errors=errors)
else:
self.render("admin/view/user_objects.html", errors=form.errors)
开发者ID:mach327,项目名称:RootTheBox,代码行数:60,代码来源:AdminHandlers.py
示例9: __queue__
def __queue__(self):
''' Starts a job or leaves it in the queue (thread safe) '''
logging.debug("Attempting to acquire queue mutex ...")
self.mutex.acquire()
logging.debug("Successfully acquired queue mutex.")
queue = list(Job.queue()) # Create a copy of the queue
for job in queue:
logging.info("Dispatching job: %s" % job.job_name)
if len(job) == 0:
job.status = u"COMPLETED"
dbsession.add(job)
dbsession.flush()
else:
algo = Algorithm.by_id(job.algorithm_id)
weapon_systems = WeaponSystem.system_ready(algo)
if weapon_systems is not None and 0 < len(weapon_systems):
logging.info("Weapon systems available: %d" % (
len(weapon_systems),
))
thread.start_new_thread(
self.__crack__,
(job, weapon_systems[0],)
)
else:
logging.info("No available weapon systems at this time.")
self.mutex.release()
开发者ID:DJHartley,项目名称:The-Planetary-Assault-System,代码行数:26,代码来源:Dispatch.py
示例10: score_bots
def score_bots():
''' Award money for botnets '''
logging.info("Scoring botnets, please wait ...")
bot_manager = BotManager.instance()
event_manager = EventManager.instance()
for team in Team.all():
if len(team.members) > 0:
bots = bot_manager.by_team(team.name)
if 0 < len(bots):
reward = 0
for bot in bots:
try:
reward += options.bot_reward
bot.write_message({
'opcode': 'status',
'message': 'Collected $%d reward' % options.bot_reward
})
except:
logging.info(
"Bot at %s failed to respond to score ping" % bot.remote_ip
)
message = "%s was awarded $%d for controlling %s bot(s)" % (
team.name, reward, len(bots),
)
bot_manager.add_rewards(team.name, options.bot_reward)
bot_manager.notify_monitors(team.name)
team.money += reward
dbsession.add(team)
dbsession.flush()
event_manager.bot_scored(team, message)
dbsession.commit()
开发者ID:moloch--,项目名称:RootTheBox,代码行数:32,代码来源:Scoreboard.py
示例11: create_boxes
def create_boxes(parent, corporation):
''' Create boxes for a corporation '''
logging.info("Found %s boxes" % parent.get('count'))
for index, box_elem in enumerate(parent.getchildren()):
try:
name = get_child_text(box_elem, 'name')
game_level = GameLevel.by_number(box_elem.get('gamelevel'))
if game_level is None:
logging.warning("GameLevel does not exist for box %s, skipping" % name)
elif Box.by_name(name) is None:
box = Box(corporation_id=corporation.id)
box.name = name
box.game_level_id = game_level.id
box.difficulty = get_child_text(box_elem, 'difficulty')
box.description = get_child_text(box_elem, 'description')
box.operating_system = get_child_text(box_elem, 'operatingsystem')
box.avatar = get_child_text(box_elem, 'avatar').decode('base64')
box.garbage = get_child_text(box_elem, 'garbage')
dbsession.add(box)
dbsession.flush()
create_flags(get_child_by_tag(box_elem, 'flags'), box)
create_hints(get_child_by_tag(box_elem, 'hints'), box)
else:
logging.info("Box with name %s already exists, skipping" % name)
except:
logging.exception("Failed to import box %d" % (index + 1))
开发者ID:AdaFormacion,项目名称:RootTheBox,代码行数:26,代码来源:xmlsetup.py
示例12: post
def post(self, *args, **kwargs):
''' Change user password '''
user = self.get_current_user()
old_password = self.get_argument('old_password', None)
pass1 = self.get_argument('pass1', None)
pass2 = self.get_argument('pass2', None)
if old_password is None or pass1 is None or pass2 is None:
self.render('veil/settings.html',
errors=['Fill in all the forms']
)
elif len(pass1) < 12 or len(pass2) < 12:
self.render('veil/settings.html',
errors=['New password too short (min. 12)']
)
elif pass1 != pass2:
self.render('veil/settings.html',
errors=['New passwords do not match']
)
elif user.validate_password(old_password):
user.password = pass1
dbsession.add(user)
dbsession.flush()
self.render('veil/settings.html', errors=[])
else:
self.render('veil/settings.html',
errors=['Old password incorrect']
)
开发者ID:DJHartley,项目名称:Veil,代码行数:27,代码来源:VeilHandlers.py
示例13: create_levels
def create_levels(levels):
''' Create GameLevel objects based on XML data '''
logging.info("Found %s game level(s)" % levels.get('count'))
for index, level_elem in enumerate(levels.getchildren()):
# GameLevel 0 is created automatically by the bootstrap
if get_child_text(level_elem, 'number') != '0':
try:
number = get_child_text(level_elem, 'number')
if GameLevel.by_number(number) is None:
game_level = GameLevel()
game_level.number = number
game_level.buyout = get_child_text(level_elem, 'buyout')
dbsession.add(game_level)
else:
logging.info("GameLevel %d already exists, skipping" % number)
except:
logging.exception("Failed to import game level #%d" % (index + 1))
dbsession.flush()
game_levels = GameLevel.all()
for index, game_level in enumerate(game_levels):
if index + 1 < len(game_levels):
game_level.next_level_id = game_levels[index + 1].id
logging.info("%r -> %r" % (game_level, game_levels[index + 1]))
dbsession.add(game_level)
dbsession.commit()
开发者ID:AdaFormacion,项目名称:RootTheBox,代码行数:25,代码来源:xmlsetup.py
示例14: score_bots
def score_bots():
''' Award money for botnets '''
logging.info("Scoring botnets, please wait ...")
bot_manager = BotManager.Instance()
config = ConfigManager.Instance()
for team in Team.all():
bots = bot_manager.by_team(team.name)
reward = 0
for bot in bots:
try:
reward += config.bot_reward
bot.write_message({
'opcode': 'status',
'message': 'Collected $%d reward' % config.bot_reward
})
except:
logging.info(
"Bot at %s failed to respond to score ping" % bot.remote_ip
)
if 0 < len(bots):
logging.debug("%s was awarded $%d for controlling %s bot(s)" % (
team.name, reward, len(bots),
))
bot_manager.add_rewards(team.name, config.bot_reward)
bot_manager.notify_monitors(team.name)
team.money += reward
dbsession.add(team)
dbsession.flush()
开发者ID:lavalamp-,项目名称:RootTheBox,代码行数:28,代码来源:Scoreboard.py
示例15: delivered
def delivered(cls, user_id, uuid):
notify = dbsession.query(cls).filter(
and_(cls.event_uuid == uuid, cls.user_id == user_id)
).first()
notify.viewed = True
dbsession.add(notify)
dbsession.flush()
开发者ID:brutalhonesty,项目名称:RootTheBox,代码行数:7,代码来源:Notification.py
示例16: post
def post(self, *args, **kwargs):
''' Attempt to upgrade hash algo '''
form = Form(
old_password="Enter your existing password",
new_password1="Enter a new password",
new_password2="Confirm your new password",
)
if form.validate(self.request.arguments):
user = self.get_current_user()
passwd = self.get_argument('new_password1')
old_passwd = self.get_argument('old_password')
if not user.validate_password(old_passwd):
self.render_page(["Invalid password"])
elif not passwd == self.get_argument('new_password2'):
self.render_page(["New passwords do not match"])
elif user.team.money < self.config.password_upgrade:
self.render_page(["You cannot afford to upgrade your hash"])
elif len(passwd) <= self.config.max_password_length:
user.team.money -= self.config.password_upgrade
dbsession.add(user.team)
dbsession.flush()
self.update_password(passwd)
self.render_page()
else:
self.render_page(["New password is too long"])
else:
self.render_page(form.errors)
开发者ID:brutalhonesty,项目名称:RootTheBox,代码行数:27,代码来源:UpgradeHandlers.py
示例17: buyout
def buyout(self):
''' Buyout and unlock a level '''
form = Form(uuid="Level parameter missing")
user = self.get_current_user()
if form.validate(self.request.arguments):
level = GameLevel.by_uuid(self.get_argument('uuid', ''))
if level is not None and user is not None:
if level.buyout < user.team.money:
user.team.game_levels.append(level)
user.team.money -= level.buyout
dbsession.add(user.team)
self.event_manager.unlocked_level(user, level)
self.redirect("/user/missions")
else:
self.render("missions/view.html",
team=user.team,
errors=[
"You do not have enough money to unlock this level"
]
)
else:
self.render("missions/view.html",
team=user.team,
errors=["Level does not exist"]
)
else:
self.render("missions/view.html",
team=user.team,
errors=form.errors
)
开发者ID:brutalhonesty,项目名称:RootTheBox,代码行数:30,代码来源:MissionsHandler.py
示例18: buyout
def buyout(self):
''' Buyout and unlock a level '''
form = Form(uuid="Level parameter missing")
user = self.get_current_user()
if form.validate(self.request.arguments):
level = GameLevel.by_uuid(self.get_argument('uuid', ''))
if level is not None and user is not None:
if level.buyout < user.team.money:
logging.info("%s (%s) payed buyout for level #%d" % (
user.handle, user.team.name, level.number
))
user.team.game_levels.append(level)
user.team.money -= level.buyout
dbsession.add(user.team)
event = self.event_manager.create_unlocked_level_event(user, level)
self.new_events.append(event)
self.redirect("/user/missions")
else:
self.render("missions/view.html",
team=user.team,
errors=[
"You do not have enough money to unlock this level"
]
)
else:
self.render("missions/view.html",
team=user.team,
errors=["Level does not exist"]
)
else:
self.render("missions/view.html",
team=user.team,
errors=form.errors
)
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:34,代码来源:MissionsHandler.py
示例19: post_avatar
def post_avatar(self, *args, **kwargs):
'''
Saves avatar - Reads file header an only allows approved formats
'''
user = User.by_id(self.session['user_id'])
if 'avatar' in self.request.files:
if len(self.request.files['avatar'][0]['body']) < (1024 * 1024):
if user.avatar == "default_avatar.jpeg":
user.avatar = unicode(uuid4()) + u".jpeg"
ext = imghdr.what(
"", h=self.request.files['avatar'][0]['body']
)
avatar_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar)
if ext in ['png', 'jpeg', 'gif', 'bmp']:
if os.path.exists(avatar_path):
os.unlink(avatar_path)
user.avatar = unicode(user.avatar[:user.avatar.rfind('.')] + "." + ext)
file_path = str(self.application.settings['avatar_dir'] + '/' + user.avatar)
avatar = open(file_path, 'wb')
avatar.write(self.request.files['avatar'][0]['body'])
avatar.close()
dbsession.add(user)
dbsession.flush()
self.render_page(success=["Successfully changed avatar"])
else:
self.render_page(
errors=["Invalid image format, avatar must be: .png .jpeg .gif or .bmp"]
)
else:
self.render_page(errors=["The image is too large"])
else:
self.render_page(errors=["Please provide an image"])
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:32,代码来源:UserHandlers.py
示例20: create_flag
def create_flag(name, token, value, box, description="No description", is_file=False):
if Flag.by_name(name) is not None:
logging.info("Flag with name '%s' already exists, skipping" % (name))
return Flag.by_name(name)
if Flag.by_token(token) is not None:
logging.info("Flag with token '%s' already exists, skipping" % (token))
return Flag.by_token(token)
if is_file and os.path.exists(token):
with open(token) as favatar:
_token = Flag.digest(favatar.read())
elif is_file and 40 == len(token):
_token = unicode(token) # Just assume it's a SHA1
elif is_file:
raise ValueError("Flag token file does not exist, and is not a hash.")
else:
_token = unicode(token[:256])
logging.info("Create Flag: %s" % name)
flag = Flag(
name=unicode(name[:32]),
token=_token,
is_file=is_file,
description=unicode(description[:256]),
value=abs(int(value)),
box_id=box.id,
)
dbsession.add(flag)
dbsession.flush()
return flag
开发者ID:CRYPTOlab,项目名称:RootTheBox,代码行数:28,代码来源:helpers.py
注:本文中的models.dbsession.add函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论