You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-3-core/core/client/cl_client.py

481 lines
15 KiB

#!/usr/bin/python
#-*- 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 suds import WebFault
from suds.transport import TransportError
from calculate.core.client.client_class import Client_suds
import traceback as tb
import time, logging
import os
import re, threading
from calculate.core.client.function import *
from calculate.core.client.pid_information import *
from calculate.core.client.cert_func import *
from calculate.core.client.cert_verify import get_CRL
from calculate.core.client.sid_func import *
from calculate.lib.datavars import DataVars
from calculate.core.datavars import DataVarsCore
from calculate.core.client.client_class import HTTPSClientCertTransport
t = time
help_ = '''
useradd, cl-unix-useradd - add unix user
template, cl_template - overlay templates
halt, server_shutdown - shutdown server
run, server_start - start server
---- process methods ----
lsp, list-pid - listing all pids for this session
pi, pid-info - get information about select pid (0 for all)
kill, pid-kill - kill select pid
---- sessions methods ----
lss, list-session - listing all sessions in server
si, session-info - get information about select session (sid)
lsr, list-method - listing all accessible methods
q, quit - exit
h, help - display this help and exit
v, version - output version information and exit'''
def client_login (client):
login = raw_input ("Login: ")
password = raw_input ("password: ")
try:
name_re = re.compile("[^a-zA-Z_]")
if name_re.findall(login):
print _("input error")
return 2
print client.service.cl_login(login = login, password = password)
except (Exception) , e:
sys.stdout.flush()
for i in e.message:
sys.stdout.write(str(i) + ' ')
def client_useradd (client):
user_name = raw_input ("User name: ")
try:
name_re = re.compile("[^a-zA-Z_]")
if name_re.findall(user_name):
print _("input error")
return 2
print client.service.cl_unix_useradd(param = user_name)
except:
print _("create error")
def client_userdel (client):
user_name = raw_input ("User name: ")
try:
name_re = re.compile("[^a-zA-Z_]")
if name_re.findall(user_name):
print _("input error")
return 2
print client.service.cl_unix_userdel(param = user_name)
except:
print _("deleted error")
def client_shut (client):
try:
temp = client.service.server_shutdown()
if ( temp == 1):
print _("Server shutting down...")
except:
print _("Connection error! ")
return 1
def client_signal(client):
Vars = DataVarsCore()
Vars.importCore()
Vars.flIniFile()
try:
client_active = Vars.Get('cl_core_client_active_period')
except:
client_active = 15
while True:
if os.path.exists(client.SID_FILE) :
fi = open(client.SID_FILE, 'r')
temp = fi.read()
fi.close()
sid = int(temp)
else:
sid = 0
try:
reply = client.service.active_client(sid)
except:
print _('no connection to server!')
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 = []
for param in list_param:
if not param.startswith('_'):
param_list.append(param)
for Group in view.groups.GroupField:
print "GroupField name : ", Group.name
for field in Group.fields.Field:
if field.element == 'input':
if field.type == 'str':
cr[field.name] = raw_input(field.label)
if field.type == 'int':
while True:
try:
var = raw_input(field.label)
cr[field.name] = int (var)
break
except (TypeError, ValueError):
print 'Это не целое число'
elif field.element == 'bool':
while 1:
bool_var = raw_input(field.label+' (y/n): ')
if bool_var.lower() in ['y','yes']:
cr[field.name] = True
break
if bool_var.lower() in ['n','no']:
cr[field.name] = False
break
print _('Enter "Yes" or "No"!')
elif field.element == 'check':
choice = field.choice[0]
while 1:
print _('Select one: ')
for i in range(1,len(choice)+1):
print choice[i-1], ' - %d' %i
try:
bool_var = int (raw_input(field.label))
if bool_var > 0:
cr[field.name] = choice[bool_var - 1]
print 'your choice %s' %cr[field.name]
break
except:
pass
#field.choice
#print field.help
sid = get_sid(client.SID_FILE)
s = client.service[0][method_name](sid, cr)
analysis(client, sid, s)
import argparse
def parse():
parser = argparse.ArgumentParser()
parser.add_argument(
'-l', '--lang', type=str, dest='lang',
help=_('language for translate'))
parser.add_argument(
'-p', '--port', type=int, default = '8888', dest='port',
help=_('port number'))
#parser.add_argument(
#'--script', type=str, default = '/Server', dest='script_name',
#help='name script in server')
parser.add_argument(
'--host', type=str, default = 'localhost', dest='host',
help=_('host destination'))
parser.add_argument(
'--gen-cert-by', type=str, dest='by_host',
help=_('post request a signed certificate by server'))
parser.add_argument(
'--get-cert-from', type=str, dest='from_host',
help=_('get signed certificate from server'))
parser.add_argument(
'--cert-path', type=str,
default = '~/.calculate/client_cert/',
nargs ='?', dest='path_to_cert',
help=_('path to cert and key file'))
return parser.parse_args()
def https_server(client, signaling):
global url
client_post_auth(client)
signaling.start()
client_list_methods(client)
get_entire_frame(client)
#create_obj(client, "install_system")
while True:
try:
command = raw_input ('\n'+_("Command: "))
except KeyboardInterrupt, e:
print
sys.exit()
if (command == 'halt' or command == 'server_shutdown'):
client_shut(client)
#elif (command == 'say_hello' or command == 'say'):
#client_say_hello(client)
#elif (command == 'say_hello2' or command == 'say2'):
#client_say_hello2(client)
elif (command == 'server_start' or command == 'run'):
if os.path.exists(client.CERT_KEY) and\
os.path.exists(client.CERT_FILE) :
client = Client_suds(url,\
transport = HTTPSClientCertTransport(client.CERT_KEY,\
client.CERT_FILE))
#If the certificate file misses
else:
CERT_FILE = None
CERT_KEY = None
client = Client_suds(url,\
transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE))
elif (command == 'login' or command == 'cl-login'):
client_login(client)
elif (command == 'useradd' or command == 'cl-unix-useradd'):
client_useradd(client)
elif (command == 'sid-del' or command == 'del-sid'):
client_del_sid(client)
elif (command == 'lsp' or command == 'list-pid'):
client_list_pid(client)
elif (command == 'ins' or command == 'install'):
client_install(client)
elif (command == 'lsr' or command == 'list-method'\
or command == 'list-right'):
client_list_methods(client)
elif (command == 'lss' or command == 'list-session'\
or command == 'sls'):
client_list_sessions(client)
elif (command == 'pi' or command == 'pid-info'):
client_pid_info(client)
elif (command == 'si' or command == 'session-info'):
client_session_info(client)
elif (command == 'kill' or command == 'pid-kill'):
client_pid_kill(client)
elif (command == 'userdel' or command == 'cl-unix-userdel'):
client_userdel(client)
elif (command == 'vcr' or command == 'view-cert-right'):
client_view_cert_right(client)
elif command.split(' ',1)[0] in ['t', 'template', 'cl-template']:
#client_template(client, command)
test(client, 'cl_template')
elif command.lower() in ['test']:
test(client)
elif (command == 'help' or command == 'h'):
print help_
elif command in ['q', 'quit', 'exit']:
print _("Closing") + "\n"
signaling._Thread__stop()
time.sleep(0.3)
num = client_list_pid(client)
if num:
print _('at closing session, '
'data %d processes will be deleted!') %num
c = raw_input (_("Close your session y/[n]: "))
if c in ['y', 'yes', 'Y', 'YES']:
client_del_sid(client)
#signaling.killed = True
# client_shut(client)
return 0
else:
print _("Input Error")
#t.sleep(1)
#def http_server(client):
#pass
def translate(lang = None):
import locale
import gettext
if lang:
try:
language = gettext.translation ('cl_core', languages = [lang])
language.install()
return 0
except:
print _("lang %s not supported!") %str(lang)
try:
current_locale, encoding = locale.getdefaultlocale()
language = gettext.translation ('cl_core', \
languages = [current_locale] )
language.install()
print "set translate", current_locale
return 0
except:
language = gettext.translation ('cl_core', languages = ['en'] )
language.install()
return 0
def main():
clear()
#password = getpass(prompt="Password: ")
logging.basicConfig(level=logging.FATAL)
logging.getLogger('suds.client').setLevel(logging.FATAL)
logging.getLogger('suds.transport').setLevel(logging.FATAL)
logging.getLogger('suds.transport.http').setLevel(logging.FATAL)
#fmt = '%(asctime)s [%(levelname)s] %(funcName)s() @%(filename)s:%(lineno)d\n%(message)s\n'
#logging.basicConfig(level=logging.INFO, format=fmt)
logging.getLogger('suds.umx.typed').setLevel(logging.ERROR)
clVars = DataVars()
clVars.flIniFile()
homePath = clVars.Get('ur_home_path')
print _('path to cert and key file')
args = parse()
# translate
if args.lang:
translate(args.lang)
port = args.port
host = args.host
path_to_cert = args.path_to_cert
path_to_cert = path_to_cert.replace("~",homePath)
getCRL = threading.Thread(target=get_CRL, args = (path_to_cert, ))
getCRL.start()
if args.by_host:
client_post_request (path_to_cert, args.by_host)
return 0
if args.from_host:
client_get_cert (path_to_cert, args)
return 0
url = "https://%s:%d/?wsdl" %(host, port)
print "url = %s" %url
#try:
client = Client_suds(url, \
transport = HTTPSClientCertTransport(None,None, path_to_cert))
server_host_name = client.service.get_server_host_name()
del (client)
#except Exception, e:
#print 'get host name error', e
##print _("Connection Error. Failure verification server.")
#sys.exit()
try:
import glob
all_cert_list = glob.glob(path_to_cert + '*.crt')
fit_cert_list = []
for client_cert_path in all_cert_list:
client_cert = client_cert_path.replace(path_to_cert, '')
client_cert_name = client_cert.replace('.crt', '')
if server_host_name.endswith(client_cert_name):
fit_cert_list.append(client_cert_name)
fit_cert_list.sort(key = len)
Connect_Error = 1
for i in range (0, len(fit_cert_list)):
#print 'fit_cert_list = ',fit_cert_list
cert_name = fit_cert_list.pop()
CERT_FILE = path_to_cert + cert_name + '.crt'
CERT_KEY = path_to_cert + cert_name + '.key'
print "cert_name = ",cert_name
try:
client = Client_suds(url,\
transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE,\
path_to_cert))
client.set_parameters (path_to_cert, CERT_FILE, CERT_KEY)
client_post_cert(client)
Connect_Error = 0
except VerifyError, e:
print e.value
Connect_Error = 1
except Exception, e:
print e
Connect_Error = 1
#sys.exit()
if Connect_Error == 0:
break
#If the certificate file misses
if Connect_Error:
CERT_FILE = None
CERT_KEY = None
client = Client_suds(url,\
transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE,\
path_to_cert))
client.set_parameters (path_to_cert, CERT_FILE, CERT_KEY)
Vars = DataVarsCore()
Vars.importCore()
Vars.flIniFile()
try:
client.frame_period = Vars.Get('cl_core_get_frame_period')
except:
client.frame_period = 2
signaling = threading.Thread(target=client_signal, args = (client, ))
signaling.setDaemon(True)
https_server(client, signaling)
#----------------------------------------------------
except WebFault, f:
print _("Exception: %s") %f
print f.fault
except TransportError, te:
print _("Exception: %s") %te
except Exception, e:
print _("Exception: %s") %e
tb.print_exc()