add brief support, modified display result, add support many methods

develop
Спиридонов Денис 12 years ago
parent a04b62911f
commit 6d5768335c

@ -27,6 +27,7 @@ from function import create_obj, get_sid, analysis, clear, get_entire_frame
from pid_information import client_list_methods
from cert_func import client_post_auth, client_post_request, client_get_cert, \
client_post_cert
from sid_func import session_clean, client_session_info
from cert_verify import get_CRL, VerifyError
import argparse, datetime
@ -60,19 +61,14 @@ def client_signal(client):
sys.exit()
time.sleep(float(client_active))
#url = 'http://localhost:8888/TestService/?wsdl'
def test(client, com=None):
if not com:
method_name = 'test'
else:
method_name = com
view = client.service[0][method_name + '_view']()
#print '==>', view
cr = create_obj(client, method_name)
#print 'ddd',cr
#print type (cr)
list_param = dir (cr)
param_list = []
@ -166,6 +162,12 @@ def parse():
parser.add_argument(
'--pid-kill', type=int, metavar = 'PID',
dest='pid_kill', help=_("kill selected process"))
parser.add_argument(
'--session-clean', action='store_true', default=False,
dest='session_clean', help=_('Clear cache session'))
parser.add_argument(
'--session-info', action='store_true', default=False,
dest='session_info', help=_("View session information"))
parser.add_argument(
'--update-crl', action='store_true', default=False,
dest='update_crl', help=_("update the certificate revocation lists"))
@ -174,6 +176,12 @@ def parse():
def https_server(client, args, unknown_args, url, clVarsCore):
client_post_auth(client)
if args.session_clean:
session_clean(client)
if args.session_info:
client_session_info(client)
if args.list_pid:
if args.dump:
from pid_information import client_pid_info
@ -181,7 +189,6 @@ def https_server(client, args, unknown_args, url, clVarsCore):
else:
from pid_information import client_list_pid
client_list_pid(client)
return 0
if args.pid_res:
get_entire_frame(client, args.pid_res)
@ -210,8 +217,10 @@ def https_server(client, args, unknown_args, url, clVarsCore):
client.frame_period = 2
method_result = call_method(client, args)
analysis(client, client.sid, method_result)
try:
analysis(client, client.sid, method_result)
except urllib2.URLError, e:
print e
# Vars = DataVarsCore()
# Vars.importCore()
# Vars.flIniFile()
@ -341,6 +350,8 @@ def main():
now = datetime.datetime.now()
print '5 ===> %ds %dms' %(now.second, now.microsecond)
https_server(client, args, unknown_args, url, clVarsCore)
now = datetime.datetime.now()
print 'END ===> %ds %dms' %(now.second, now.microsecond)
#----------------------------------------------------
except WebFault, f:
print _("Exception: %s") %f

@ -18,7 +18,7 @@ import time, os, sys, re
import subprocess
from OpenSSL import crypto
import shlex
import suds
from suds import MethodNotFound
from calculate.core.server.cert_cmd import getHwAddr, getIpLocal
from calculate.lib.cl_lang import setLocalTranslate
@ -100,6 +100,91 @@ def get_ip_mac_type(client_type = None):
results.append ('console')
return results
def print_brief_group(Fields, group_name):
if group_name:
print group_name
uncompatible_count = 0
green = '\033[32m * \033[0m'
red = '\033[31m * \033[0m'
for field in Fields:
if field.uncompatible:
uncompatible_count += 1
continue
if field.element in ['input', 'openfile']:
value = field.value if field.value else ''
print green+'%s: %s' %(field.label, value)
elif field.element in ['combo', 'comboEdit', 'radio', 'file']:
if hasattr (field.comments, 'string') and field.value in \
field.choice.string:
value = map(lambda x: field.comments.string[x] \
if len(field.comments.string) > x \
else field.choice.string[x],
map(lambda x: field.choice.string.index(x), \
[field.value]))
value = ', '.join(value)
else:
value = field.value if field.value else ''
print green+'%s: %s' %(field.label, value)
elif field.element in ['multichoice', 'multichoice_add',\
'selecttable', 'selecttable_add']:
if hasattr (field.comments, 'string') and \
hasattr (field.listvalue, 'string'):
value = map(lambda x: field.comments.string[x] \
if len(field.comments.string) > x \
else field.choice.string[x],
map(lambda x: field.choice.string.index(x), \
field.listvalue.string))
value = ', '.join(value)
elif hasattr (field.listvalue, 'string'):
value = ', '.join(field.listvalue.string)
else:
value = field.value if field.value else ''
print green+'%s: %s' %(field.label, value)
#
# elif field.element == 'label':
# print field.label
elif field.element == 'error':
print red + 'Error: %s' %field.label
elif field.element in ['check', 'check_tristate']:
if field.value == 'on':
value = 'yes'
elif field.value == 'off':
value = 'no'
else:
value = field.value
print green+'%s: %s' %(field.label, value)
elif field.element == 'table' and field.type != 'steps':
if hasattr (field.tablevalue.head, 'string'):
head = field.tablevalue.head.string
else: head = None
body = []
if hasattr (field.tablevalue.body, 'stringArray'):
for row in field.tablevalue.body.stringArray:
if hasattr(row, 'string'):
body.append(row.string)
else: body = [[]]
print printTable(body, head)
else:
uncompatible_count += 1
if uncompatible_count == len (Fields) and group_name:
print green+'NONE'
def print_brief(view, brief_label):
print brief_label
for Group in view.groups.GroupField:
if Group.name:
if not Group.fields:
continue
print_brief_group(Group.fields.Field, Group.name)
def create_obj(client, method_name):
""" create object indispensable for transfer to the server function """
sd_item = 0
@ -119,7 +204,7 @@ def create_obj(client, method_name):
info = operation.methods.get(method_name)
if not info:
raise suds.MethodNotFound(method_name)
raise MethodNotFound(method_name)
type_op = info.binding.input.param_defs(info)[param][inf_param]
str_type = type_op.__getattribute__('type')[param_type]
@ -183,7 +268,7 @@ def show_view(view):
def printTable(data, header=None ):
res = []
for row in data:
encode_row = map(lambda x: x.encode('utf-8'), row)
encode_row = map(lambda x: x.encode('utf-8') if x else None, row)
res.append(encode_row)
data = res
@ -272,12 +357,31 @@ def startGroup(item):
def endGruop(item):
pass
def callView(item, sid):
def _create_obj(client, method):
try:
view_params = create_obj(client, method)
except MethodNotFound:
if method.endswith('_view'):
method = method[:-5]
print _('Method not found: ') + method
sys.exit(1)
return view_params
def get_view_params(client, method, step = None, expert = None, brief = None):
view_params = _create_obj(client, method)
view_params.step = step
view_params.expert = expert
view_params.brief = brief
return view_params
def callView(client, item, sid):
return
print "\n\n",item.message
try:
view = client.service[0][item.message] (sid)
show_view (view)
view_params = get_view_params(client, item.message, brief = True, \
expert = True)
view = client.service[0][item.message] (sid, view_params)
show_view(view)
except:
pass
@ -352,7 +456,7 @@ def get_message(client, item, sid, pid):
endGruop(item)
return 1
if case('briefParams'):
callView(item, sid)
callView(client, item, sid)
if case(): # default, could also just omit condition or 'if True'
return 1
@ -418,8 +522,8 @@ def get_Progress(client, sid, pid, id):
#def cout(string):
# sys.stdout.write(string)
# sys.stdout.flush()
#
#for perc in xrange(101) :
#
#for perc in xrange(101):
# cout ('\r' + str(perc / 1.0).rjust(5) + '% ')
# time.sleep(.2)
@ -470,8 +574,8 @@ def get_Table(client, sid, pid, item):
def send_Message(client, sid, pid, item):
""" send answer to the question """
answer = raw_input (item.message)
result = client.service.send_message(sid, pid, answer)
show_result(result)
client.service.send_message(sid, pid, answer)
# show_result(result)
def send_Password(client, sid, pid, item):
""" send password """

@ -15,27 +15,12 @@
# limitations under the License.
import argparse, sys
from suds import MethodNotFound
from function import create_obj, listToArray, listToArrayArray
from function import listToArray, listToArrayArray, _create_obj, \
get_view_params, print_brief
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('calculate_console',sys.modules[__name__])
import urllib2
def _create_obj(client, method):
try:
view_params = create_obj(client, method)
except MethodNotFound:
print _('Method not found: ') + method
sys.exit(1)
return view_params
def get_view_params(client, method, step = None, expert = None, brief = None):
view_params = _create_obj(client, method)
view_params.step = step
view_params.expert = expert
view_params.brief = brief
return view_params
def get_view(client, method, sid, view_params):
try:
view = client.service[0][method + '_view'](client.sid, view_params)
@ -49,8 +34,8 @@ def get_method_argparser(client, args):
view_params = get_view_params(client, method + '_view', step = None, \
expert = True)
progr = 'cl-console --method '+method
view = get_view(client, method, client.sid, view_params)
progr = 'cl-console --method '+method
parser = argparse.ArgumentParser(prog=progr, add_help=False)
for Group in view.groups.GroupField:
@ -116,16 +101,35 @@ def call_method(client, args):
param_object = _create_obj(client, method)
args = method_parser.parse_known_args()[0]
param_object = collect_object(client, param_object, view, args)
# print param_object
param_object, steps = collect_object(client, param_object, view, args)
if steps.label and hasattr (param_object, 'CheckOnly'):
param_object['CheckOnly'] = True
method_result = client.service[0][method](client.sid, param_object)
view_params = get_view_params(client, method + '_view', step = None, \
expert = True, brief = True)
view = get_view(client, method, client.sid, view_params)
print_brief(view, steps.label)
while True:
ask = raw_input('\n'+_('Run process? (yes/no): '))
if ask.lower() in ['n', 'no']:
red = '\033[31m * \033[0m'
print red + _('Interrupted by user')
sys.exit(1)
if ask.lower() in ['y', 'yes']:
break
param_object['CheckOnly'] = False
method_result = client.service[0][method](client.sid, param_object)
return method_result
def _getattr(obj, attr):
return getattr(obj, attr) if hasattr(obj, attr) else None
def collect_object(client, param_object, view, args):
steps = None
for Group in view.groups.GroupField:
if not Group.fields:
continue
@ -155,7 +159,10 @@ def collect_object(client, param_object, view, args):
val = _getattr(args, field.name)
param_object[field.name] = collect_table(field, val, client)
return param_object
elif field.element == 'table' and field.type == 'steps':
steps = field
return param_object, steps
# print result_table
def collect_table(field, val_list, client):

@ -74,34 +74,33 @@ def sid_inf(client, sid):
return -3
print "============================"
print '\n' + _(u"Session number - %s") %sid
if s[0][5] == "0":
print _(u"session is active")
else:
print _(u"session is inactive")
print _(u"Session number - %s") %sid
# if s[0][5] == "0":
# print _(u"session is active")
# else:
# print _(u"session is inactive")
print _(u"Certificate number - %s") %s[0][0]
print _(u"Date issue of certificate - %s") %s[0][1]
print "ip - %s" %s[0][2]
print "MAC - %s" %s[0][3]
print _(u"Client type - %s") %s[0][4]
# print _(u"Client type - %s") %s[0][4]
print "============================"
return 0
def client_session_info(client):
""" select session for get information """
sid = raw_input ("SID: ")
try:
sid = int (sid)
except:
print _("Error sid")
sid_inf(client, client.sid)
except Exception, e:
print e
return 1
def session_clean(client):
try:
if sid > 0:
sid_inf(client, sid)
else:
print _("Enter correctly sid!")
except:
print _("Error get data")
return 1
return 0
res = client.service.clear_session_cache(client.sid)
except Exception, e:
print e
if res:
print _('Error clearing session cache')
else:
print _('Session cache is cleared')

@ -1,35 +0,0 @@
#-*- coding: utf-8 -*-
# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from function import get_sid, analysis
# method of applying templates
def client_template(client, command):
sid = get_sid(client.SID_FILE)
try:
args = command.split(' ',1)[1]
except:
args = ''
try:
s = client.service.cl_template(sid, args)
analysis(client, sid, s)
except Exception, e:
if e[0][0] == 403:
print _('Permission denied')
else:
print e
return 1
return 0

@ -2,8 +2,8 @@ msgid ""
msgstr ""
"Project-Id-Version: console_gui_translate\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2012-05-23 11:13+0300\n"
"PO-Revision-Date: 2012-05-23 11:14+0300\n"
"POT-Creation-Date: 2012-05-23 17:35+0300\n"
"PO-Revision-Date: 2012-05-23 17:35+0300\n"
"Last-Translator: Denis <ds@mail.ru>\n"
"Language-Team: \n"
"Language: \n"
@ -20,7 +20,6 @@ msgid "PID not found"
msgstr "Процесс не найден"
#: /var/calculate/mydir/git/calculate-console/console/application/pid_information.py:32
#: /var/calculate/mydir/git/calculate-console/console/application/template.py:31
#: /var/calculate/mydir/git/calculate-console/console/application/cert_func.py:316
msgid "Permission denied"
msgstr "Доступ запрещён"
@ -172,95 +171,111 @@ msgstr "Страна (2 символа): [%s]"
msgid "Clear Cache error! "
msgstr "Ошибка очистки кэша!"
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:237
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:323
msgid "Error"
msgstr "Ошибка"
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:243
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:329
msgid "Warning"
msgstr "Предепреждение"
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:384
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:367
msgid "Method not found: "
msgstr "Метод не найден: "
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:488
msgid "Process not exist or not belong to your session"
msgstr "Процесс не существует или принадлежит не вашей сессии"
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:436
#: /var/calculate/mydir/git/calculate-console/console/application/function.py:540
#, python-format
msgid "Error task by %s"
msgstr "Ошибка задачи на %s"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:59
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:60
msgid "no connection to server!"
msgstr "нет соединения с сервером!"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:135
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:131
msgid "show this help message and exit"
msgstr "просмотр данной справки и выход"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:138
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:134
msgid "call method"
msgstr "вызов метода"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:141
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:137
msgid "language for translate"
msgstr "язык для перевода"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:144
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:140
msgid "port number"
msgstr "номер порта"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:147
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:143
msgid "host destination"
msgstr "хост назначения"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:150
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:146
msgid "post request a signed certificate by server"
msgstr "послать запрос подписания сертификата на сервер"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:153
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:149
msgid "get signed certificate from server"
msgstr "забрать подписанный сертификат с сервера"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:156
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:152
msgid "path to cert and key files"
msgstr "путь к файлам сертификата и ключа"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:159
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:155
msgid "view a list of running processes"
msgstr "просмотр списка запущенных процессов"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:162
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:158
msgid "dump (using with key --list-pid)"
msgstr "дамп (используйте с ключом --list-pid)"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:165
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:161
msgid "view result of process"
msgstr "просмотр результата работы процесса"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:168
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:164
msgid "kill selected process"
msgstr "завершить выбранный процесс"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:171
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:167
msgid "Clear cache session"
msgstr "Очистить кэш сессии"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:170
msgid "View session information"
msgstr "Просмотр информации о сессии"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:173
msgid "update the certificate revocation lists"
msgstr "обновить список отзыва сертификатов"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:289
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:323
#: /var/calculate/mydir/git/calculate-console/console/application/methods_func.py:43
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:298
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:332
#: /var/calculate/mydir/git/calculate-console/console/application/methods_func.py:28
msgid "Failed to connect"
msgstr "Не удалось подключиться"
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:346
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:349
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:351
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:357
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:360
#: /var/calculate/mydir/git/calculate-console/console/application/cl_client.py:362
#, python-format
msgid "Exception: %s"
msgstr "Исключение: %s"
#: /var/calculate/mydir/git/calculate-console/console/application/methods_func.py:28
msgid "Method not found: "
msgstr "Метод не найден: "
#: /var/calculate/mydir/git/calculate-console/console/application/methods_func.py:114
msgid "Run process? yes/[no]: "
msgstr "Запустить процесс? yes/[no]: "
#: /var/calculate/mydir/git/calculate-console/console/application/methods_func.py:116
msgid "Interrupted by user"
msgstr "Прервано пользователем"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:33
msgid " New Session"
@ -308,14 +323,6 @@ msgstr "Данная сессия не зарегистрирована на с
msgid "Session number - %s"
msgstr "Серийный номер = %s"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:79
msgid "session is active"
msgstr "сессия активна"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:81
msgid "session is inactive"
msgstr "сессия неактивна"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:82
#, python-format
msgid "Certificate number - %s"
@ -326,22 +333,13 @@ msgstr "Номер сертификата - %s"
msgid "Date issue of certificate - %s"
msgstr "Дата подписания сертификата - %s"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:86
#, python-format
msgid "Client type - %s"
msgstr "Тип клиента - %s"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:96
msgid "Error sid"
msgstr "Ошибка sid (идентификатора сессии)"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:102
msgid "Enter correctly sid!"
msgstr "Введите корректный идентификатор сессии!"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:104
msgid "Error get data"
msgstr "Ошибка при получении данных"
msgid "Error clearing session cache"
msgstr "Ошибка очистки кэша сессии"
#: /var/calculate/mydir/git/calculate-console/console/application/sid_func.py:106
msgid "Session cache is cleared"
msgstr "Кэш сессии очищен"
#: /var/calculate/mydir/git/calculate-console/console/application/cert_func.py:38
msgid "Certificate not found in Server Database!"
@ -581,6 +579,24 @@ msgstr ""
"\n"
"Внимание! %s пытается подменить сертификат!\n"
#~ msgid "session is active"
#~ msgstr "сессия активна"
#~ msgid "session is inactive"
#~ msgstr "сессия неактивна"
#~ msgid "Client type - %s"
#~ msgstr "Тип клиента - %s"
#~ msgid "Error sid"
#~ msgstr "Ошибка sid (идентификатора сессии)"
#~ msgid "Enter correctly sid!"
#~ msgstr "Введите корректный идентификатор сессии!"
#~ msgid "Error get data"
#~ msgstr "Ошибка при получении данных"
#~ msgid "PID for kill:"
#~ msgstr "Процесс для завершения: "

Loading…
Cancel
Save