Weak password detection service implementation (multi-process, multi-thread, holy)

weak.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import global_par
from global_par import *
from weakcheck_tool import WEAK_CHECK
 
import signal
import os
import errno
import time
import logging
importsys
import json
import multiprocessing #pid
import stomp
from stomp import ConnectionListener
import ConfigParser
 
 
hand_count = 0
task_list = {}
task_return_dic = {"type":6, "status":0, "task_id":"0", "tool":"weak", "data":[ ]}
 
 
def pid_exists(pid):
    """Check whether pid exists in the current process table.
    UNIX only.
    """
    if pid < 0:
        return False
    if pid == 0:
        raise ValueError('invalid PID 0')
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            return False
        elif err.errno == errno.EPERM:
            return True
        else:
            raise
    else:
        return True
 
def start_weakchecktool(PipePar):
weak_check = WEAK_CHECK(PipePar)
weak_check.run()
time.sleep(1)
return
 
 
class MyListener(object):
def on_error(self, headers, message):
logging.error('received an error message is :%s' % message)
def on_message(self, headers, message):
#logging.warning("received a message is : %s"%message)
try:
TextData = json.loads(message)
exceptException,e:
logging.error("load except:%s",e)
return
#logging.warning("%s", TextData)
\t\t
global task_return_dic
task_id = TextData["task_id"]
task_return_dic["task_id"] = TextData["task_id"]
global_par.MQ.send(body=json.dumps(task_return_dic),destination=global_par.MQ_SEND)
\t\t
if TextData.has_key('task_id'):
if task_id in task_list.keys():
#task_list[task_id][1].send(TextData)
for line in open("/tmp/proc_pid.txt"):
n_pid = int(line.strip())
if pid_exists(n_pid):
os.kill(n_pid, 9)
os.remove("/tmp/proc_pid.txt")
os.kill(task_list[task_id], 9)
\t\t\t\t
else:
PipePar = multiprocessing.Pipe(True)
p = multiprocessing.Process(target=start_weakchecktool, args=(PipePar,))
PipePar[1].send(TextData)
p.daemon = True
p.start()
task_list[task_id]=p.pid
#task_list[task_id]=PipePar
else:
logging.warning("send message no task_id")
return
time.sleep(1)
\t
return
 
\t
def init_mq():
try:
config=ConfigParser.ConfigParser()
config.read(global_par.product_path + global_par.AUTH_FILE)
 
global_par.CONNECT_HOST = str(config.get('ActiveMq','active_addr'))
global_par.CONNECT_PORT = int(config.get('ActiveMq','active_port'))
global_par.USER = str(config.get('ActiveMq','active_user'))
global_par.PASSWORD = str(config.get('ActiveMq','active_passwd'))
#logging.warning("%s %s %s %s", global_par.CONNECT_HOST, global_par.CONNECT_PORT, global_par.USER, global_par.PASSWORD)
"""
global_par.CONNECT_HOST = '127.0.0.1'
global_par.CONNECT_PORT = 61613
global_par.USER = 'admin'
global_par.PASSWORD = 'admin'
"""
except IOError,e:
logging.error(str(e))
\t\t
\t
def run_server():
while True:
global_par.MQ.set_listener('', MyListener())
if not global_par.MQ.is_connected():
try:
global_par.MQ.start()
if global_par.USER == 'admin' or global_par.PASSWORD == 'admin':
global_par.MQ.connect()
else:
global_par.MQ.connect(global_par.USER,global_par.PASSWORD)
global_par.MQ.subscribe(destination=global_par.MQ_LISTENER, id=7)
# logging.warning("ActiveMQ connect success")
exceptException,e:
logging.error("ActiveMQ connect failed: %s" % e)
time.sleep(2)
time.sleep(2)
global_par.MQ.disconnect()
 
 
def daemon(childpid):
    while True:
        try:
            apid, status= os.wait()
            if childpid != apid:
                logging.error('failed: find unknown child')
                continue
            else:
                logging.error('fatal:Child %d exit with state'%(apid))
                return
        except OSError as e:
            logging.error(e)
            continue
 
 
def quitdaemon(sig_num, addtion):
logging.error('the daemon is to be stopped!')
global task_return_dic
\t
global_par.MQ.set_listener('', MyListener())
if not global_par.MQ.is_connected():
global_par.MQ.start()
if global_par.USER == 'admin' or global_par.PASSWORD == 'admin':
global_par.MQ.connect()
else:
global_par.MQ.connect(global_par.USER,global_par.PASSWORD)
task_return_dic["status"] = -1
global_par.MQ.send(body=json.dumps(task_return_dic),destination="WEAK_RESULT")
sys.exit(1)
   
def alarm_handle():
    hand_count + =1
 
 
def console_out(logFilename):
if len(sys.argv)>1:
log_level = sys.argv[1]
else :
log_level = "warning"
if cmp(log_level.lower(), "debug")==0:
log_level = "DEBUG"
elif cmp(log_level.lower(),"info") == 0:
log_level = "INFO"
elif cmp(log_level.lower(), "warning")==0 or cmp(log_level.lower(), "warn")==0 :
log_level = "WARNING"
elif cmp(log_level.lower(),"error") == 0:
log_level = "ERROR"
elif cmp(log_level.lower(),"critical") == 0:
log_level = "CRITICAL"
else :
log_level = "WARNING"
    #print log_level
logging.basicConfig(level = logging.DEBUG,format = '%(levelname)s %(asctime)s %(filename)s[line:%(lineno)d] : %(message)s', datefmt = \ '%Y-%m-%d %a %H:%M:%S', filename = logFilename, filemode = 'a + ')
 
 
def start_server():
config_path = sys.argv[1]
global_par.product_path = config_path
if os.path.isfile("/etc/password.txt"):
os.remove(global_par.product_path + "/log/log.log")
\t
init_mq()
global_par.MQ = stomp.Connection([(global_par.CONNECT_HOST,global_par.CONNECT_PORT)])
console_out(global_par.product_path + "/log/log.log")
\t
signal.signal(signal.SIGTTOU, signal.SIG_IGN)
signal.signal(signal.SIGTTIN, signal.SIG_IGN)
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
signal.signal(signal.SIGTERM, quitdaemon)
 
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
signal.signal(signal.SIGALRM, alarm_handle)
\t
pid = os.fork()
if pid == 0:
while True:
pid = os.fork()
if pid > 0:
daemon(pid)
elif pid < 0:
logging.critical('failed to fork a new process!')
sys.exit(-1)
else:
break
time.sleep(1)
#logging.warning( "begin run sever!")
run_server()
elif pid > 0:
sys.exit(0)
else:
logging.critical("Error to fork a new process!")
sys.exit(-1)
 
 
if __name__ == "__main__":
start_server()

weakcheck_tool.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
 
from __future__ import division
import global_par
from global_par import *
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
import os
importsys
import logging
import subprocess #Popen
import threading
import multiprocessing #pid
import time
import re
import json
import stomp
from stomp import ConnectionListener
import urllib2
#import traceback #log
 
 
 
UserPasswordXml = "/conf/UserPasswordConfigure.xml"
ComboUserPasswordXml = "/conf/ComboUserPasswordConfigure.xml"
CustomUserPasswordXml = "/conf/CustomUserPasswordConfigure.xml"
 
GlobalDicPath = "/tmp/"
 
GlobalProtocolDic = {"smb":0, "telnet":1, "ssh":2, "mysql":3, "oracle":4, "mssql":5 , "pop3":6, "ftp":7, "rdp":8, "postgres":9, "snmp":10, "smtp":11}
 
task_success_list = []
task_ips_list = []
n_percentage = 0
n_return_percentage = 0
thread_flag = 0
 
task_return_dic = {"type":6, "status":0, "task_id":"0", "tool":"weak", "data":[ ]}
task_progress_dic = {"type":5, "task_id":"0", "tool":"weak", "data":{"status":0, "progress":0.00}}
 
 
 
 
"""
SMB: type 0
TELNET: type 1
SSH: type 2
MYSQL: type 3
ORALCE: type 4
MSSQL: type 5
POP3: type 6
FTP: type 7
RDP: type 8
POSTGRES: type 9
SNMP: type 10
SMTP: type 11
"""
class CREATE_DIC_PAR(object):
def create_weak_dic(self, protocolName, task_id, dic_type, dic_data):
list_combo_dic = []
dict_user = []
dict_pwd = []
if type(dic_data).__name__ == 'list':
list_combo_dic = dic_data
elif type(dic_data).__name__ == 'dict':
dict_user = dic_data["userName"]
dict_pwd = dic_data["userPassword"]
\t
if dic_type == "0":
dic_combo_path = GlobalDicPath + task_id + protocolName + "combo.txt"
f_combo = open(dic_combo_path, "w + ")
for i in range(0, len(list_combo_dic)):
f_combo.write(list_combo_dic[i])
f_combo.write("\\
")
f_combo.close()
elif dic_type == "1":
dic_gb_user_path = GlobalDicPath + task_id + protocolName + "users.txt"
f_gb_user = open(dic_gb_user_path, "w + ")
for i in range(0, len(dict_user)):
f_gb_user.write(dict_user[i])
f_gb_user.write("\\
")
f_gb_user.close()
\t\t\t
dic_gb_pwd_path = GlobalDicPath + task_id + protocolName + "passwords.txt"
f_gb_pwd = open(dic_gb_pwd_path, "w + ")
for i in range(0, len(dict_pwd)):
f_gb_pwd.write(dict_pwd[i])
f_gb_pwd.write("\\
")
f_gb_pwd.close()
elif dic_type == "2":
dic_custom_user_path = GlobalDicPath + task_id + protocolName + "customusers.txt"
f_custom_user = open(dic_custom_user_path, "w + ")
for i in range(0, len(dict_user)):
f_custom_user.write(dict_user[i])
f_custom_user.write("\\
")
f_custom_user.close()
\t\t\t
dic_custom_pwd_path = GlobalDicPath + task_id + protocolName + "custompasswords.txt"
f_custom_pwd = open(dic_custom_pwd_path, "w + ")
for i in range(0, len(dict_pwd)):
f_custom_pwd.write(dict_pwd[i])
f_custom_pwd.write("\\
")
f_custom_pwd.close()
\t
 
def CreateComboWeakpasswordDic(self, protocolName, task_id, ntype):
#xmlFilePath = os.path.abspath(ComboUserPasswordXml)
#logging.warning("%s", xmlFilePath)
 
try:
xmlFilePath = global_par.product_path + ComboUserPasswordXml
tree = ET.parse(xmlFilePath)
root = tree.getroot()
except Exception as e:
logging.error("parse ComboUserPasswordConfigure.xml:%s" % e)
sys.exit()
 
dicComboPath = GlobalDicPath + task_id + protocolName + "combo.txt"
fComboDic = open(dicComboPath, "w + ")
for text in range(0, len(root[ntype][0])):
fComboDic.write(root[ntype][0][text].text)
fComboDic.write("\\
")
fComboDic.close()
\t\t
\t\t
def CreateWeakpasswordDic(self, protocolName, task_id, ntype):
#xmlFilePath = os.path.abspath(UserPasswordXml)
#logging.warning("%s", xmlFilePath)
 
try:
xmlFilePath = global_par.product_path + UserPasswordXml
tree = ET.parse(xmlFilePath)
root = tree.getroot()
except Exception as e:
logging.error("parse UserPasswordConfigure.xml:%s" % e)
sys.exit()
 
UserDicPath = GlobalDicPath + task_id + protocolName + "users.txt"
fUserDic = open(UserDicPath, "w + ")
for users in range(0, len(root[ntype][0])):
fUserDic.write(root[ntype][0][users].text)
fUserDic.write("\\
")
fUserDic.close()
 
PasswordDicPath = GlobalDicPath + task_id + protocolName + "passwords.txt"
fPasswordDic = open(PasswordDicPath, "w + ")
for passwords in range(0, len(root[ntype][1])):
fPasswordDic.write(root[ntype][1][passwords].text)
fPasswordDic.write("\\
")
fPasswordDic.close()
\t\t
\t\t
def CreateCustomWeakpasswordDic(self, protocolName, task_id, ntype):
#xmlFilePath = os.path.abspath(CustomUserPasswordXml)
#logging.warning("%s", xmlFilePath)
 
try:
xmlFilePath = global_par.product_path + CustomUserPasswordXml
tree = ET.parse(xmlFilePath)
root = tree.getroot()
except Exception as e:
logging.error("parse UserPasswordConfigure.xml:%s" % e)
sys.exit()
 
UserDicPath = GlobalDicPath + task_id + protocolName + "customusers.txt"
fUserDic = open(UserDicPath, "w + ")
for users in range(0, len(root[ntype][0])):
fUserDic.write(root[ntype][0][users].text)
fUserDic.write("\\
")
fUserDic.close()
 
PasswordDicPath = GlobalDicPath + task_id + protocolName + "custompasswords.txt"
fPasswordDic = open(PasswordDicPath, "w + ")
for passwords in range(0, len(root[ntype][1])):
fPasswordDic.write(root[ntype][1][passwords].text)
fPasswordDic.write("\\
")
fPasswordDic.close()
\t\t
\t\t
def CreateHosts(self, task_id, ips):
global task_ips_list
HostPath = GlobalDicPath + task_id + "hosts.txt"
 
fHosts = open(HostPath, "w + ")
if '-' in ips:
strstart = re.findall(r"^(. + ?)-", ips)[0]
stretch = re.findall("-(. + ?)$", ips)[0]
num = strstart.rfind('.')
strTest = strstart[:num + 1]
nstart = int(strstart[num + 1:])
nend = int(strend[num + 1:])
 
for i in range(nstart, nend + 1):
testIP = strTest + str(i)
task_ips_list.append(testIP)
fHosts.write(testIP)
fHosts.write("\\
")
else:
task_ips_list.append(ips)
fHosts.write(ips)
fHosts.write("\\
")
fHosts.close()
\t\t
return HostPath
 
\t\t
 
class WEAK_CHECK:
def __init__(self, PipePar):
self.PipePar = PipePar
self.create_dic = CREATE_DIC_PAR()
\t\t
\t\t
def return_progress(self, status, n_return_percentage):
#task_progress_dic = {"type":5, "task_id":0, "data":{"status":0, "progress":0}}
global task_progress_dic
try:
task_progress_dic["data"]["status"] = status
task_progress_dic["data"]["progress"] = n_return_percentage
global_par.MQ.send(body=json.dumps(task_progress_dic),destination=global_par.MQ_SEND)
except Exception as e:
logging.error("return_progress: %s" % e)
sys.exit()
\t\t
def return_result(self, status):
global task_return_dic
global task_success_list
\t
task_data = []
task_data_dic = {"ip":"", "weak":[]}
task_return_dic["status"] = status
\t\t
try:
if len(task_success_list) == 0:
task_data.append(task_data_dic)
task_return_dic["data"] = task_data
#logging.warning("return_result: %s", task_return_dic)
global_par.MQ.send(body=json.dumps(task_return_dic),destination=global_par.MQ_SEND)
else:
for i in range(0, len(task_success_list)):
task_data_dic = {"IP":"", "weak":[]}
weak_list= []
task_list_dic = {}
\t\t\t\t\t\t\t\t\t\t
task_list_dic["protocol"] = task_success_list[i]["protocol"]
task_list_dic["user"] = task_success_list[i]["user"]
task_list_dic["password"] = task_success_list[i]["password"]
task_list_dic["flag"] = task_success_list[i]["flag"]
weak_list.append(task_list_dic)
\t\t\t\t\t
task_data_dic["IP"] = task_success_list[i]["IP"]
task_data_dic["weak"] = weak_list
task_data.append(task_data_dic)
\t\t\t\t\t
result = []
newdata = []
addin = {}
origin_ip = [task_data[0]['IP']]
for ip in origin_ip:
for item in task_data:
if item['IP'] == ip:
addinfo = item["weak"]
newdata.extend(addinfo)
addin = {"IP":ip, "weak":newdata}
else:
if item['IP'] not in origin_ip:
origin_ip.append(item['IP'])
result.append(addin)
#task_data.append(addin)
newdata = []
\t\t\t\t\t
task_return_dic["data"] = result
global_par.MQ.send(body=json.dumps(task_return_dic),destination=global_par.MQ_SEND)
except Exception as e:
logging.error("return_result: %s" % e)
sys.exit()
\t\t\t
\t\t
def progress(self, str):
global thread_flag
while True:
time.sleep(10)
global n_return_percentage
if thread_flag == 1:
break
self.return_result(0)
self.return_progress(0, n_return_percentage)
thread_flag = 0
\t\t\t\t\t
\t\t\t
def StartCheckWeak(self, task_id, dic_protocol, task_sleep):
global n_percentage
global n_return_percentage
global task_success_list
global task_ips_list
\t
try:
weakProtocol = dic_protocol["protocolName"]
weakPort = dic_protocol["port"]
dicType = dic_protocol["dictionaryType"]
#print weakProtocol, weakPort, dicType
 
weakdic = ""
\t\t\t
weakIP = ""
weakUser = ""
weakPassword = ""
listtxt = []
medusaCMD = ""
 
\t\t\t
if weakProtocol == "postgresql":
weakProtocol = "postgres"
weakdic = weakProtocol
 
if dicType == "0":
#self.create_dic.CreateComboWeakpasswordDic(weakdic, task_id, GlobalProtocolDic[weakdic])
self.create_dic.create_weak_dic(weakdic, task_id, dicType, dic_protocol["result"])
medusaCMD = "medusa -H " + GlobalDicPath + task_id + "hosts.txt " + "-C " + GlobalDicPath + task_id + weakdic + "combo.txt" + " -n " + weakPort
listtxt.append(GlobalDicPath + task_id + weakdic + "combo.txt")
#logging.warning("combo--------------------------------------------- --")
elif dicType == "1":
#self.create_dic.CreateWeakpasswordDic(weakdic, task_id, GlobalProtocolDic[weakdic])
self.create_dic.create_weak_dic(weakdic, task_id, dicType, dic_protocol["result"])
medusaCMD = "medusa -H " + GlobalDicPath + task_id + "hosts.txt " + "-U " + GlobalDicPath + task_id + weakdic + "users.txt" + " -P " + GlobalDicPath + task_id + weakdic + "passwords.txt" + " -n " + weakPort
listtxt.append(GlobalDicPath + task_id + weakdic + "users.txt")
listtxt.append(GlobalDicPath + task_id + weakdic + "passwords.txt")
#logging.warning("GB--------------------------------------------- ------")
elif dicType == "2":
#self.create_dic.CreateCustomWeakpasswordDic(weakdic, task_id, GlobalProtocolDic[weakdic])
self.create_dic.create_weak_dic(weakdic, task_id, dicType, dic_protocol["result"])
medusaCMD = "medusa -H " + GlobalDicPath + task_id + "hosts.txt " + "-U " + GlobalDicPath + task_id + weakdic + "customusers.txt" + " -P " + GlobalDicPath + task_id + weakdic + "custompasswords.txt" + " -n " + weakPort
listtxt.append(GlobalDicPath + task_id + weakdic + "customusers.txt")
listtxt.append(GlobalDicPath + task_id + weakdic + "custompasswords.txt")
#logging.warning("custom--------------------------------------------- --")
if weakProtocol == "rdp":
medusaCMD + = " -b -f -r " + task_sleep
else:
medusaCMD + = " -e ns -b -L -T 4 -f -r " + task_sleep
\t\t\t
if weakProtocol == "smb":
medusaCMD + = "-M smbnt"
elif weakProtocol == "oracle":
medusaCMD + = " -m TYPE:STDIN -m PROG:" + global_par.product_path + "/conf/" + "oracle.pl -m ARGS:"%H %U ORCL\\ "" + " -M wrapper"
else:
medusaCMD + = " -M " + weakProtocol
\t\t\t\t
medusaCMD = "cd " + global_par.product_path + " & amp; & amp; ./bin/" + medusaCMD
logging.debug("medusaCMD: %s", medusaCMD)
\t\t\t
proc = subprocess.Popen(medusaCMD, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True)
proc_pid_path = GlobalDicPath + "proc_pid.txt"
f_proc_pid = open(proc_pid_path, "a + ")
popen_pid = proc.pid
f_proc_pid.write(str(popen_pid))
f_proc_pid.write("\\
")
f_proc_pid.close()
\t\t\t
for line in iter(proc.stdout.readline, 'b'):
#logging.debug("line: %s", line)
if 'Cannot connect' in line and 'retrying' in line:
continue
elif 'failed to connect' in line or 'Failed to connect' in line:
#print err #on 291.123.321.33\\

str_err = line.replace('\\
','')
weakIP = re.findall(r"on\s(.*)", str_err)
\t\t\t\t\t
task_no_connect = {}
task_no_connect["IP"] = weakIP[0]
task_no_connect["protocol"] = weakProtocol
task_no_connect["user"] = ""
task_no_connect["password"] = ""
task_no_connect["flag"] = -1
task_success_list.append(task_no_connect)
n_return_percentage + = n_percentage
 
if subprocess.Popen.poll(proc) is None:
if line == '':
break
 
weakIP = re.findall(r"Host:\s(. + ?)\s", line)
\t\t\t\t
if 'SUCCESS' in line:
weakUser = re.findall(r"User:\s(. + ?)\s", line)[0]
if 'Password: ' in line:
weakPassword = ""
else:
weakPassword = re.findall(r"Password:\s(. + ?)\s", line)[0]
\t\t\t\t\t
task_success = {}
task_success["IP"] = weakIP[0]
task_success["protocol"] = weakProtocol
task_success["user"] = weakUser
task_success["password"] = weakPassword
task_success["flag"] = 1
task_success_list.append(task_success)
n_return_percentage + = n_percentage
 
proc.stdout.close()
task_tmp_list = task_success_list
 
tmp_list = []
for i in range(0, len(task_tmp_list)):
if task_tmp_list[i]["protocol"] == weakProtocol:
tmp_list.append(task_tmp_list[i]["IP"])
\t\t\t
if len(tmp_list) == 0:
for i in range(0, len(task_ips_list)):
task_success = {}
task_success["IP"] = task_ips_list[i]
task_success["protocol"] = weakProtocol
task_success["user"] = ""
task_success["password"] = ""
task_success["flag"] = 0
task_success_list.append(task_success)
else:
for i in range(0, len(task_ips_list)):
tmp_num = 0
for j in range(0, len(tmp_list)):
if task_ips_list[i] == tmp_list[j]:
tmp_num = 0
break
else:
tmp_num = 1
if tmp_num == 1:
task_success = {}
task_success["IP"] = task_ips_list[i]
task_success["protocol"] = weakProtocol
task_success["user"] = ""
task_success["password"] = ""
task_success["flag"] = 0
task_success_list.append(task_success)
\t\t\t\t\t\t
for i in range(0, len(listtxt)):
os.remove(listtxt[i])
except Exception as e:
#logging.warning ("WEAK_CHECK.StartCheckWeak:%s" % traceback.print_exc())
logging.error("WEAK_CHECK.StartCheckWeak:%s" % e)
sys.exit()
\t
\t\t
def run(self):
try:
global task_progress_dic
global task_return_dic
\t\t
HostPath = ""
 
task_type = -1
task_id = ""
ips = ""
task_sleep = ""
 
while True:
TextData = self.PipePar[0].recv()
if TextData is None:
break
else:
task_type = TextData["type"]
task_id = TextData["task_id"]
 
if task_type == 0:
#logging.warning("task_type: %s", task_type)
ips = TextData["data"]["ips"]
task_sleep = TextData["data"]["sleep"]
 
HostPath = self.create_dic.CreateHosts(task_id, ips.encode("UTF-8"))
\t\t\t\t\t\t
task_return_dic["task_id"] = TextData["task_id"]
task_progress_dic["task_id"] = TextData["task_id"]
\t\t\t
listProtocolPar = []
nNum = len(TextData["data"]["protocol"])
for i in range(0, nNum):
data = TextData["data"]["protocol"][i]
keys = list(data.keys()) #mysql dic
values = list(data.values()) #1433 0
listProtocolPar.append(keys + values)
\t\t\t
#logging.warning("ProtocolList: %s", len(listProtocolPar))
\t\t\t\t\t\t
global n_percentage
n_percentage = round(100/len(listProtocolPar)/len(task_ips_list), 2)
#print "satrt:", n_percentage
\t\t\t\t\t\t
threads = []
list_curl_post = []
for i in range(0, len(listProtocolPar)):
dic_curl_post = {"dictionaryType":"", "protocolName":"", "port":""}
\t\t\t\t\t\t\t
if listProtocolPar[i][0].encode("UTF-8").lower() == "dic":
dic_curl_post["protocolName"] = listProtocolPar[i][1].encode("UTF-8").lower()
dic_curl_post["dictionaryType"] = listProtocolPar[i][2].encode("UTF-8")
dic_curl_post["port"] = listProtocolPar[i][3].encode("UTF-8")
else:
dic_curl_post["protocolName"] = listProtocolPar[i][0].encode("UTF-8").lower()
dic_curl_post["port"] = listProtocolPar[i][2].encode("UTF-8")
dic_curl_post["dictionaryType"] = listProtocolPar[i][3].encode("UTF-8")
list_curl_post.append(dic_curl_post)
\t\t\t\t\t\t
headers = {'Content-Type': 'application/json'}
url= "http://" + global_par.CONNECT_HOST + "/ipc_moudle/weakDictionary/weakDictionaryDatas"
req = urllib2.Request(url=url, data=json.dumps(list_curl_post), headers=headers)
res = urllib2.urlopen(req)
res = res.read()
res_data = json.loads(res)
if not res_data["flag"]:
logging.error("get dic error")
task_progress_dic["data"]["status"] = -1
task_return_dic["status"] = -1
break
else:
for i in range(0, len(res_data["data"])):
t = threading.Thread(target=self.StartCheckWeak, args=(task_id, res_data["data"][i], task_sleep))
t.setDaemon(True)
threads.append(t)
t.start()
\t\t\t\t\t\t\t
thread_progress = threading.Thread(target=self.progress, args=(task_id,))
thread_progress.setDaemon(True)
thread_progress.start()
\t\t\t
for i in range(0, len(threads)):
threads[i].join()
\t\t\t
self.PipePar[1].send(None)
elif task_type == 4:
task_return_dic["task_id"] = TextData["task_id"]
task_progress_dic["task_id"] = TextData["task_id"]
self.PipePar[1].send(None)
os.remove(HostPath)
\t\t\t
global thread_flag
thread_flag = 1
self.return_result(1)
self.return_progress(1, 100)
except Exception as e:
#logging.warning ("WEAK_CHECK.run: %s" % traceback.print_exc())
logging.error("WEAK_CHECK.run: %s" % e)
sys.exit()

global_par.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
 
global MQ
global CONNECT_HOST
global CONNECT_PORT
global USER
global PASSWORD
 
 
 
globalAUTH_FILE
AUTH_FILE = "/conf/weak.conf"
 
global MQ_LISTENER
MQ_LISTENER = "WEAK_TASK"
 
global MQ_SEND
MQ_SEND = "WEAK_RESULT"
 
global product_path

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeHomepageOverview 387167 people are learning the system