commit
3561ef23b4
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
@ -0,0 +1,295 @@
|
||||
#-*- 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.
|
||||
|
||||
import os, re, glob, sys
|
||||
import OpenSSL
|
||||
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('calculate_console',sys.modules[__name__])
|
||||
|
||||
class VerifyError(Exception):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
def __str__(self):
|
||||
return repr(self.value)
|
||||
|
||||
|
||||
# check recall of server certificate
|
||||
def verify(server_cert, crl_path, flag):
|
||||
|
||||
certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, server_cert)
|
||||
serverSerial = certobj.get_serial_number()
|
||||
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
CN, L = None, None
|
||||
for i in Issuer:
|
||||
if i[0] == 'CN':
|
||||
CN = i[1]
|
||||
elif i[0] == 'L':
|
||||
L = i[1]
|
||||
|
||||
if CN and len(CN) > 2:
|
||||
crl_file = crl_path + CN
|
||||
elif L:
|
||||
try:
|
||||
host = L.split(':')[0]
|
||||
except:
|
||||
if not flag:
|
||||
print _("field CN and L in CA certificate are incorrect!")
|
||||
return 0
|
||||
crl_file = crl_path + host
|
||||
else:
|
||||
if not flag:
|
||||
print _( "field CN and L in CA certificate are incorrect!")
|
||||
return 0
|
||||
|
||||
if not os.path.exists(crl_file):
|
||||
if not flag:
|
||||
pass
|
||||
# print _("This certificate can not be verified in the CRL.")
|
||||
return 0
|
||||
|
||||
with open(crl_file, 'r') as _crl_file:
|
||||
crl = "".join(_crl_file.readlines())
|
||||
|
||||
if crl == '':
|
||||
return 0
|
||||
crl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, crl)
|
||||
|
||||
|
||||
revoked_objects = crl_object.get_revoked()
|
||||
|
||||
for rvk in revoked_objects:
|
||||
if serverSerial == int(rvk.get_serial(), 16):
|
||||
print _("This certificate is revoked!")
|
||||
print _("Serial")+ ': %s\n' %rvk.get_serial() + _("Revoke date") + \
|
||||
': %s' %rvk.get_rev_date()
|
||||
|
||||
raise VerifyError('CRL Exception')
|
||||
return 0
|
||||
|
||||
|
||||
def get_CRL(path_to_cert):
|
||||
print 'update CRL'
|
||||
""" get new CRL (Certificate Revocation List) from all CA """
|
||||
# local CRL
|
||||
CRL_path = os.path.join(path_to_cert, 'ca/crl/')
|
||||
if not os.path.exists(CRL_path):
|
||||
if not os.path.exists(os.path.join(path_to_cert, 'ca')):
|
||||
if not os.path.exists(path_to_cert):
|
||||
try:
|
||||
os.makedirs(path_to_cert)
|
||||
except OSError:
|
||||
print _("error creating directory %s") %path_to_cert
|
||||
sys.exit()
|
||||
try:
|
||||
os.makedirs(os.path.join(path_to_cert, 'ca'))
|
||||
except OSError:
|
||||
print _("error creating directory %s") \
|
||||
%(os.path.join(path_to_cert, 'ca'))
|
||||
sys.exit()
|
||||
os.makedirs(CRL_path)
|
||||
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
# user and system ca and root certificates
|
||||
user_root_cert = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_root_cert = user_root_cert.replace("~",homePath)
|
||||
|
||||
glob_root_cert = clVars.Get('cl_glob_root_cert')
|
||||
|
||||
if os.path.exists(user_root_cert):
|
||||
user_ca_certs = open(user_root_cert, 'r').read()
|
||||
else: user_ca_certs = ''
|
||||
if os.path.exists(glob_root_cert):
|
||||
glob_ca_certs = open(glob_root_cert, 'r').read()
|
||||
else: glob_ca_certs = ''
|
||||
|
||||
# get certificates list fron text
|
||||
p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
|
||||
user_ca_certs_list = p.findall(user_ca_certs)
|
||||
glob_ca_certs_list = p.findall(glob_ca_certs)
|
||||
|
||||
# association in one list
|
||||
all_ca_certs_list = user_ca_certs_list + glob_ca_certs_list
|
||||
for ca in all_ca_certs_list:
|
||||
certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, ca)
|
||||
# get url from certificates
|
||||
url = None
|
||||
CN = None
|
||||
Subject = certobj.get_subject().get_components()
|
||||
for subj in Subject:
|
||||
if subj[0] == 'L':
|
||||
url = "https://" + subj[1] +"/?wsdl"
|
||||
if subj[0] == 'CN':
|
||||
CN = subj[1]
|
||||
|
||||
if url:
|
||||
from client_class import Client_suds
|
||||
from client_class import HTTPSClientCertTransport
|
||||
# connect to ca server (url get from certificates)
|
||||
try:
|
||||
client = Client_suds(url,\
|
||||
transport = HTTPSClientCertTransport(None, None, \
|
||||
path_to_cert))
|
||||
|
||||
client.set_parameters (path_to_cert, None, None)
|
||||
new_crl = client.service.get_crl()
|
||||
except VerifyError, e:
|
||||
print e.value
|
||||
#rm_ca_from_trusted(ca)
|
||||
sys.exit()
|
||||
except:
|
||||
pass
|
||||
if 'new_crl' in locals():
|
||||
if new_crl:
|
||||
if CN and len(CN) > 2:
|
||||
CRL_file = CRL_path + CN
|
||||
else:
|
||||
host = subj[1].split(':')[0]
|
||||
CRL_file = CRL_path + host
|
||||
if new_crl == ' ':
|
||||
open(CRL_file, 'w')
|
||||
#if os.path.exists(CRL_file):
|
||||
#os.unlink(CRL_file)
|
||||
continue
|
||||
if os.path.exists(CRL_file):
|
||||
if open(CRL_file, 'r').read() == new_crl:
|
||||
continue
|
||||
|
||||
fd = open(CRL_file, 'w')
|
||||
fd.write(new_crl)
|
||||
fd.close()
|
||||
print _("CRL add")
|
||||
find_ca_in_crl (CRL_path, all_ca_certs_list)
|
||||
|
||||
def find_ca_in_crl (CRL_path, all_ca_certs_list):
|
||||
CRL_name_list = glob.glob(CRL_path + '*')
|
||||
for ca in all_ca_certs_list:
|
||||
certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, ca)
|
||||
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
for item in Issuer:
|
||||
if item[0] == 'CN':
|
||||
CN = item[1]
|
||||
serverSerial = certobj.get_serial_number()
|
||||
CRL = CRL_path + CN
|
||||
if not os.path.exists(CRL):
|
||||
continue
|
||||
|
||||
with open(CRL, 'r') as _crl_file:
|
||||
crl = "".join(_crl_file.readlines())
|
||||
|
||||
try:
|
||||
crl_object = OpenSSL.crypto.load_crl \
|
||||
(OpenSSL.crypto.FILETYPE_PEM, crl)
|
||||
except:
|
||||
continue
|
||||
revoked_objects = crl_object.get_revoked()
|
||||
|
||||
for rvk in revoked_objects:
|
||||
if serverSerial == int(rvk.get_serial(), 16):
|
||||
rm_ca_from_trusted(ca)
|
||||
|
||||
def rm_ca_from_trusted(ca_cert):
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
|
||||
user_ca_dir = clVars.Get('cl_client_cert_dir')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_ca_dir = user_ca_dir.replace("~",homePath)
|
||||
user_ca_dir = os.path.join(user_ca_dir, 'ca')
|
||||
user_ca_list = os.path.join(user_ca_dir, 'cert_list')
|
||||
user_ca_db = clVars.Get('cl_user_root_cert')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
user_ca_db = user_ca_db.replace("~",homePath)
|
||||
|
||||
system_ca_dir = clVars.Get('cl_core_cert_path')
|
||||
system_ca_list = os.path.join(system_ca_dir, 'cert_list')
|
||||
system_ca_db = clVars.Get('cl_glob_root_cert')
|
||||
|
||||
import hashlib
|
||||
md5 = hashlib.md5()
|
||||
md5.update(ca_cert)
|
||||
md5sum = md5.hexdigest()
|
||||
|
||||
# search ca certificate in user ca list
|
||||
with open(user_ca_list) as fd:
|
||||
t = fd.read()
|
||||
# See each line
|
||||
for line in t.splitlines():
|
||||
newfile = ''
|
||||
# and each word in line
|
||||
words = line.split()
|
||||
if words[0] == md5sum:
|
||||
filename = os.path.join(user_ca_dir, words[1])
|
||||
if ca_cert == open(filename, 'r').read():
|
||||
os.unlink(filename)
|
||||
else:
|
||||
newfile += (line + '\n')
|
||||
else:
|
||||
newfile += (line + '\n')
|
||||
|
||||
fd.close()
|
||||
fn = open(user_ca_list, 'w')
|
||||
fn.write(newfile)
|
||||
fn.close()
|
||||
|
||||
p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
|
||||
|
||||
# open, write and split user ca certificates
|
||||
user_ca_certs = open(user_ca_db, 'r').read()
|
||||
user_ca_certs_list = p.findall(user_ca_certs)
|
||||
|
||||
if ca_cert in user_ca_certs_list:
|
||||
new_user_ca_certs = []
|
||||
for cert in user_ca_certs_list:
|
||||
if ca_cert != cert:
|
||||
new_user_ca_certs.append(cert)
|
||||
else:
|
||||
print _("CA certificate delete from user trusted certificate")
|
||||
|
||||
fd = open(user_ca_db, 'w')
|
||||
for cert in new_user_ca_certs:
|
||||
fd.write(cert)
|
||||
fd.close()
|
||||
|
||||
if not os.path.exists(system_ca_db):
|
||||
open(system_ca_db, 'w')
|
||||
|
||||
system_ca_certs = open(system_ca_db, 'r').read()
|
||||
system_ca_certs_list = p.findall(system_ca_certs)
|
||||
|
||||
if ca_cert in system_ca_certs_list:
|
||||
new_system_ca_certs = []
|
||||
for cert in system_ca_certs_list:
|
||||
if ca_cert != cert:
|
||||
new_system_ca_certs.append(cert)
|
||||
else:
|
||||
print _("CA certificate delete from system trusted certificate")
|
||||
|
||||
fd = open(system_ca_db, 'w')
|
||||
for cert in new_system_ca_certs:
|
||||
fd.write(cert)
|
||||
fd.close()
|
||||
return 0
|
@ -0,0 +1,421 @@
|
||||
#!/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 sudsds import WebFault
|
||||
from sudsds.transport import TransportError
|
||||
|
||||
from client_class import Client_suds
|
||||
import traceback as tb
|
||||
import time, logging
|
||||
import os, sys
|
||||
import threading, urllib2
|
||||
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, get_password_from_daemon, clear_password
|
||||
from sid_func import session_clean, client_session_info, client_session_list
|
||||
from cert_verify import get_CRL, VerifyError
|
||||
|
||||
import argparse, datetime
|
||||
import M2Crypto, OpenSSL
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
|
||||
from client_class import HTTPSClientCertTransport
|
||||
from methods_func import call_method, get_method_argparser
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
from calculate.lib.utils.files import makeDirectory
|
||||
setLocalTranslate('calculate_console',sys.modules[__name__])
|
||||
|
||||
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:
|
||||
client.service.active_client(sid)
|
||||
except:
|
||||
print _('no connection to server!')
|
||||
sys.exit()
|
||||
time.sleep(float(client_active))
|
||||
|
||||
def test(client, com=None):
|
||||
if not com:
|
||||
method_name = 'test'
|
||||
else:
|
||||
method_name = com
|
||||
view = client.service[0][method_name + '_view']()
|
||||
|
||||
cr = create_obj(client, method_name)
|
||||
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)
|
||||
print s
|
||||
|
||||
def parse():
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
parser.add_argument(
|
||||
'-h', '--help', action='store_true', default=False,
|
||||
dest='help', help=_("show this help message and exit"))
|
||||
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', metavar = 'HOST',
|
||||
help=_('post request a signed certificate by server'))
|
||||
parser.add_argument(
|
||||
'--get-cert-from', type=str, dest='from_host', metavar = 'HOST',
|
||||
help=_('get signed certificate from server'))
|
||||
parser.add_argument(
|
||||
'--cert-path', type=str, dest='path_to_cert', metavar = 'PATH',
|
||||
help=_('path to cert and key files'))
|
||||
parser.add_argument(
|
||||
'--list-pid', action='store_true', default=False,
|
||||
dest='list_pid', help=_("view a list of running processes"))
|
||||
parser.add_argument(
|
||||
'-d', '--dump', action='store_true', default=False, dest = 'dump',
|
||||
help=_('dump (using with key --list-pid)'))
|
||||
parser.add_argument(
|
||||
'--pid-result', type=int, metavar = 'PID',
|
||||
dest='pid_res', help=_("view result of process"))
|
||||
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(
|
||||
'--session-num-info', type=int, metavar = 'SID',
|
||||
dest='session_num_info', help=_("view information about session "
|
||||
"with sid = SID"))
|
||||
parser.add_argument(
|
||||
'--session-list', action='store_true', default=False,
|
||||
dest='session_list', help=_("view list active session on server"))
|
||||
parser.add_argument(
|
||||
'--update-crl', action='store_true', default=False,
|
||||
dest='update_crl', help=_("update the certificate revocation lists"))
|
||||
parser.add_argument(
|
||||
'--stop-consoled', action='store_true', default=False,
|
||||
dest='stop_consoled', help=_("stop cl-consoled"))
|
||||
return parser
|
||||
|
||||
def https_server(client, args, unknown_args, url, clVarsCore):
|
||||
client_post_auth(client)
|
||||
|
||||
if args.stop_consoled:
|
||||
os.system('cl-consoled --stop')
|
||||
return 0
|
||||
|
||||
if args.session_clean:
|
||||
session_clean(client)
|
||||
|
||||
if args.session_info or args.session_num_info:
|
||||
client_session_info(client, args.session_num_info)
|
||||
|
||||
if args.session_list:
|
||||
client_session_list(client)
|
||||
|
||||
if args.list_pid:
|
||||
if args.dump:
|
||||
from pid_information import client_pid_info
|
||||
client_pid_info(client)
|
||||
else:
|
||||
from pid_information import client_list_pid
|
||||
client_list_pid(client)
|
||||
|
||||
if args.pid_res:
|
||||
get_entire_frame(client, args.pid_res)
|
||||
return 0
|
||||
|
||||
if args.pid_kill:
|
||||
from pid_information import client_pid_kill
|
||||
return client_pid_kill(client, args.pid_kill)
|
||||
|
||||
if not args.method:
|
||||
client_list_methods(client)
|
||||
return 1
|
||||
|
||||
elif args.method and args.help:
|
||||
# now = datetime.datetime.now()
|
||||
# print '6 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
method_parser, view = get_method_argparser(client, args)
|
||||
method_parser.print_help()
|
||||
# now = datetime.datetime.now()
|
||||
# print '7 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
|
||||
else:
|
||||
try:
|
||||
client.frame_period = clVarsCore.Get('cl_core_get_frame_period')
|
||||
except:
|
||||
client.frame_period = 2
|
||||
method_result = call_method(client, args)
|
||||
if method_result:
|
||||
try:
|
||||
analysis(client, client.sid, method_result)
|
||||
except urllib2.URLError, e:
|
||||
print e
|
||||
|
||||
try:
|
||||
mess = method_result[0][0]
|
||||
pid = int(mess.message)
|
||||
except:
|
||||
return 1
|
||||
|
||||
client.service.clear_pid_cache(client.sid, pid)
|
||||
client.service.clear_method_cache(client.sid, args.method)
|
||||
return 0
|
||||
|
||||
def main():
|
||||
# now = datetime.datetime.now()
|
||||
# print '1 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
parser = parse()
|
||||
args, unknown_args = parser.parse_known_args()
|
||||
|
||||
if not args.method and args.help:
|
||||
parser.print_help()
|
||||
# now = datetime.datetime.now()
|
||||
# print '1/2 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
return 0
|
||||
|
||||
logging.basicConfig(level=logging.FATAL)
|
||||
logging.getLogger('sudsds.client').setLevel(logging.FATAL)
|
||||
logging.getLogger('sudsds.transport').setLevel(logging.FATAL)
|
||||
logging.getLogger('sudsds.transport.http').setLevel(logging.FATAL)
|
||||
logging.getLogger('sudsds.umx.typed').setLevel(logging.ERROR)
|
||||
|
||||
clVarsCore = DataVarsCore()
|
||||
clVarsCore.importCore()
|
||||
clVarsCore.flIniFile()
|
||||
|
||||
homePath = clVarsCore.Get('ur_home_path')
|
||||
|
||||
# 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)
|
||||
|
||||
for dirs in ['', 'ca', 'trusted']:
|
||||
dir_path = os.path.join(path_to_cert, dirs)
|
||||
if not os.path.isdir(dir_path):
|
||||
if not makeDirectory(dir_path):
|
||||
print _("cannot create directory %s") %dir_path
|
||||
return 1
|
||||
|
||||
if args.update_crl:
|
||||
getCRL = threading.Thread(target=get_CRL, args = (path_to_cert, ))
|
||||
getCRL.start()
|
||||
getCRL.join()
|
||||
print 'GRL updated'
|
||||
return 0
|
||||
|
||||
if args.by_host:
|
||||
client_post_request (path_to_cert, args)
|
||||
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
|
||||
|
||||
clear()
|
||||
try:
|
||||
# now = datetime.datetime.now()
|
||||
# print '2 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
client = Client_suds(url, \
|
||||
transport = HTTPSClientCertTransport(None,None, path_to_cert))
|
||||
# now = datetime.datetime.now()
|
||||
# print '2/1 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
server_host_name = client.service.get_server_host_name()
|
||||
# print server_host_name
|
||||
# now = datetime.datetime.now()
|
||||
# print '2/2 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
del (client)
|
||||
except urllib2.URLError, e:
|
||||
print _('Failed to connect')+':', e
|
||||
sys.exit(1)
|
||||
# server_host_name = 'dspiridonov.local.calculate.ru'
|
||||
|
||||
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
|
||||
crypto_Error = 0
|
||||
# now = datetime.datetime.now()
|
||||
# print '3 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
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'
|
||||
|
||||
bio = M2Crypto.BIO.openfile(CERT_KEY)
|
||||
rsa = M2Crypto.m2.rsa_read_key(bio._ptr(),lambda *unused: None)
|
||||
if not rsa:
|
||||
store_passwd = get_password_from_daemon(host, port)
|
||||
# if not rsa and not 'store_passwd' in locals():
|
||||
# store_passwd = getpass.getpass(_('Password: '))
|
||||
# if not store_passwd:
|
||||
# store_passwd = None
|
||||
if 'store_passwd' in locals():
|
||||
key_passwd = store_passwd
|
||||
else:
|
||||
key_passwd = None
|
||||
try:
|
||||
# print 111111111
|
||||
client = Client_suds(url,\
|
||||
transport = HTTPSClientCertTransport(CERT_KEY, CERT_FILE,\
|
||||
path_to_cert, password=key_passwd))
|
||||
client.set_parameters (path_to_cert, CERT_FILE, CERT_KEY)
|
||||
client_post_cert(client, clVarsCore)
|
||||
Connect_Error = 0
|
||||
except VerifyError, e:
|
||||
# print e.value
|
||||
Connect_Error = 1
|
||||
except OpenSSL.crypto.Error, e:
|
||||
Connect_Error = 1
|
||||
crypto_Error = 1
|
||||
except urllib2.URLError, e:
|
||||
Connect_Error = 1
|
||||
except Exception, e:
|
||||
Connect_Error = 1
|
||||
if Connect_Error == 0:
|
||||
break
|
||||
# now = datetime.datetime.now()
|
||||
# print '4 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
#If the certificate file misses
|
||||
if Connect_Error:
|
||||
if crypto_Error and 'store_passwd' in locals():
|
||||
print _('Password is invalid')
|
||||
# delete password from daemon list
|
||||
clear_password(host, port)
|
||||
return 1
|
||||
if 'e' in locals():
|
||||
print _('Error: '), e
|
||||
return 1
|
||||
# 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)
|
||||
|
||||
client.port = port
|
||||
# now = datetime.datetime.now()
|
||||
# print '5 ===> %ds %dms' %(now.second, now.microsecond)
|
||||
try:
|
||||
return_val = https_server(client, args, unknown_args, url, \
|
||||
clVarsCore)
|
||||
except urllib2.URLError, e:
|
||||
print _('Error: '), e
|
||||
# now = datetime.datetime.now()
|
||||
# print 'END ===> %ds %dms' %(now.second, now.microsecond)
|
||||
return return_val
|
||||
#----------------------------------------------------
|
||||
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()
|
@ -0,0 +1,496 @@
|
||||
#-*- 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.
|
||||
|
||||
import urllib2 as u2
|
||||
import os, sys
|
||||
import socket, ssl
|
||||
import OpenSSL, hashlib, M2Crypto
|
||||
from calculate.core.datavars import DataVarsCore
|
||||
from calculate.lib.datavars import DataVars
|
||||
from sudsds.client import Client
|
||||
from cert_verify import verify, get_CRL
|
||||
from sudsds.transport.http import HttpTransport, SUDSHTTPRedirectHandler, \
|
||||
CheckingHTTPSConnection, CheckingHTTPSHandler, \
|
||||
PYOPENSSL_AVAILABLE, PyOpenSSLSocket
|
||||
from sudsds.transport import Transport
|
||||
from sudsds.properties import Unskin
|
||||
from cookielib import CookieJar, DefaultCookiePolicy
|
||||
from logging import getLogger
|
||||
from calculate.console.datavars import DataVarsConsole
|
||||
#import cert_func.verify
|
||||
log = getLogger(__name__)
|
||||
flag = 0
|
||||
|
||||
class Client_suds(Client):
|
||||
def set_parameters (self, path_to_cert, CERT_FILE, PKEY_FILE):
|
||||
self.path_to_cert = path_to_cert
|
||||
if not CERT_FILE:
|
||||
CERT_FILE = ''
|
||||
self.CERT_FILE = CERT_FILE
|
||||
self.REQ_FILE = path_to_cert + 'client.csr'
|
||||
self.PKEY_FILE = PKEY_FILE
|
||||
self.SID_FILE = path_to_cert + 'sid.int'
|
||||
self.CRL_PATH = path_to_cert + 'ca/crl/'
|
||||
if not os.path.exists(self.CRL_PATH):
|
||||
os.makedirs(self.CRL_PATH)
|
||||
|
||||
class CheckingClientHTTPSConnection(CheckingHTTPSConnection):
|
||||
"""based on httplib.HTTPSConnection code - extended to support
|
||||
server certificate verification and client certificate authorization"""
|
||||
|
||||
def __init__(self, cert_path, host, ca_certs=None,
|
||||
cert_verifier=None, keyobj=None, certobj=None, **kw):
|
||||
"""cert_verifier is a function returning either True or False
|
||||
based on whether the certificate was found to be OK,
|
||||
keyobj and certobj represent internal PyOpenSSL structures holding
|
||||
the key and certificate respectively.
|
||||
"""
|
||||
CheckingHTTPSConnection.__init__(self, host, ca_certs, cert_verifier,
|
||||
keyobj, certobj, **kw)
|
||||
# self.ClientObj = ClientObj
|
||||
self.cert_path = cert_path
|
||||
self.CRL_PATH = os.path.join(cert_path, 'ca/crl/')
|
||||
|
||||
# get filename store cert server
|
||||
def cert_list (self, host, ca_certs, server_cert):
|
||||
if host == '127.0.0.1':
|
||||
host = 'localhost'
|
||||
if not os.path.exists(self.trusted_path):
|
||||
try:
|
||||
os.makedirs(self.trusted_path)
|
||||
except OSError:
|
||||
pass
|
||||
if not os.path.exists(ca_certs):
|
||||
fc = open(ca_certs,"w")
|
||||
fc.close()
|
||||
filename = None
|
||||
try:
|
||||
with open(ca_certs) as fd:
|
||||
t = fd.read()
|
||||
# for each line
|
||||
for line in t.splitlines():
|
||||
# Split string into a words list
|
||||
words = line.split()
|
||||
if len(words) > 1:
|
||||
# if first word...
|
||||
if words[0] == host:
|
||||
filename = words[1]
|
||||
if not filename:
|
||||
return None
|
||||
except:
|
||||
print _("Certificate not found in client")
|
||||
return None
|
||||
try:
|
||||
fd = open(self.trusted_path + filename, 'r')
|
||||
store_cert = fd.read()
|
||||
fd.close()
|
||||
if store_cert == server_cert:
|
||||
return filename
|
||||
except:
|
||||
print _("Error open file"), self.trusted_path, filename
|
||||
return None
|
||||
|
||||
def add_all_ca_cert(self, list_ca_certs):
|
||||
# so root cert be first, ca after
|
||||
clVarsCore = DataVarsCore()
|
||||
clVarsCore.importCore()
|
||||
clVarsCore.flIniFile()
|
||||
|
||||
list_ca_certs.reverse()
|
||||
system_ca_db = clVarsCore.Get('cl_glob_root_cert')
|
||||
|
||||
clVars = DataVars()
|
||||
clVars.flIniFile()
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
cl_client_cert_dir = clVarsCore.Get('cl_client_cert_dir')
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~",homePath)
|
||||
root_cert_md5 = os.path.join(cl_client_cert_dir, "ca/cert_list")
|
||||
|
||||
user_root_cert = clVarsCore.Get('cl_user_root_cert')
|
||||
user_root_cert = user_root_cert.replace("~",homePath)
|
||||
|
||||
for cert in list_ca_certs:
|
||||
if os.path.exists(system_ca_db):
|
||||
if cert in open(system_ca_db, 'r').read():
|
||||
continue
|
||||
|
||||
if os.path.exists(user_root_cert):
|
||||
if cert in open(user_root_cert, 'r').read():
|
||||
continue
|
||||
|
||||
md5 = hashlib.md5()
|
||||
md5.update(cert)
|
||||
md5sum = md5.hexdigest()
|
||||
print "\n================================================="
|
||||
print "md5sum = ", md5sum
|
||||
|
||||
if not os.path.exists(root_cert_md5):
|
||||
fc = open(root_cert_md5,"w")
|
||||
fc.close()
|
||||
|
||||
filename = None
|
||||
with open(root_cert_md5) as fd:
|
||||
t = fd.read()
|
||||
# for each line
|
||||
for line in t.splitlines():
|
||||
# Split string into a words list
|
||||
words = line.split(' ',1)
|
||||
if words[0] == md5sum:
|
||||
filename = words[1]
|
||||
if not filename:
|
||||
certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
for item in Issuer:
|
||||
if item[0] == 'CN':
|
||||
filename = item[1]
|
||||
|
||||
fc = open(root_cert_md5,"a")
|
||||
fc.write('%s %s\n' %(md5sum, filename))
|
||||
fc.close()
|
||||
|
||||
if not filename:
|
||||
print _('Not found field "CN" in certificate!')
|
||||
return 1
|
||||
|
||||
fd = open(os.path.join(cl_client_cert_dir,'ca/',filename),'w')
|
||||
fd.write(cert)
|
||||
fd.close()
|
||||
|
||||
fa = open(user_root_cert, 'a')
|
||||
fa.write(cert)
|
||||
fa.close()
|
||||
print _("filename = "), filename
|
||||
print _("CERTIFICATE ADD")
|
||||
else:
|
||||
print _("file with ca certificates exists")
|
||||
get_CRL(cl_client_cert_dir)
|
||||
|
||||
def add_ca_cert(self, cert, list_ca_certs):
|
||||
url = 'https://%s:%s/?wsdl' %(self.host, self.port)
|
||||
client = Client_suds(url, transport = HTTPSClientCertTransport \
|
||||
(None, None, self.cert_path))
|
||||
cert = client.service.get_ca()
|
||||
if cert == '1':
|
||||
print _('Server certificate is not valid')
|
||||
sys.exit()
|
||||
|
||||
if cert == '2':
|
||||
print _('CA not found on server')
|
||||
sys.exit()
|
||||
|
||||
try:
|
||||
certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
except:
|
||||
print _("Error. Certificate not added to trusted")
|
||||
sys.exit()
|
||||
print '\n', _("Fingerprint = %s") % certobj.digest('SHA1')
|
||||
print _("Serial Number = "), certobj.get_serial_number()
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
print '\n', _("Issuer")
|
||||
for i in Issuer:
|
||||
print "%s : %s" %(i[0], i[1])
|
||||
Subject = certobj.get_subject().get_components()
|
||||
print '\n', _("Subject")
|
||||
for subj in Subject:
|
||||
print "%s : %s" %(subj[0], subj[1])
|
||||
ans = raw_input (_("Add CA certificates to trusted? y/[n]:"))
|
||||
if ans.lower() in ['y','yes']:
|
||||
list_ca_certs.append(cert)
|
||||
self.add_all_ca_cert(list_ca_certs)
|
||||
else:
|
||||
print _("Certificate not added to trusted")
|
||||
|
||||
# add certificate server in trusted
|
||||
def add_server_cert(self, cert):
|
||||
print _("Untrusted Server Certificate!")
|
||||
certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, cert)
|
||||
print '\n' + _("Fingerprint = %s") % certobj.digest('SHA1')
|
||||
print _("Serial Number = "), certobj.get_serial_number()
|
||||
Issuer = certobj.get_issuer().get_components()
|
||||
print '\n' + _("Issuer")
|
||||
for i in Issuer:
|
||||
print "%s : %s" %(i[0], i[1])
|
||||
Subject = certobj.get_subject().get_components()
|
||||
print '\n' + _("Subject")
|
||||
for item in Subject:
|
||||
print "%s : %s" %(item[0], item[1])
|
||||
|
||||
print '\n' + _('Add this Servers certificate to trusted (s) or')
|
||||
print _('Try add CA and ROOT certificates to trusted (c) or')
|
||||
choice = raw_input (_("Quit (q)? s/c/[q]: "))
|
||||
if choice.lower() in ['s', 'c']:
|
||||
#self.sock = ssl.wrap_socket(sock)
|
||||
ca_certs = os.path.join(self.trusted_path, "cert.list")
|
||||
|
||||
if not os.path.exists(ca_certs):
|
||||
fc = open(ca_certs,"w")
|
||||
fc.close()
|
||||
|
||||
if self.host == '127.0.0.1':
|
||||
host = 'localhost'
|
||||
else: host = self.host
|
||||
filename = host
|
||||
fc = open(self.trusted_path + filename,"w")
|
||||
fc.write(cert)
|
||||
fc.close()
|
||||
with open(ca_certs) as fd:
|
||||
t = fd.read()
|
||||
# for each line
|
||||
for line in t.splitlines():
|
||||
# Split string into a words list
|
||||
words = line.split()
|
||||
if len(words) > 1:
|
||||
# if first word...
|
||||
if words[0] == host:
|
||||
return 0
|
||||
# Open file with compliance server certificates and server hostname
|
||||
fcl = open(ca_certs,"a")
|
||||
fcl.write(host + ' ' + filename + '\n')
|
||||
fcl.close()
|
||||
if choice.lower() != 'c':
|
||||
return 3
|
||||
if choice.lower() == 'c':
|
||||
clVars = DataVarsCore()
|
||||
clVars.importCore()
|
||||
clVars.flIniFile()
|
||||
cl_client_cert_dir = clVars.Get('cl_client_cert_dir')
|
||||
homePath = clVars.Get('ur_home_path')
|
||||
cl_client_cert_dir = cl_client_cert_dir.replace("~",homePath)
|
||||
root_cert_dir = os.path.join(cl_client_cert_dir, "ca")
|
||||
|
||||
if not os.path.exists(root_cert_dir):
|
||||
try:
|
||||
os.makedirs(root_cert_dir)
|
||||
except OSError:
|
||||
print _("error creating directory %s") %root_cert_dir
|
||||
sys.exit()
|
||||
|
||||
print '\n' + _("Try add CA and ROOT certificates")
|
||||
self.list_ca_certs = []
|
||||
self.add_ca_cert(cert, self.list_ca_certs)
|
||||
return 3
|
||||
elif not choice.lower() in ['c','s']:
|
||||
return 4
|
||||
|
||||
def connect_trusted_root(self, sock, root_cert, crl_certs):
|
||||
self.ca_path = self.cert_path + "ca/"
|
||||
server_cert = ssl.get_server_certificate(addr = (self.host, self.port))
|
||||
global flag
|
||||
|
||||
if self.cert_file:
|
||||
f = verify(server_cert, crl_certs, flag)
|
||||
if not f:
|
||||
flag = 1
|
||||
elif f == 1:
|
||||
sys.exit()
|
||||
else:
|
||||
import time
|
||||
time.sleep(0.1)
|
||||
|
||||
try:
|
||||
if self.FORCE_SSL_VERSION:
|
||||
add = {'ssl_version': self.FORCE_SSL_VERSION}
|
||||
else:
|
||||
add = {}
|
||||
add['cert_reqs'] = ssl.CERT_REQUIRED
|
||||
# try to use PyOpenSSL by default
|
||||
if PYOPENSSL_AVAILABLE:
|
||||
wrap_class = PyOpenSSLSocket
|
||||
add['keyobj'] = self.keyobj
|
||||
add['certobj'] = self.certobj
|
||||
add['keyfile'] = self.key_file
|
||||
add['certfile'] = self.cert_file
|
||||
else:
|
||||
wrap_class = ssl.SSLSocket
|
||||
self.sock = wrap_class(sock, ca_certs=self.ca_certs, **add)
|
||||
return 0
|
||||
except:
|
||||
return 1
|
||||
|
||||
def connect_trusted_server(self, sock, crl_certs):
|
||||
self.trusted_path = self.cert_path + "trusted/"
|
||||
ca_cert_list = self.trusted_path + "cert.list"
|
||||
server_cert = ssl.get_server_certificate(addr = (self.host, self.port))
|
||||
global flag
|
||||
if self.cert_file:
|
||||
f = verify(server_cert, crl_certs, flag)
|
||||
if not f:
|
||||
flag = 1
|
||||
elif f == 1:
|
||||
sys.exit()
|
||||
#if not hasattr(HTTPSClientCertTransport, 'filename') or \
|
||||
#HTTPSClientCertTransport.filename == None:
|
||||
HTTPSClientCertTransport.filename = self.cert_list \
|
||||
(self.host, ca_cert_list, server_cert)
|
||||
if HTTPSClientCertTransport.filename:
|
||||
try:
|
||||
if self.FORCE_SSL_VERSION:
|
||||
add = {'ssl_version': self.FORCE_SSL_VERSION}
|
||||
else:
|
||||
add = {}
|
||||
add['cert_reqs'] = ssl.CERT_NONE
|
||||
# try to use PyOpenSSL by default
|
||||
if PYOPENSSL_AVAILABLE:
|
||||
wrap_class = PyOpenSSLSocket
|
||||
add['keyobj'] = self.keyobj
|
||||
add['certobj'] = self.certobj
|
||||
add['keyfile'] = self.key_file
|
||||
add['certfile'] = self.cert_file
|
||||
else:
|
||||
wrap_class = ssl.SSLSocket
|
||||
self.sock = wrap_class(sock, ca_certs=self.ca_certs, **add)
|
||||
|
||||
return 0
|
||||
except Exception, e:
|
||||
print (e)
|
||||
HTTPSClientCertTransport.filename = None
|
||||
return 1
|
||||
else:
|
||||
return self.add_server_cert(server_cert)
|
||||
|
||||
def connect(self):
|
||||
sock = socket.create_connection((self.host, self.port), self.timeout)
|
||||
if hasattr(self, '_tunnel_host') and self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
|
||||
self.Vars = DataVarsConsole()
|
||||
self.Vars.importConsole()
|
||||
self.Vars.flIniFile()
|
||||
user_root_cert = self.Vars.Get('cl_user_root_cert')
|
||||
homePath = self.Vars.Get('ur_home_path')
|
||||
user_root_cert = user_root_cert.replace("~",homePath)
|
||||
result_user_root = 1
|
||||
|
||||
while True:
|
||||
if os.path.exists(user_root_cert):
|
||||
result_user_root = self.connect_trusted_root(sock, \
|
||||
user_root_cert, self.CRL_PATH)
|
||||
if result_user_root == 1:
|
||||
glob_root_cert = self.Vars.Get('cl_glob_root_cert')
|
||||
result_root_con = 1
|
||||
if os.path.exists(glob_root_cert):
|
||||
sock = socket.create_connection((self.host, self.port),
|
||||
self.timeout, self.source_address)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
result_root_con = self.connect_trusted_root(sock, \
|
||||
glob_root_cert, self.CRL_PATH)
|
||||
if result_root_con == 1:
|
||||
sock = socket.create_connection((self.host, self.port),
|
||||
self.timeout, self.source_address)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
result_server_con = self.connect_trusted_server \
|
||||
(sock, self.CRL_PATH)
|
||||
if result_server_con in [1,2]:
|
||||
raise Exception (1)
|
||||
elif result_server_con == 3:
|
||||
continue
|
||||
elif result_server_con == 4:
|
||||
raise Exception (_('This server is not trusted'))
|
||||
elif result_root_con == 2:
|
||||
raise Exception (1)
|
||||
elif result_user_root == 2:
|
||||
raise Exception (1)
|
||||
break
|
||||
|
||||
class CheckingClientHTTPSHandler(CheckingHTTPSHandler):
|
||||
def __init__(self, cert_path, ca_certs=None, cert_verifier=None,
|
||||
client_certfile=None, client_keyfile=None,
|
||||
client_keyobj=None, client_certobj=None,
|
||||
*args, **kw):
|
||||
"""cert_verifier is a function returning either True or False
|
||||
based on whether the certificate was found to be OK"""
|
||||
CheckingHTTPSHandler.__init__(self, ca_certs, cert_verifier,
|
||||
client_keyfile, client_certfile,
|
||||
client_keyobj, client_certobj)
|
||||
# self.ClientObj = ClientObj
|
||||
self.cert_path = cert_path
|
||||
|
||||
def https_open(self, req):
|
||||
def open(*args, **kw):
|
||||
new_kw = dict(ca_certs=self.ca_certs,
|
||||
cert_verifier=self.cert_verifier,
|
||||
cert_file=self.client_certfile,
|
||||
key_file=self.client_keyfile,
|
||||
keyobj=self.keyobj,
|
||||
certobj=self.certobj)
|
||||
new_kw.update(kw)
|
||||
return CheckingClientHTTPSConnection(self.cert_path,
|
||||
*args, **new_kw)
|
||||
return self.do_open(open, req)
|
||||
|
||||
https_request = u2.AbstractHTTPHandler.do_request_
|
||||
|
||||
class HTTPSClientCertTransport(HttpTransport):
|
||||
def __init__(self, key, cert, path_to_cert, password = None,
|
||||
ca_certs=None, cert_verifier=None,
|
||||
client_keyfile=None, client_certfile=None,
|
||||
client_keyobj=None, client_certobj=None,
|
||||
cookie_callback=None, user_agent_string=None,
|
||||
**kwargs):
|
||||
Transport.__init__(self)
|
||||
# self.ClientObj = parent
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.cert_path = path_to_cert
|
||||
if key:
|
||||
client_certobj = OpenSSL.crypto.load_certificate \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, file(cert).read())
|
||||
if password:
|
||||
client_keyobj = OpenSSL.crypto.load_privatekey \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, file(key).read(),
|
||||
str(password))
|
||||
else:
|
||||
bio = M2Crypto.BIO.openfile(key)
|
||||
rsa = M2Crypto.m2.rsa_read_key(bio._ptr(),lambda *unused:None)
|
||||
if not rsa:
|
||||
raise OpenSSL.crypto.Error
|
||||
client_keyobj = OpenSSL.crypto.load_privatekey \
|
||||
(OpenSSL.SSL.FILETYPE_PEM, file(key).read())
|
||||
|
||||
Unskin(self.options).update(kwargs)
|
||||
self.cookiejar = CookieJar(DefaultCookiePolicy())
|
||||
self.cookie_callback = cookie_callback
|
||||
self.user_agent_string = user_agent_string
|
||||
log.debug("Proxy: %s", self.options.proxy)
|
||||
from dslib.network import ProxyManager
|
||||
proxy_handler = ProxyManager.HTTPS_PROXY.create_proxy_handler()
|
||||
proxy_auth_handler = \
|
||||
ProxyManager.HTTPS_PROXY.create_proxy_auth_handler()
|
||||
if ca_certs or (client_keyfile and client_certfile) \
|
||||
or (client_keyobj and client_certobj):
|
||||
https_handler = CheckingClientHTTPSHandler(cert_path=path_to_cert,
|
||||
ca_certs=ca_certs, cert_verifier=cert_verifier,
|
||||
client_keyfile=client_keyfile, client_certfile = \
|
||||
client_certfile, client_keyobj=client_keyobj,
|
||||
client_certobj=client_certobj)
|
||||
else:
|
||||
https_handler = u2.HTTPSHandler()
|
||||
self.urlopener = u2.build_opener(SUDSHTTPRedirectHandler(),
|
||||
u2.HTTPCookieProcessor(self.cookiejar),
|
||||
https_handler)
|
||||
if proxy_handler:
|
||||
self.urlopener.add_handler(proxy_handler)
|
||||
if proxy_auth_handler:
|
||||
self.urlopener.add_handler(proxy_auth_handler)
|
||||
self.urlopener.addheaders = [('User-agent', self.user_agent_string)]
|
@ -0,0 +1,95 @@
|
||||
#-*- 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.
|
||||
|
||||
import sys
|
||||
import socket
|
||||
from M2Crypto import RSA, X509, EVP, m2
|
||||
from calculate.lib.datavars import DataVars
|
||||
import gettext
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('calculate_console',sys.modules[__name__])
|
||||
|
||||
def passphrase_callback(v):
|
||||
if type(v) == int or not v:
|
||||
return None
|
||||
return str(v)
|
||||
|
||||
def generateRSAKey():
|
||||
return RSA.gen_key(2048, m2.RSA_F4)
|
||||
|
||||
def makePKey(key):
|
||||
pkey = EVP.PKey()
|
||||
pkey.assign_rsa(key)
|
||||
return pkey
|
||||
|
||||
def makeRequest(pubkey, pkey, serv_host, auto = False):
|
||||
""" create query to the signing on server """
|
||||
req = X509.Request()
|
||||
# Seems to default to 0, but we can now set it as well, so just API test
|
||||
req.set_version(req.get_version())
|
||||
req.set_pubkey(pkey)
|
||||
name = X509.X509_Name()
|
||||
if auto:
|
||||
c = 'n'
|
||||
else:
|
||||
c = raw_input (_("Enter certificate data by hand? y/[n]: "))
|
||||
# Get HostName
|
||||
host_name = socket.getfqdn()
|
||||
list_host_name = host_name.split('.')
|
||||
result_host_name = list_host_name[0]+"@"+serv_host
|
||||
# Get username
|
||||
clVars = DataVars()
|
||||
clVars.flIniFile()
|
||||
username = clVars.Get('ur_fullname')
|
||||
# Get language
|
||||
lang = gettext.locale.getdefaultlocale()[0][:2]
|
||||
if c.lower() in ['y', 'yes']:
|
||||
#if serv_host in host_name:
|
||||
#host_name = host_name.replace('.'+serv_host, '')
|
||||
#list_host_name = host_name.split('.')
|
||||
#result_host_name = \
|
||||
#list_host_name[len(list_host_name)-1]+"@"+serv_host
|
||||
#else:
|
||||
#host_name = socket.getfqdn()
|
||||
name.CN = raw_input (_('Host Name [%s] : ') %result_host_name)
|
||||
if name.CN in ['', None]:
|
||||
name.CN = result_host_name
|
||||
|
||||
name.OU = raw_input (_('User Name [%s]: ') %username)
|
||||
if name.OU in ['', None]:
|
||||
name.OU = username
|
||||
name.O = raw_input (_('Organization Name: '))
|
||||
name.L = raw_input (_('Network address (hostname or IP) [%s]: ')\
|
||||
%host_name)
|
||||
name.ST = raw_input (_('State Name: '))
|
||||
name.C = raw_input (_('Country (2 words): [%s]') %lang)
|
||||
if not name.C:
|
||||
name.C = lang
|
||||
else:
|
||||
name.CN = result_host_name # Имя сертификата (Common Name);
|
||||
name.OU = username # Название отдела (Organization Unit);
|
||||
name.O = 'My Company'# Название организации (Organization Name);
|
||||
name.L = host_name # Название города (Locality Name);
|
||||
name.ST = 'My State'# Название региона (State Name);
|
||||
name.C = lang # Двухсимвольный код страны (Country);
|
||||
req.set_subject_name(name)
|
||||
|
||||
ext1 = X509.new_extension('Comment', 'Auto Generated')
|
||||
extstack = X509.X509_Extension_Stack()
|
||||
extstack.push(ext1)
|
||||
req.add_extensions(extstack)
|
||||
req.sign(pkey, 'md5')
|
||||
return req
|
@ -0,0 +1,576 @@
|
||||
#-*- 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.
|
||||
|
||||
import time, os, sys, re
|
||||
import subprocess
|
||||
from OpenSSL import crypto
|
||||
import shlex
|
||||
from sudsds import MethodNotFound
|
||||
from calculate.core.server.cert_cmd import getHwAddr, getIpLocal
|
||||
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('calculate_console',sys.modules[__name__])
|
||||
from calculate.core.client.function import create_obj
|
||||
|
||||
def _print (*args):
|
||||
print " ".join(map(lambda x:unicode(x).encode('utf-8'),args))
|
||||
|
||||
# get list of certificate and session id
|
||||
def get_sid (SID_FILE):
|
||||
if not os.path.exists(SID_FILE):
|
||||
fi = open(SID_FILE, 'w')
|
||||
fi.write('0')
|
||||
fi.close()
|
||||
sid = 0
|
||||
else:
|
||||
fi = open(SID_FILE, 'r')
|
||||
sid = fi.read()
|
||||
fi.close()
|
||||
return sid
|
||||
|
||||
def clear ():
|
||||
""" delete caching suds file """
|
||||
try:
|
||||
import glob
|
||||
for filename in glob.glob("/tmp/suds/suds-*"):
|
||||
#print "delete", filename
|
||||
os.unlink (filename)
|
||||
except:
|
||||
print _("Clear Cache error! ")
|
||||
return 1
|
||||
|
||||
def get_ip_global():
|
||||
import urllib2
|
||||
|
||||
strURL = 'http://api.wipmania.com/'
|
||||
f = urllib2.urlopen(urllib2.Request(strURL))
|
||||
response = f.read()
|
||||
outerIP = response.split("<br>")[0]
|
||||
f.close()
|
||||
return outerIP
|
||||
|
||||
def get_ip_mac_type(client_type = None):
|
||||
results = []
|
||||
#try:
|
||||
results.append ( getIpLocal() )
|
||||
#except:
|
||||
#results.append ('no_ip')
|
||||
#try:
|
||||
results.append ( getHwAddr())
|
||||
#except:
|
||||
#results.append ('no_mac')
|
||||
if client_type:
|
||||
results.append (client_type)
|
||||
else:
|
||||
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[91m * \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')
|
||||
elif field.value == 'auto':
|
||||
value = _('auto')
|
||||
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 = [[]]
|
||||
|
||||
# if empty table
|
||||
if not filter (None, map(lambda x: x, body)):
|
||||
body = [['']*len(head)]
|
||||
res = printTable(body, head)
|
||||
sys.stdout.flush()
|
||||
sys.stdout.write(res)
|
||||
continue
|
||||
|
||||
ChoiceValue = field.tablevalue.values.ChoiceValue
|
||||
for row in xrange(len(ChoiceValue)):
|
||||
if ChoiceValue[row].typefield in ['check', 'check_tristate']:
|
||||
for i in xrange(len(body)):
|
||||
if body[i][row] == 'on':
|
||||
body[i][row] = _('yes')
|
||||
if body[i][row] == 'off':
|
||||
body[i][row] = _('no')
|
||||
if body[i][row] == 'auto':
|
||||
body[i][row] = _('auto')
|
||||
if ChoiceValue[row].typefield == 'password':
|
||||
for i in xrange(len(body)):
|
||||
if body[i][row]:
|
||||
body[i][row] = '***'
|
||||
|
||||
data = []
|
||||
for body_row in body:
|
||||
data.append(map(lambda x: x if x else '', body_row))
|
||||
|
||||
print green+'%s: ' %(field.label)
|
||||
res = printTable(data, head)
|
||||
sys.stdout.flush()
|
||||
sys.stdout.write(res)
|
||||
|
||||
else:
|
||||
uncompatible_count += 1
|
||||
|
||||
if uncompatible_count == len (Fields) and group_name:
|
||||
print green + _('Not used')
|
||||
|
||||
def print_brief(view, 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 listToArray (client, _list, _type = 'string'):
|
||||
Array = client.factory.create('%sArray' %_type)
|
||||
for i in _list:
|
||||
Array['%s' %_type].append(i)
|
||||
return Array
|
||||
|
||||
def listToArrayArray (client, _list, _type = 'string'):
|
||||
ArrayArray = client.factory.create('%sArrayArray' %_type)
|
||||
for i in _list:
|
||||
Array = client.factory.create('%sArray' %_type)
|
||||
for j in i:
|
||||
Array[_type].append(j)
|
||||
ArrayArray['%sArray' %_type].append(Array)
|
||||
return ArrayArray
|
||||
|
||||
class switch(object):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
self.fall = False
|
||||
|
||||
def __iter__(self):
|
||||
"""Return the match method once, then stop"""
|
||||
yield self.match
|
||||
raise StopIteration
|
||||
|
||||
def match(self, *args):
|
||||
"""Indicate whether or not to enter a case suite"""
|
||||
if self.fall or not args:
|
||||
return True
|
||||
elif self.value in args: # changed for v1.5, see below
|
||||
self.fall = True
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
#################API FUNCTION###############################
|
||||
def show_view(view):
|
||||
print "+====== show view! ======+"
|
||||
|
||||
def printTable(data, header=None ):
|
||||
res = []
|
||||
for row in data:
|
||||
encode_row = map(lambda x: x.encode('utf-8') if x else '', row)
|
||||
res.append(encode_row)
|
||||
data = res
|
||||
|
||||
if type(header) == list:
|
||||
header = map(lambda x: x.encode('utf-8'), header)
|
||||
|
||||
lens = [0]*len(data[0])
|
||||
for row in data:
|
||||
for numCol, column in enumerate(row):
|
||||
cLen = len(unicode(str(column).decode('utf-8')))
|
||||
if lens[numCol] < cLen:
|
||||
lens[numCol] = cLen
|
||||
res = ""
|
||||
spacer = lambda lenList: '+' + '+'.join( '-'*(x+2) for x in lenList ) + '+'
|
||||
drawRow = lambda lenList, valueList: '|' + "".join(
|
||||
' %s ' % item + ' ' * (lenList[num] - \
|
||||
len(unicode(str(item).decode('utf-8')))) + '|'
|
||||
for num, item in enumerate(valueList) )
|
||||
if header:
|
||||
for numCol, column in enumerate(header):
|
||||
cLen = len(unicode(str(column).decode('utf-8')))
|
||||
if lens[numCol] < cLen:
|
||||
lens[numCol] = cLen
|
||||
res += spacer(lens)+ "\n"
|
||||
res += drawRow( lens, header )+ "\n"
|
||||
|
||||
res+= spacer(lens) + "\n"
|
||||
for r in data:
|
||||
res += drawRow( lens, r )+ "\n"
|
||||
res+= spacer(lens)+ "\n"
|
||||
return res
|
||||
|
||||
def show_table(table, item):
|
||||
head = table.head.string if hasattr (table.head, 'string') else None
|
||||
data = []
|
||||
for line in table.body[0]:
|
||||
if hasattr (line, 'string'):
|
||||
data.append(line.string)
|
||||
|
||||
res = printTable(data, head)
|
||||
sys.stdout.flush()
|
||||
sys.stdout.write(res)
|
||||
|
||||
def show_error(item):
|
||||
red = '\033[91m * \033[0m'
|
||||
# FAIL = '\033[31m'
|
||||
# ENDC = '\033[0m'
|
||||
print red + _("Error")
|
||||
print red + item.message
|
||||
# print ENDC
|
||||
|
||||
def show_warning(item):
|
||||
yellow = '\033[93m * \033[0m'
|
||||
# WARNING = '\033[91m'
|
||||
print yellow + _("Warning")
|
||||
print yellow + item.message
|
||||
# ENDC = '\033[0m'
|
||||
# print ENDC
|
||||
|
||||
def show_group(item):
|
||||
print "Group"
|
||||
print item.message
|
||||
|
||||
def show_result(result):
|
||||
print "Result = ", result.message
|
||||
|
||||
def startTask(item):
|
||||
print "start Task"
|
||||
print item.message
|
||||
|
||||
def endTask(item):
|
||||
print item.message
|
||||
print "end Task\n\n"
|
||||
|
||||
def beginFrame(item):
|
||||
pass
|
||||
|
||||
def endFrame(item):
|
||||
pass
|
||||
|
||||
def startGroup(item):
|
||||
pass
|
||||
|
||||
def endGruop(item):
|
||||
pass
|
||||
|
||||
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_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
|
||||
|
||||
#################MESSAGE####################################
|
||||
|
||||
def analysis(client, sid, s):
|
||||
""" analysis of the bounced message method """
|
||||
messages = s[0]
|
||||
for mess in messages:
|
||||
if mess.type == 'pid':
|
||||
try:
|
||||
pid = int(mess.message)
|
||||
except:
|
||||
show_error(_('server send pid = ') + pid)
|
||||
return 1
|
||||
get_messages(client, sid, pid)
|
||||
elif mess.type == 'error':
|
||||
show_error(mess)
|
||||
elif mess.type == 'warning':
|
||||
show_warning(mess)
|
||||
|
||||
def get_message(client, item, sid, pid):
|
||||
""" get one message by its type """
|
||||
for case in switch(item.type):
|
||||
if case('normal'):
|
||||
# sys.stdout.flush()
|
||||
# sys.stdout.write('\x1b[1;33m' + item.message + '\033[0m')
|
||||
if item.message:
|
||||
p = re.compile(r'<b>|</b>')
|
||||
print p.sub('', item.message)
|
||||
# print item.message
|
||||
return 1
|
||||
if case('progress'):
|
||||
get_Progress(client, sid, pid, item.id)
|
||||
return 1
|
||||
if case('error'):
|
||||
show_error(item)
|
||||
if item.message == "403 Forbidden":
|
||||
return 0
|
||||
return 1
|
||||
if case('warning'):
|
||||
show_warning(item)
|
||||
return 1
|
||||
if case('table'):
|
||||
get_Table(client, sid, pid, item)
|
||||
return 1
|
||||
if case('group'):
|
||||
show_group(client, sid, pid, item)
|
||||
return 1
|
||||
if case('question'):
|
||||
send_Message(client, sid, pid, item)
|
||||
return 1
|
||||
if case('password'):
|
||||
send_Password(client, sid, pid, item)
|
||||
return 1
|
||||
if case('startTask'):
|
||||
startTask(item)
|
||||
return 1
|
||||
if case('endTask'):
|
||||
endTask(item)
|
||||
return 1
|
||||
if case('beginFrame'):
|
||||
beginFrame(item)
|
||||
return 1
|
||||
if case('endFrame'):
|
||||
endFrame(item)
|
||||
return 0
|
||||
if case('startGroup'):
|
||||
startGroup(item)
|
||||
return 1
|
||||
if case('endGruop'):
|
||||
endGruop(item)
|
||||
return 1
|
||||
if case('briefParams'):
|
||||
callView(client, item, sid)
|
||||
if case(): # default, could also just omit condition or 'if True'
|
||||
return 1
|
||||
|
||||
def get_messages(client, sid, pid):
|
||||
""" get frame in a separate thread """
|
||||
#thread_messages = threading.Thread(target=get_Frame,\
|
||||
#args = (client, sid, pid))
|
||||
#thread_messages.start()
|
||||
get_Frame(client, sid, pid)
|
||||
|
||||
|
||||
def get_Frame(client, sid, pid):
|
||||
""" get all messages, until type is not endFrame (or Error) """
|
||||
end_frame = 1
|
||||
while end_frame:
|
||||
current_frame = client.service[0].get_frame(sid, pid)
|
||||
while current_frame in [None, [], ""]:
|
||||
time.sleep(float(client.frame_period))
|
||||
current_frame = client.service[0].get_frame(sid, pid)
|
||||
for item in current_frame[0]:
|
||||
end_frame = get_message(client, item, sid, pid)
|
||||
|
||||
def get_entire_frame(client, pid):
|
||||
""" get entire frame, from beginning (if client disconnected) """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
list_pid = client.service.list_pid(sid = sid)
|
||||
if hasattr (list_pid, 'integer'):
|
||||
if not pid in list_pid.integer:
|
||||
print _('Process not exist or not belong to your session')
|
||||
# if list_pid[0] == [0]:
|
||||
# return 0
|
||||
# for pid in list_pid[0]:
|
||||
end_frame = 1
|
||||
while end_frame:
|
||||
current_frame = client.service.get_entire_frame(sid, pid)
|
||||
while current_frame in [None, [], ""]:
|
||||
time.sleep(1)
|
||||
current_frame = client.service.get_frame(sid, pid)
|
||||
for item in current_frame[0]:
|
||||
end_frame = get_message(client, item, sid, pid)
|
||||
|
||||
def get_Progress(client, sid, pid, id):
|
||||
""" get progress for the current job """
|
||||
returnProgr = client.service.get_progress(sid, pid, id)
|
||||
temp_progress = -1
|
||||
last_message = ''
|
||||
percent = returnProgr.percent
|
||||
while percent <= 100 and percent >= 0 :
|
||||
if temp_progress != percent:
|
||||
last_message = print_progress(returnProgr, last_msg = last_message)
|
||||
if percent == 100:
|
||||
print
|
||||
return
|
||||
temp_progress = percent
|
||||
time.sleep(1)
|
||||
returnProgr = client.service.get_progress(sid, pid, id)
|
||||
percent = returnProgr.percent
|
||||
if percent < 0:
|
||||
print_progress(returnProgr, error = True)
|
||||
else:
|
||||
print_progress(returnProgr)
|
||||
|
||||
#def cout(string):
|
||||
# sys.stdout.write(string)
|
||||
# sys.stdout.flush()
|
||||
#
|
||||
#for perc in xrange(101):
|
||||
# cout ('\r' + str(perc / 1.0).rjust(5) + '% ')
|
||||
# time.sleep(.2)
|
||||
|
||||
def cout_progress(string):
|
||||
sys.stdout.write('\b\b\b\b\b\b' + string)
|
||||
sys.stdout.flush()
|
||||
|
||||
def cout(string):
|
||||
sys.stdout.write(string)
|
||||
sys.stdout.flush()
|
||||
|
||||
def print_progress(returnProgr, last_msg = None, error = False):
|
||||
if error:
|
||||
cout_progress ('\n'+_("Error task by %s") \
|
||||
%str(0 - returnProgr.percent).rjust(5) + '%\n')
|
||||
return ''
|
||||
elif returnProgr.long_message:
|
||||
if last_msg == returnProgr.long_message:
|
||||
cout_progress('%s%%' %str(returnProgr.percent).rjust(5))
|
||||
else:
|
||||
if not last_msg:
|
||||
cout_progress('')
|
||||
else:
|
||||
cout_progress('OK'.rjust(6) + '\n')
|
||||
cout_progress('%s %s%%' %(returnProgr.long_message, \
|
||||
str(returnProgr.percent).rjust(5)))
|
||||
return returnProgr.long_message
|
||||
elif returnProgr.short_message:
|
||||
if last_msg == returnProgr.short_message:
|
||||
cout_progress('%s%%' %str(returnProgr.percent).rjust(5))
|
||||
else:
|
||||
if not last_msg:
|
||||
cout_progress('')
|
||||
else:
|
||||
cout_progress('OK'.rjust(6) + '\n')
|
||||
cout_progress('%s %s%%' %(returnProgr.short_message, \
|
||||
str(returnProgr.percent).rjust(5)))
|
||||
return returnProgr.short_message
|
||||
else:
|
||||
# print '%s' %str(returnProgr.percent).rjust(5) + '%'
|
||||
cout_progress ('%s' %str(returnProgr.percent).rjust(5) + '%')
|
||||
return ''
|
||||
|
||||
def get_Table(client, sid, pid, item):
|
||||
table = client.service.get_table(sid, pid, item.id)
|
||||
show_table(table, item)
|
||||
|
||||
def send_Message(client, sid, pid, item):
|
||||
""" send answer to the question """
|
||||
answer = raw_input (item.message)
|
||||
client.service.send_message(sid, pid, answer)
|
||||
# show_result(result)
|
||||
|
||||
def send_Password(client, sid, pid, item):
|
||||
""" send password """
|
||||
from getpass import getpass
|
||||
password = getpass(prompt=item.message)
|
||||
result = client.service.send_message(sid, pid, password)
|
||||
show_result(result)
|
||||
|
||||
|
||||
def _return_revoked_serials(self, crlfile):
|
||||
try:
|
||||
serials = []
|
||||
crltext = open(crlfile, 'r').read()
|
||||
crl = crypto.load_crl(crypto.FILETYPE_PEM, crltext)
|
||||
revs = crl.get_revoked()
|
||||
for revoked in revs:
|
||||
serials.append(str(revoked.get_serial()))
|
||||
return serials
|
||||
except (ImportError, AttributeError):
|
||||
call = '/usr/bin/openssl crl -text -noout -in %s' % crlfile
|
||||
call = shlex.split(call)
|
||||
serials = []
|
||||
(res,err) = subprocess.Popen(call, stdout=subprocess.PIPE).communicate()
|
||||
for line in res.split('\n'):
|
||||
if line.find('Serial Number:') == -1:
|
||||
continue
|
||||
(crap, serial) = line.split(':')
|
||||
serial = serial.strip()
|
||||
serial = int(serial, 16)
|
||||
serials.append(serial)
|
||||
return serials
|
@ -0,0 +1,324 @@
|
||||
#-*- 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.
|
||||
|
||||
import argparse, sys
|
||||
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
|
||||
from cert_func import get_password
|
||||
|
||||
def get_view(client, method, sid, view_params):
|
||||
try:
|
||||
view = client.service[0][method + '_view'](client.sid, view_params)
|
||||
except urllib2.URLError, e:
|
||||
print _('Failed to connect')+':', e
|
||||
sys.exit(1)
|
||||
return view
|
||||
|
||||
def get_method_argparser(client, args):
|
||||
method = args.method
|
||||
view_params = get_view_params(client, method + '_view', step = None, \
|
||||
expert = True)
|
||||
|
||||
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:
|
||||
if not Group.fields:
|
||||
continue
|
||||
# if Group.name:
|
||||
group = parser.add_argument_group(Group.name)
|
||||
for field in Group.fields.Field:
|
||||
if field.opt:
|
||||
action = None
|
||||
arg_type = str
|
||||
if field.element in ['check', 'check_tristate']:
|
||||
arg_type = bool
|
||||
elif field.element == 'radio' and field.type == 'bool':
|
||||
arg_type = bool
|
||||
elif field.element == 'table' and field.type != 'steps':
|
||||
action = 'append'
|
||||
|
||||
opt = field.opt
|
||||
metavalue = opt.metavalue if opt.metavalue \
|
||||
else field.name.upper()
|
||||
|
||||
if ':' in metavalue:
|
||||
metavalue = field.name.upper()
|
||||
|
||||
if arg_type == str:
|
||||
if opt.shortopt and opt.longopt:
|
||||
group.add_argument(opt.shortopt, opt.longopt,
|
||||
type = arg_type, dest=field.name, metavar = \
|
||||
metavalue, action = action, help = opt.help)
|
||||
elif opt.shortopt and not opt.longopt:
|
||||
group.add_argument(opt.shortopt,
|
||||
type = arg_type, dest=field.name, metavar = \
|
||||
metavalue, action = action, help = opt.help)
|
||||
elif opt.longopt and not opt.shortopt:
|
||||
group.add_argument(opt.longopt,
|
||||
type = arg_type, dest=field.name, metavar = \
|
||||
metavalue, action = action, help = opt.help)
|
||||
|
||||
elif arg_type == bool:
|
||||
if opt.shortopt and opt.longopt:
|
||||
group.add_argument(opt.shortopt, opt.longopt,
|
||||
action='store_true', dest=field.name,
|
||||
default=None, help = opt.help)
|
||||
elif opt.shortopt and not opt.longopt:
|
||||
group.add_argument(opt.shortopt,
|
||||
action='store_true', dest=field.name,
|
||||
default=None, help = opt.help)
|
||||
elif opt.longopt and not opt.shortopt:
|
||||
group.add_argument(opt.longopt,
|
||||
action='store_true', dest=field.name,
|
||||
default=None, help = opt.help)
|
||||
return parser, view
|
||||
|
||||
def call_method(client, args):
|
||||
method = args.method
|
||||
method_parser, view = get_method_argparser(client, args)
|
||||
param_object = _create_obj(client, method)
|
||||
args = method_parser.parse_known_args()[0]
|
||||
|
||||
param_object, steps = collect_object(client, param_object, view, args)
|
||||
|
||||
if steps.label and hasattr (param_object, 'CheckOnly'):
|
||||
param_object['CheckOnly'] = True
|
||||
# print param_object
|
||||
method_result = client.service[0][method](client.sid, param_object)
|
||||
if not method_result:
|
||||
print _('method is not available')
|
||||
return None
|
||||
if method_result.ReturnedMessage[0].type and \
|
||||
method_result.ReturnedMessage[0].type != "pid":
|
||||
for error in method_result.ReturnedMessage:
|
||||
red = '\033[91m * \033[0m'
|
||||
print red + error.message
|
||||
return None
|
||||
|
||||
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:
|
||||
try:
|
||||
ask = raw_input('\n' + _('Run process? (yes/no): '))
|
||||
red = '\033[91m * \033[0m'
|
||||
except KeyboardInterrupt:
|
||||
ask = 'no'
|
||||
red = '\n'+'\033[91m * \033[0m'
|
||||
if ask.lower() in ['n', 'no']:
|
||||
print red + _('Interrupted by user')
|
||||
return None
|
||||
if ask.lower() in ['y', 'yes']:
|
||||
break
|
||||
|
||||
param_object['CheckOnly'] = False
|
||||
method_result = client.service[0][method](client.sid, param_object)
|
||||
if not method_result:
|
||||
print _('method is not available')
|
||||
return None
|
||||
if method_result.ReturnedMessage[0].type and \
|
||||
method_result.ReturnedMessage[0].type != "pid":
|
||||
for error in method_result.ReturnedMessage:
|
||||
red = '\033[91m * \033[0m'
|
||||
print red + error.message
|
||||
return None
|
||||
|
||||
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
|
||||
for field in Group.fields.Field:
|
||||
if field.uncompatible:
|
||||
continue
|
||||
if field.element in ['check', 'check_tristate'] or \
|
||||
field.element == 'radio' and field.type == 'bool':
|
||||
param_object[field.name] = _getattr(args, field.name)
|
||||
|
||||
elif field.element == 'input' and \
|
||||
field.name in ['cl_page_offset','cl_page_count']:
|
||||
val = _getattr(args, field.name)
|
||||
if not val:
|
||||
val = 0
|
||||
param_object[field.name] = val
|
||||
|
||||
elif field.element in ['input', 'combo', 'comboEdit', 'openfile',\
|
||||
'file', 'password', 'radio']:
|
||||
param_object[field.name] = _getattr(args, field.name)
|
||||
elif field.element in ['multichoice', 'multichoice_add', \
|
||||
'selecttable', 'selecttable_add']:
|
||||
val = _getattr(args, field.name)
|
||||
if val in ['off', 'none']:
|
||||
param_object[field.name] = listToArray(client, [None])
|
||||
else:
|
||||
param_object[field.name] = listToArray(client, \
|
||||
val.split(',')) if val else None
|
||||
|
||||
elif field.element == 'table' and field.type != 'steps':
|
||||
val = _getattr(args, field.name)
|
||||
param_object[field.name] = collect_table(field, val, client)
|
||||
|
||||
elif field.element == 'table' and field.type == 'steps':
|
||||
steps = field
|
||||
|
||||
return param_object, steps
|
||||
|
||||
def collect_table(field, val_list, client):
|
||||
if not val_list:
|
||||
return None
|
||||
val_table = map(lambda x: x.split(':'), val_list)
|
||||
|
||||
obj_body = []
|
||||
key_list = []
|
||||
if hasattr (field.tablevalue.body, 'stringArray'):
|
||||
for obj_row in field.tablevalue.body.stringArray:
|
||||
if hasattr(obj_row, 'string'):
|
||||
key_list.append(obj_row.string[0])
|
||||
obj_body.append(obj_row.string)
|
||||
|
||||
obj_body = collect_obj_body(obj_body, field)
|
||||
column = len(field.tablevalue.head.string)
|
||||
|
||||
ChoiceValue = field.tablevalue.values.ChoiceValue
|
||||
type_list = map(lambda x: x.typefield, ChoiceValue)
|
||||
for i in range(len(val_table)):
|
||||
if 'password' in type_list:
|
||||
if len(val_table[i]) != 2 or val_table[i][1].lower() != '':
|
||||
password=get_password(_('Password for %s: ')%val_table[i][0],\
|
||||
_('Repeat password for %s: ') %val_table[i][0])
|
||||
password = password if password else ''
|
||||
temp_row = []
|
||||
empty_row_flag = True if len (val_table[i]) == 1 else False
|
||||
for j in range(column):
|
||||
# not adding if readonly
|
||||
if j > (len(ChoiceValue) + 1):
|
||||
continue
|
||||
|
||||
choice_value = ChoiceValue[j]
|
||||
typefield = choice_value.typefield
|
||||
if typefield == 'readonly':
|
||||
continue
|
||||
elif typefield in ['check', 'check_tristate']:
|
||||
if len (val_table[i]) < j + 1:
|
||||
temp_row.append('')
|
||||
continue
|
||||
if val_table[i][j].lower() in ['on', 'yes']:
|
||||
temp_row.append('on')
|
||||
elif val_table[i][j].lower() in ['off', 'no']:
|
||||
temp_row.append('off')
|
||||
else:
|
||||
temp_row.append(val_table[i][j])
|
||||
|
||||
elif typefield in ['input', 'combo', 'comboEdit', 'openfile', \
|
||||
'file', 'radio']:
|
||||
if len (val_table[i]) < j + 1:
|
||||
temp_row.append('')
|
||||
else:
|
||||
temp_row.append(val_table[i][j])
|
||||
elif typefield == 'password':
|
||||
if 'password' in locals():
|
||||
temp_row.append(password)
|
||||
del password
|
||||
else:
|
||||
if len (val_table[i]) < j + 1:
|
||||
temp_row.append('')
|
||||
else:
|
||||
temp_row.append(val_table[i][j])
|
||||
elif typefield in ['multichoice', 'multichoice_add']:
|
||||
if len (val_table[i]) < j + 1:
|
||||
temp_row.append('')
|
||||
else:
|
||||
temp_row.append(val_table[i][j])
|
||||
|
||||
if temp_row[0] in key_list:
|
||||
ind = key_list.index(temp_row[0])
|
||||
|
||||
count_val = filter (None, temp_row)
|
||||
if (len(count_val) == 1 and not empty_row_flag) or \
|
||||
(len(count_val) == 2 and temp_row[1].lower() == 'none'):
|
||||
obj_body.pop(ind)
|
||||
key_list.pop(ind)
|
||||
else:
|
||||
obj_body.pop(ind)
|
||||
obj_body.insert(ind, temp_row)
|
||||
else:
|
||||
count_val = filter (None, temp_row)
|
||||
if (len(count_val) == 1 and not empty_row_flag) or \
|
||||
(len(count_val) == 2 and temp_row[1].lower() == 'none'):
|
||||
continue
|
||||
obj_body.append(temp_row)
|
||||
key_list.append(temp_row[0])
|
||||
if not obj_body:
|
||||
obj_body = [[None]]
|
||||
return listToArrayArray(client, obj_body)
|
||||
|
||||
def collect_obj_body(body, field):
|
||||
column = len(field.tablevalue.head.string)
|
||||
ChoiceValue = field.tablevalue.values.ChoiceValue
|
||||
result_table = []
|
||||
for i in range(len(body)):
|
||||
temp_row = []
|
||||
for j in range(column):
|
||||
# not adding if readonly
|
||||
if j > (len(ChoiceValue) + 1):
|
||||
continue
|
||||
|
||||
choice_value = ChoiceValue[j]
|
||||
typefield = choice_value.typefield
|
||||
if typefield == 'readonly':
|
||||
continue
|
||||
elif typefield in ['check', 'check_tristate']:
|
||||
if len (body[i]) < j + 1:
|
||||
temp_row.append('')
|
||||
continue
|
||||
if not body[i][j]:
|
||||
temp_row.append('')
|
||||
elif body[i][j].lower() in ['on', 'yes']:
|
||||
temp_row.append('on')
|
||||
elif body[i][j].lower() in ['off', 'no']:
|
||||
temp_row.append('off')
|
||||
else:
|
||||
temp_row.append(body[i][j])
|
||||
|
||||
elif typefield in ['input', 'combo', 'comboEdit', 'openfile', \
|
||||
'file', 'password', 'radio']:
|
||||
if len (body[i]) < j + 1:
|
||||
temp_row.append('')
|
||||
elif not body[i][j]:
|
||||
temp_row.append('')
|
||||
else:
|
||||
temp_row.append(body[i][j])
|
||||
elif typefield in ['multichoice', 'multichoice_add']:
|
||||
if len (body[i]) < j + 1:
|
||||
temp_row.append('')
|
||||
elif not body[i][j]:
|
||||
temp_row.append('')
|
||||
else:
|
||||
temp_row.append(body[i][j])
|
||||
|
||||
result_table.append(temp_row)
|
||||
return result_table
|
@ -0,0 +1,147 @@
|
||||
#-*- 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
|
||||
import sys
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('calculate_console',sys.modules[__name__])
|
||||
client_types = "console"
|
||||
#client_types = "gui"
|
||||
|
||||
def pid_inf(client, sid, pids):
|
||||
""" get and show information about process """
|
||||
for pid in pids:
|
||||
s = client.service.pid_info(sid, pid)
|
||||
if s == "":
|
||||
print _("PID not found")
|
||||
return 1
|
||||
if s[0][0] == "Permission denied":
|
||||
print _("Permission denied")
|
||||
return 1
|
||||
|
||||
print '\n', _(u"Process name - %s") %s[0][4]
|
||||
print _(u"Process id - %s") %s[0][0]
|
||||
print _(u"Process started %s") %s[0][2]
|
||||
if s[0][1] == '1':
|
||||
print _(u"Process is active")
|
||||
elif s[0][1] == '0':
|
||||
print _(u"Process has been completed")
|
||||
else:
|
||||
print _(u"Process killed")
|
||||
return 0
|
||||
|
||||
def client_list_pid(client):
|
||||
""" get all process id for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
red = '\033[91m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
try:
|
||||
list_pid = client.service.list_pid(sid = sid)
|
||||
if list_pid[0][0] == 0:
|
||||
print red + _("Not found pid for this session!")
|
||||
return 0
|
||||
else:
|
||||
for i in list_pid[0]:
|
||||
print green + "pid - %d" %i
|
||||
except:
|
||||
print red + _("Server get pids error")
|
||||
return 1
|
||||
return len(list_pid[0])
|
||||
|
||||
def gen_pid_ls(client):
|
||||
""" generation list with pid for this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
pid_ls = []
|
||||
try:
|
||||
list_pid = client.service.list_pid(sid = sid)
|
||||
if list_pid[0][0] == 0:
|
||||
print _("Not found pid for this session!")
|
||||
return 0
|
||||
else:
|
||||
for i in list_pid[0]:
|
||||
pid_ls.append(i)
|
||||
except:
|
||||
print _("Server get pids error")
|
||||
return 0
|
||||
return pid_ls
|
||||
|
||||
def client_pid_info(client):
|
||||
""" get information about selected process (or about all) """
|
||||
# try:
|
||||
sid = get_sid(client.SID_FILE)
|
||||
pid_ls = gen_pid_ls(client)
|
||||
if pid_ls:
|
||||
pid_inf(client, sid, pid_ls)
|
||||
# except:
|
||||
# print _("Error get data")
|
||||
# return 1
|
||||
# return 0
|
||||
|
||||
def client_list_methods(client):
|
||||
""" get & show all available methods for this certificate """
|
||||
DAT = 0 # Access to data soap structure
|
||||
RES = 0 # Access to result
|
||||
COM = 0 # Getting command line
|
||||
METH = 1 # Getting method line
|
||||
TR_METH = 2 # Translate method name
|
||||
results = client.service.get_methods(client.sid, client_types)
|
||||
if not results:
|
||||
print _('no methods available')
|
||||
return 1
|
||||
try:
|
||||
if results[DAT][RES][RES][COM] == '0':
|
||||
print _('no methods available')
|
||||
return 1
|
||||
except:
|
||||
pass
|
||||
print _("You can execute:"), _('use key'), '--method'
|
||||
for num in range (0, len(results[DAT])):
|
||||
# command = results[DAT][num][RES][COM]
|
||||
view_command = results[DAT][num][RES][METH]
|
||||
meth_name = results[DAT][num][RES][METH] if len \
|
||||
(results[DAT][num][RES]) < 3 else results[DAT][num][RES][TR_METH]
|
||||
print " %s - %s" % (view_command, meth_name)
|
||||
|
||||
def client_list_sessions(client):
|
||||
""" get all sessions on server """
|
||||
results = client.service.get_sessions()
|
||||
if results[0][0] == "Permission denied":
|
||||
print results[0][0]
|
||||
return 1
|
||||
|
||||
print _("Execute sessions:")
|
||||
for sess in results[0]:
|
||||
print " - %s" %sess
|
||||
return 0
|
||||
|
||||
def client_pid_kill(client, pid):
|
||||
sid = get_sid(client.SID_FILE)
|
||||
|
||||
result = client.service.pid_kill(pid, sid)
|
||||
if result == 0:
|
||||
print _("Process is completed")
|
||||
elif result == 2:
|
||||
print _("Process killed")
|
||||
elif result == 3:
|
||||
print _("Process not found")
|
||||
elif result == -1:
|
||||
print _("Certificate not found in server database")
|
||||
elif result == -2:
|
||||
print _("Session doesn't belong to your certificate")
|
||||
elif result == 1:
|
||||
print _("It was not possible to kill process")
|
||||
return 0
|
@ -0,0 +1,116 @@
|
||||
#-*- 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.
|
||||
|
||||
import sys
|
||||
from function import get_sid
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('calculate_console',sys.modules[__name__])
|
||||
|
||||
def client_sid(sid, client, cert_id, clVars, show_info = False):
|
||||
""" get number session from server and write this in file """
|
||||
lang = clVars.Get('os_locale_locale')[:2]
|
||||
|
||||
new_sid = client.service.post_sid(sid = sid, cert_id = cert_id, lang = lang)
|
||||
fi = open(client.SID_FILE, 'w')
|
||||
sid = str(new_sid[0][0])
|
||||
fi.write(sid)
|
||||
fi.close()
|
||||
if show_info:
|
||||
if new_sid[0][1] == 1:
|
||||
print _(" New Session")
|
||||
else: print _(" Old Session")
|
||||
print _(" Your session id = %s") %sid
|
||||
|
||||
def client_del_sid(client):
|
||||
""" delete this session """
|
||||
sid = get_sid(client.SID_FILE)
|
||||
try:
|
||||
s = client.service.del_sid(sid)
|
||||
|
||||
if s[0][0] == "-1":
|
||||
print _("No access to file!")
|
||||
return -1
|
||||
if s[0][0] == "1":
|
||||
print _("Failed to obtain certificate data!")
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print _("Permission denied %s") % s[1][1]
|
||||
return -3
|
||||
|
||||
if s[0][0] == '0':
|
||||
fi = open(client.SID_FILE, 'w')
|
||||
fi.write('0')
|
||||
fi.close()
|
||||
print _("Sid Deleted!")
|
||||
except:
|
||||
print _("Server delete sid error")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
def sid_inf(client, sid):
|
||||
red = '\033[91m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
""" get information about selected session """
|
||||
s = client.service.sid_info(sid)
|
||||
if s[0][0] == "-1":
|
||||
print red + _("This session not registered on server!")
|
||||
return -1
|
||||
if s[0][0] == "-2":
|
||||
print red + _("Failed to obtain certificate data!")
|
||||
return -2
|
||||
if s[0][0] == "Permission denied":
|
||||
print red + _("Permission denied %s") % s[0][1]
|
||||
return -3
|
||||
|
||||
print _('Session information: ')
|
||||
print green + _(u"Session number - %s") %sid
|
||||
print green + _(u"Certificate number - %s") %s[0][0]
|
||||
print green + _(u"Date issue of certificate - %s") %s[0][1]
|
||||
print green + "ip - %s" %s[0][2]
|
||||
print green + "MAC - %s\n" %s[0][3]
|
||||
return 0
|
||||
|
||||
def client_session_info(client, sid = None):
|
||||
""" select session for get information """
|
||||
try:
|
||||
select_sid = sid if sid else client.sid
|
||||
sid_inf(client, select_sid)
|
||||
except Exception, e:
|
||||
print e
|
||||
return 1
|
||||
|
||||
def client_session_list(client):
|
||||
red = '\033[91m * \033[0m'
|
||||
green = '\033[32m * \033[0m'
|
||||
res = client.service.get_sessions(client.sid)
|
||||
if hasattr (res, 'string'):
|
||||
if res.string:
|
||||
print _('Active session on server: ')
|
||||
for session_id in res.string:
|
||||
print green + session_id
|
||||
print
|
||||
return 0
|
||||
print red + _('No active session on server')
|
||||
|
||||
def session_clean(client):
|
||||
try:
|
||||
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')
|
@ -0,0 +1,29 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2010 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.
|
||||
|
||||
__version__ = "3.0.0"
|
||||
__app__ = "Calculate Console"
|
||||
|
||||
from calculate.lib.datavars import DataVars
|
||||
|
||||
class DataVarsConsole(DataVars):
|
||||
"""Variable class for installation"""
|
||||
|
||||
def importConsole(self, **args):
|
||||
'''Заполнить конфигурацию переменных, для десктопа'''
|
||||
self.importData()
|
||||
self.importData('calculate.core.variables')
|
||||
self.importData('calculate.console.variables')
|
@ -0,0 +1,34 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2008-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 calculate.lib.datavars import ReadonlyVariable
|
||||
from calculate.console.datavars import __version__,__app__
|
||||
|
||||
import console
|
||||
|
||||
section = "gui"
|
||||
|
||||
class VariableClName(ReadonlyVariable):
|
||||
"""
|
||||
Package name
|
||||
"""
|
||||
value = __app__
|
||||
|
||||
class VariableClVer(ReadonlyVariable):
|
||||
"""
|
||||
Package version
|
||||
"""
|
||||
value = __version__
|
@ -0,0 +1,41 @@
|
||||
#-*- coding: utf-8 -*-
|
||||
|
||||
# Copyright 2011-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 calculate.lib.datavars import Variable
|
||||
import sys
|
||||
from os import path
|
||||
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('cl_gui',sys.modules[__name__])
|
||||
|
||||
|
||||
class VariableClGuiData(Variable):
|
||||
"""
|
||||
Variable store path to data files
|
||||
"""
|
||||
value = '/var/calculate/server'
|
||||
|
||||
class VariableClGuiDatabase(Variable):
|
||||
"""
|
||||
Variable store name files containing clients certificates
|
||||
"""
|
||||
def get(self):
|
||||
return path.join(self.Get('cl_gui_data'),"client_certs/Database")
|
||||
|
||||
class VariableClGuiImagePath(Variable):
|
||||
"""
|
||||
Variable store path to images
|
||||
"""
|
||||
value = '/usr/share/calculate/themes'
|
@ -0,0 +1,422 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: \n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2012-02-16 12:34+0300\n"
|
||||
"PO-Revision-Date: 2012-02-16 12:34+0300\n"
|
||||
"Last-Translator: dspiridonov <ds@calculate.ru>\n"
|
||||
"Language-Team: \n"
|
||||
"Language: \n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
|
||||
"X-Poedit-Basepath: .\n"
|
||||
"X-Poedit-SearchPath-0: /var/calculate/mydir/source/spyder/cl-api-client/console/gui\n"
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/Box.py:177
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/Box.py:315
|
||||
msgid "Close your session?"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/Box.py:178
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/Box.py:316
|
||||
#, python-format
|
||||
msgid "at closing session, data %d processes will be deleted!"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:29
|
||||
msgid "Methods"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:30
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:31
|
||||
msgid "Display Methods"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:38
|
||||
msgid "Processes"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:39
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:40
|
||||
msgid "View information about running processes"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:47
|
||||
msgid "Session"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:48
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:49
|
||||
msgid "View information about current session"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:56
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:57
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:58
|
||||
msgid "Disconnect"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:66
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:67
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:68
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/conf_connection.py:81
|
||||
msgid "Connect"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:75
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:105
|
||||
msgid "Certificates"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:76
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:77
|
||||
msgid "Window work with certificates"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:83
|
||||
msgid "Tool"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:84
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:85
|
||||
msgid "Application settings"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:91
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:92
|
||||
msgid "Help"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:93
|
||||
msgid "About Application"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:99
|
||||
msgid "Exit"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:100
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainmenu.py:101
|
||||
msgid "Exit application"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:53
|
||||
msgid "User@Server_HostName"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:63
|
||||
msgid "User Name"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:68
|
||||
msgid "Organization Name"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:73
|
||||
msgid "Network address"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:78
|
||||
msgid "State Name"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:83
|
||||
msgid "Country (2 words)"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:93
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:107
|
||||
msgid "Create Request"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/create_cert.py:98
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:255
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:419
|
||||
msgid "Cancel"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/LeftMenu.py:148
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/LeftMenu.py:267
|
||||
msgid " Step "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/LeftMenu.py:204
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/LeftMenu.py:248
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/LeftMenu.py:271
|
||||
msgid " > Step "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/helpwidget.py:29
|
||||
msgid "Composed of Calculate Utilities 3.0\n"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/helpwidget.py:30
|
||||
msgid "Calculate Utilities developed company "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/helpwidget.py:31
|
||||
#, python-format
|
||||
msgid "Calculate. (c) 2007-%s"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/helpwidget.py:39
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:118
|
||||
msgid "Quit"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/helpwidget.py:68
|
||||
msgid "Calculate Utilities"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:52
|
||||
#, python-format
|
||||
msgid "Your certificate ID = %s"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:56
|
||||
msgid " New Session"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:57
|
||||
msgid " Old Session"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:58
|
||||
#, python-format
|
||||
msgid " Your session id = %s"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:60
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:101
|
||||
msgid "Certificate not send!"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:62
|
||||
#, python-format
|
||||
msgid " Your certifitate id = %d"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:65
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:108
|
||||
msgid "expiry date certificate has passed"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:67
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:111
|
||||
#, python-format
|
||||
msgid "shelf life expires after %d days"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:82
|
||||
msgid "Certificate not found in Server Database!"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:85
|
||||
msgid "Add certificate to server Database..."
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:88
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:115
|
||||
msgid "Your IP adress - "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:89
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:116
|
||||
msgid "Your MAC adress - "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:92
|
||||
msgid "Your certificate ID = "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:98
|
||||
msgid "Your session id = "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/session_function.py:104
|
||||
msgid "Your certifitate id = "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/more.py:195
|
||||
msgid "Open"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/more.py:577
|
||||
msgid "Yes"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:48
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:66
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/conf_connection.py:43
|
||||
msgid "Host"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:49
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:67
|
||||
msgid "Enter Host"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:52
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:70
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/conf_connection.py:47
|
||||
msgid "Port"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:62
|
||||
msgid "Send certificate signing request"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:80
|
||||
msgid "Get certificate from server"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:114
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:202
|
||||
msgid "Enter Hostname or IP adress"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:114
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:202
|
||||
msgid "Field \"Host\" Error!"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:119
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:207
|
||||
msgid "Enter Port"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:119
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:207
|
||||
msgid "Field \"Port\" Error!"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:146
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:218
|
||||
#, python-format
|
||||
msgid "Error code: %s"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:146
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:218
|
||||
msgid "Close. Connecting Error."
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:180
|
||||
msgid "This server can not sign certificate!"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:185
|
||||
#, python-format
|
||||
msgid "Your request id = %s"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:318
|
||||
msgid "filename = "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/CertificateClass.py:321
|
||||
msgid "file with ca certificates exists"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:38
|
||||
msgid "Tools"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:58
|
||||
msgid "Clear config"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:97
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:109
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:134
|
||||
msgid "Gui Tools"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:98
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:109
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:138
|
||||
msgid "Other Tools"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:112
|
||||
#, python-format
|
||||
msgid "In the %s tab has unsaved changes"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:114
|
||||
msgid "\tApply them?"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:156
|
||||
msgid "Select Color"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:186
|
||||
msgid "Path to bg Image"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:195
|
||||
msgid "Select repeat background"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:215
|
||||
msgid "Set opacity "
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:246
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:410
|
||||
msgid "Ok"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:251
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:415
|
||||
msgid "Apply"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:376
|
||||
msgid "Select Language"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:380
|
||||
msgid "English"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:380
|
||||
msgid "Russian"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/tools.py:393
|
||||
msgid "Path to Certificates"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/MainFrameResult.py:395
|
||||
#, python-format
|
||||
msgid "Percent = %s"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/MainFrameResult.py:463
|
||||
msgid "Send"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/DisplayMethod.py:120
|
||||
msgid "No Methods!"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/client_class.py:113
|
||||
msgid "Add certificate to trusted"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainframe.py:331
|
||||
msgid "Press for advanced settings."
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainframe.py:624
|
||||
msgid "Previous"
|
||||
msgstr ""
|
||||
|
||||
#: /var/calculate/mydir/source/spyder/cl-api-client/console/gui/mainframe.py:645
|
||||
msgid "Next"
|
||||
msgstr ""
|
||||
|
@ -0,0 +1,32 @@
|
||||
#!/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.
|
||||
|
||||
import sys
|
||||
from calculate.console.application.cl_client import main
|
||||
reload(sys)
|
||||
sys.setdefaultencoding("utf-8")
|
||||
|
||||
from calculate.lib.cl_lang import setLocalTranslate
|
||||
setLocalTranslate('calculate_console',sys.modules[__name__])
|
||||
|
||||
if __name__=='__main__':
|
||||
try:
|
||||
sys.exit(main())
|
||||
except KeyboardInterrupt:
|
||||
red = '\033[31m * \033[0m'
|
||||
print '\n'+red+_('Interrupted by user')
|
||||
sys.exit(1)
|
@ -0,0 +1,127 @@
|
||||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# setup.py --- Setup script for calculate-ldap
|
||||
|
||||
# Copyright 2010 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.
|
||||
|
||||
import os
|
||||
from os import path
|
||||
import glob
|
||||
import sys
|
||||
|
||||
import distutils
|
||||
from distutils.core import setup
|
||||
from distutils.command.install_data import install_data
|
||||
import distutils.command.build
|
||||
import distutils.command.install_egg_info
|
||||
|
||||
data_files = []
|
||||
|
||||
var_data_files = []
|
||||
|
||||
__version__ = "0.1"
|
||||
__app__ = "calculate-console"
|
||||
|
||||
locales = ("ru",'en')
|
||||
|
||||
class cl_console_data(install_data):
|
||||
def run (self):
|
||||
install_data.run(self)
|
||||
data_file = []
|
||||
fileNames = map(lambda x: path.split(x[0])[1], data_file)
|
||||
listNames = map(lambda x: filter(lambda y: y, x[0].split("/")),
|
||||
data_file)
|
||||
data_find = {}
|
||||
for i in range(len(fileNames)):
|
||||
listNames[i].reverse()
|
||||
data_find[fileNames[i]] =[listNames[i],data_file[i][1]]
|
||||
|
||||
for path in self.get_outputs():
|
||||
nameFile = path.split(path)[1]
|
||||
if nameFile in data_find.keys():
|
||||
data = data_find[nameFile][0]
|
||||
mode = data_find[nameFile][1]
|
||||
flagFound = True
|
||||
iMax = len(data)
|
||||
pathFile = path
|
||||
for i in range(iMax):
|
||||
if data[i] != path.split(pathFile)[1]:
|
||||
flagFound = False
|
||||
break
|
||||
pathFile = path.split(pathFile)[0]
|
||||
if flagFound:
|
||||
os.chmod(path, mode)
|
||||
|
||||
class build(distutils.command.build.build):
|
||||
def run (self):
|
||||
distutils.command.build.build.run(self)
|
||||
|
||||
def has_po( self ) :
|
||||
return len(glob.glob("ru/*.po")) > 0
|
||||
sub_commands = distutils.command.build.build.sub_commands + [
|
||||
('build_po',has_po),
|
||||
]
|
||||
|
||||
class empty_egg_info( distutils.command.install_egg_info.install_egg_info ):
|
||||
def run(self):
|
||||
pass
|
||||
|
||||
def cout(string):
|
||||
sys.stdout.write(string)
|
||||
sys.stdout.flush()
|
||||
|
||||
class build_po( distutils.core.Command ) :
|
||||
description = "build translation files"
|
||||
user_options = []
|
||||
|
||||
def initialize_options( self ) :
|
||||
pass
|
||||
def finalize_options( self ) :
|
||||
pass
|
||||
|
||||
def run( self ) :
|
||||
#self.mkpath("build")
|
||||
#build.run( self )
|
||||
for locale in locales:
|
||||
localepath = path.join("build",locale,"LC_MESSAGES")
|
||||
self.mkpath(localepath)
|
||||
self.mkpath(locale)
|
||||
for po in glob.glob("%s/*.po"%locale):
|
||||
cmd = "msgfmt -c -o %s/%s %s" % \
|
||||
(localepath,path.basename(po)[:-2]+'mo',po)
|
||||
cout( cmd + "\n" )
|
||||
os.system(cmd)
|
||||
|
||||
setup(
|
||||
name = __app__,
|
||||
version = __version__,
|
||||
description = "client for WSDL server",
|
||||
author = "Calculate Ltd.",
|
||||
author_email = "support@calculate.ru",
|
||||
url = "http://calculate-linux.org",
|
||||
license = "http://www.apache.org/licenses/LICENSE-2.0",
|
||||
|
||||
data_files = data_files + [
|
||||
(path.join('/usr/share/locale',locale,"LC_MESSAGES"),
|
||||
glob.glob(path.join("build",locale,"LC_MESSAGES/*.mo")))
|
||||
for locale in locales ],
|
||||
|
||||
package_dir = {'calculate.console': "console"},
|
||||
packages = ['calculate.console','calculate.console.variables',
|
||||
'calculate.console.application'],
|
||||
scripts = ['./scripts/cl-console','./scripts/cl-consoled'],
|
||||
cmdclass={'cl_console_data': cl_console_data,'build': build, \
|
||||
'build_po':build_po, 'install_egg_info':empty_egg_info}
|
||||
)
|
Loading…
Reference in new issue