File: //bin/bclinux-license
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2017 BigCloud Enterprise Linux, Inc.
# Authors: liujing<liujing@cmss.chinamobile.com>
import sys, getopt
import os
import gettext
import io
import subprocess
import socket
import urllib.request as urllib2
import urllib.error
from M2Crypto import RSA
import hashlib
import base64
import json
import configparser
# Calling the translation module
t = gettext.translation("demo", "/usr/share/locale", fallback=True)
_ = t.gettext
error_info = _("Error: please 'bclinux-license -h' for more information.")
print_info_1 = _("usage : bclinux-license [option] [file] ...")
print_info_2 = _("option GNU LONG option meaning")
print_info_3 = _("-h,-? --help display help information")
print_info_4 = _("-s --status display authorization status")
print_info_5 = _("-i --import inject license")
print_info_6 = _("-g --generate display machine code")
print_info_7 = _("-c --register-client <token> register as client")
print_info_8 = _("-p --register-proxy-server <token> register as proxy server")
print_info_9 = _("-d --disregister disregister client or proxy server")
print_info_10 = _("-e --check-env check environment")
pubkey_path = "/etc/bclinux/bc_yum_pub.key"
pub_key = RSA.load_pub_key(pubkey_path)
_BCLINUX_URL = 'http://mirrors.cmecloud.cn/'
_REGISTER_URL = '{uri}register/'.format(uri=_BCLINUX_URL)
_DIS_REGISTER_URL = '{uri}disregister/'.format(uri=_BCLINUX_URL)
global yum_config
# -----------------------------------
def load_config(configfile):
config = configparser.ConfigParser()
if not os.path.exists(configfile):
print("%s config file not found!" % configfile)
exit(1)
config.read(configfile)
return config
def findBaseUrl():
yum_config = load_config("/etc/yum.conf")
try:
base_url = yum_config.get('main', 'yum_base_url')
if base_url != "":
global _BCLINUX_URL
global _REGISTER_URL
global _DIS_REGISTER_URL
_BCLINUX_URL = base_url
_REGISTER_URL = '{uri}register/'.format(uri=base_url)
_DIS_REGISTER_URL = '{uri}disregister/'.format(uri=base_url)
except Exception as e:
return
def check_net():
net_command = [
"curl -X GET -I -m 10 -o /dev/null -s -w {code} {uri}bclinux/".format(code="%{http_code}", uri=_BCLINUX_URL)]
ret = subprocess.getoutput(net_command)
if ret != "200":
print(_("Check whether the network is normal and the internet can be accessed"))
sys.exit()
def check_license_online():
license_command = ['cat /etc/bclinux/license']
license = subprocess.getoutput(license_command)
if license == "":
print("system not register")
sys.exit()
try:
request = urllib2.Request(url=_BCLINUX_URL)
request.add_header('BCLINUX-AUTH-ID', license)
response = urllib2.urlopen(request, timeout=5)
response = response.read()
response = response.decode('utf-8').strip()
print("check license online result:", response)
return response
except Exception as e:
print("check license online error")
sys.exit()
def check_env():
print(_("Start check environment"))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 80
try:
result = sock.connect_ex((host, port))
if result == 0:
print(_("port 80 is already in use"))
sys.exit()
with open('/etc/os-release', 'r') as file:
for line in file:
if line.startswith("VERSION_ID="):
distro_id = line.split('=')[1].strip().strip('""')
break
flag = "22.10" == distro_id
if not flag:
print(_("The current version is not the specified, Please use [BigCloud Enterprise Linux For Euler release 22.10 LTS]"))
sys.exit()
check_net()
except Exception as e:
print(_(f"error:{e}"))
sys.exit()
finally:
sock.close()
print(_("Environment check pass"))
def install_openresty():
print(_("Install openresty"))
command = ['yum', 'install', '-y', 'openresty']
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if process.returncode != 0:
print(_(f"Install openresty fail: {error.decode()}"))
sys.exit()
command = ['yes |cp /etc/bclinux/nginx.conf /usr/local/openresty/nginx/conf/']
subprocess.getoutput(command)
print(_("Install openresty success"))
def run_openresty():
command = ['systemctl', 'start', 'openresty']
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if process.returncode != 0:
print(_(f"Start openresty fail:{error.decode()}"))
sys.exit()
print(_("Start openresty success"))
def write_role(role):
process = subprocess.Popen('echo %s > /etc/bclinux/role' % role, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, error = process.communicate()
def encrypt(body):
signer = json.dumps(body)
ctxt = pub_key.public_encrypt(bytes(signer, 'UTF-8'), RSA.pkcs1_padding)
ctxt64 = base64.b64encode(ctxt)
return ctxt64
def req_license(token, role):
command = ['/usr/bin/sys-id']
machine_code = subprocess.getoutput(command)
command = ['uname -r']
os_uname = subprocess.getoutput(command)
req_license_real(token, role, machine_code, os_uname)
def req_license_real(token, role, machine_code, os_uname):
try:
request = urllib2.Request(url=_REGISTER_URL)
body = {
"token": token,
"machineCode": machine_code,
"role": role,
"uname": os_uname
}
encrypter = encrypt(body)
request.add_header('encrypter', encrypter)
response = urllib2.urlopen(request, timeout=5)
response = response.read()
response = response.decode('utf-8').strip()
result = json.loads(response)
state = result['state']
if state == 0:
message = result['message']
print(_(f"Register fail:{message}"))
sys.exit()
license = result['license']
result = subprocess.run('echo %s > /etc/bclinux/license' % license, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except Exception as e:
print(_(f"error:{e}"))
sys.exit()
def register_client(token):
role_command = ['cat /etc/bclinux/role']
role = subprocess.getoutput(role_command)
if role == "server":
print(_("current is proxy server, please disregister first"))
sys.exit()
req_license(token, 1)
write_role("client")
print(_("Client register success"))
def register_server(token):
check_env()
req_license(token, 2)
install_openresty()
run_openresty()
write_role("server")
print(_("Proxy server register success"))
def unregister():
command = ['/usr/bin/sys-id']
machine_code = subprocess.getoutput(command)
try:
request = urllib2.Request(url=_DIS_REGISTER_URL)
body = {
"machineCode": machine_code
}
encrypter = encrypt(body)
request.add_header('encrypter', encrypter)
response = urllib2.urlopen(request, timeout=5)
response = response.read()
response = response.decode('utf-8').strip()
result = json.loads(response)
state = result['state']
if state == 0:
message = result['message']
print(_(f"Register fail:{message}"))
sys.exit()
role_command = ['cat /etc/bclinux/role']
role = subprocess.getoutput(role_command)
role_command = ['echo ''> /etc/bclinux/role']
subprocess.getoutput(role_command)
license_command = ['echo ''> /etc/bclinux/license']
subprocess.getoutput(license_command)
if role == "server":
rpm_command = ["rpm -e openresty"]
subprocess.getoutput(rpm_command)
except Exception as e:
print(_(f"error:{e}"))
sys.exit()
print(_("Disregister success"))
def main(argv):
# Chinese and English display
try:
# Command line parameter selection
opts, args = getopt.getopt(argv, "hsi:gc:p:den?", ["help", "status", "infile", "generate", "register-client=",
"register-proxy-server=", "disregister", "check-env",
"status-online", "?"])
except getopt.GetoptError:
print(error_info)
sys.exit(2)
findBaseUrl()
for opt, arg in opts:
if opt in ("-h", "-?"):
print(print_info_1)
print(print_info_2)
print(print_info_3)
print(print_info_4)
print(print_info_5)
print(print_info_6)
print(print_info_7)
print(print_info_8)
print(print_info_9)
print(print_info_10)
sys.exit()
# "bclinux-license -s": system authorization status
elif opt in ("-s", "--status"):
os.system("/usr/bin/license-manager")
sys.exit()
# "bclinux-license -i": inject authorization code into the system
elif opt in ("-i", "--infile"):
path = os.getcwd()
f1 = io.open(sys.argv[2], mode='r', encoding='utf-8')
license = f1.read()
f1.close()
f2 = io.open('/etc/bclinux/license', mode='wb')
f2.write(license.encode('utf-8'))
f2.close()
sys.exit()
# "bclinux-license -g": get the authorization code for the system
elif opt in ("-g", "--generate"):
os.system("/usr/bin/sys-id")
sys.exit()
elif opt in ("-c", "--register-client"):
register_client(arg)
sys.exit()
elif opt in ("-p", "--register-proxy-server"):
register_server(arg)
sys.exit()
elif opt in ("-d", "--disregister"):
unregister()
sys.exit()
elif opt in ("-e", "--check-env"):
check_env()
sys.exit()
elif opt in ("-n", "--status-online"):
check_license_online()
sys.exit()
print(_("please 'bclinux-license -h' for more information."))
if __name__ == "__main__":
main(sys.argv[1:])