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-console/console/application/cl_client.py

379 lines
13 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, sys
import re, threading
from function import create_obj, get_sid, analysis, get_entire_frame, clear
from pid_information import client_list_methods, client_list_pid
from cert_func import client_post_auth, client_post_request, client_get_cert, \
client_post_cert
from cert_verify import get_CRL, VerifyError
from sid_func import client_del_sid
from calculate.lib.datavars import DataVars
from calculate.core.datavars import DataVarsCore
from calculate.core.client.client_class import HTTPSClientCertTransport
t = time
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(
'--method', type=str, dest='method',
help=_('call method'))
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(
'--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, dest='path_to_cert',
help=_('path to cert and key file'))
return parser.parse_args()
def https_server(client, signaling, 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:
print
sys.exit(1)
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 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 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)
logging.getLogger('suds.umx.typed').setLevel(logging.ERROR)
clVars = DataVars()
clVars.flIniFile()
clVarsCore = DataVarsCore()
clVarsCore.importCore()
clVarsCore.flIniFile()
homePath = clVarsCore.Get('ur_home_path')
print _('path to cert and key file')
args = parse()
# translate
if args.lang:
print 'code not found!!!!'
port = args.port
host = args.host
path_to_cert = args.path_to_cert
if not path_to_cert:
path_to_cert = clVarsCore.Get('cl_client_cert_dir')
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(1)
try:
import glob
all_cert_list = glob.glob(os.path.join(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'
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:
print '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)
client.port = port
https_server(client, signaling, url)
#----------------------------------------------------
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()