Привет Коллеги!
Помогите разобраться со скриптом.
Скрипт обрабатывает события. Используются модули logging для ведения логирования, argparse для обработки опций и аргументов командной строки и suds для отправки SOAP-запроса.
Как я понял, скрипт ведет лог-файл по входам пользователей в lanbilling и отражает его действия, с отображением его логин, пароль и информацию логирования. Все ли верно или что-то упустил?
Python 2.6.6
class attrdict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
client = None
LB = attrdict({
'login': 'хххххххххх',
'password': 'ххххххххх',
'debug': True
})
#
try:
import logging
import sys
from logging import debug, info, warning, error, critical, log
logging.basicConfig(
format='%(asctime)-15s +%(relativeCreated)-7d %(module)-12s %(process)5d %(lineno)-3d %(levelname)-8s %(message)s',
filename='/var/log/billing/name.log',
level=logging.DEBUG)
rootLogger = logging.getLogger()
sudsLogger = logging.getLogger('suds')
info('Starting up %s', ' '.join(sys.argv))
import argparse
argParser = argparse.ArgumentParser(description=__doc__)
argParser.add_argument('--sysid', '-s',
help='agent ID number', type=int,
required=True)
argParser.add_argument('--action', '-a',
help='action',
choices=['on', 'off', 'create', 'delete', 'edit'],
required=True)
argParser.add_argument('--vgid', '-v',
help='vgroup ID', type=int,
required=True)
argParser.add_argument('--login', '-l',
help='vgroup login', type=str)
argParser.add_argument('--password', '-p',
help='vgroup password', type=str)
argParser.add_argument('--debug', '-d',
help='debug mode', action='store_true')
o = argParser.parse_args()
o.debug = True
if o.debug:
rootLogger.setLevel(logging.DEBUG)
if o.sysid != 3:
info('Not implemented for sysid %d (vgid %d)', o.sysid, o.vgid)
sys.exit(0)
if o.action not in ('on', 'off'):
info('Not implemented for action "%s" (vgid %d)', o.action, o.vgid)
sys.exit(0)
sudsLogger.setLevel(logging.INFO)
info('Command-line arguments parsed: %s', str(o))
from suds import WebFault
from suds.client import Client
client = Client("https://10.10.10.10/admin/soap/api1.wsdl")
manager = client.service.Login(LB.login, LB.password)
manager = manager[0]
LB['personid'] = manager.manager.personid
soapBlockRasp = client.factory.create('soapBlockRasp')
soapBlockRasp.requestby = LB.personid
soapFilter = client.factory.create('soapFilter')
soapFilter.agentid = o.sysid
soapFilter.vgid = o.vgid
p = client.service.getVgroups(soapFilter)
if len(p) == 0:
raise KeyError, o.vgid
elif len(p) > 1:
raise KeyError, o.vgid
p = p[0]
info('Parent vgroup: vgid %d, agent %d, login %s, agreement "%s" (%d), lock state: %d',
p.vgid, p.id, p.login, p.agrmnum, p.agrmid, p.blocked)
if o.action == 'on':
soapBlockRasp.blkreq = 0
elif o.action == 'off':
if p.blocked == 10:
soapBlockRasp.blkreq = 10
elif p.blocked == 0:
soapBlockRasp.blkreq = 0
else:
soapBlockRasp.blkreq = 3
else:
error('Not implemented action "%d", should have exited earlier', o.action)
raise NotImplementedError, o.action
info('action: %s, lock required: %d', o.action, soapBlockRasp.blkreq)
soapFilter = client.factory.create('soapFilter')
template = client.factory.create('soapSearchTemplate')
template.tablename = "vgroups"
template.field = "parent_vg_id"
template.condition = "="
template.value = o.vgid
soapFilter.searchtempl.append(template)
subvgroups = client.service.getVgroups(soapFilter)
info('%d subvgroups found (parent:%d) for state %d (parent:%d)',
len(subvgroups), o.vgid, soapBlockRasp.blkreq, p.blocked)
for s in subvgroups:
info("found subvgroup %d with lock state %d", s.vgid, s.blocked)
if s.blocked == soapBlockRasp.blkreq:
pass
else:
soapBlockRasp.vgid = s.vgid
soapBlockRasp.id = s.id
respo = client.service.insBlkRasp(soapBlockRasp)
info('adding lock/unlock request for subvgroup %d (parent:%d), result: %d',
s.vgid, o.vgid, respo)
except Exception, e:
print "Something went horribly wrong:", str(e)
error(str(e))
raise
finally:
if client is not None:
info('Exiting (logging off SOAP)')
client.service.Logout()
else:
info("Exiting (SOAP wasn't connected)")