示例#1
0
 def __init__(self, user, log=None):
     self.safeid = user.safeid
     self.req = user.req
     if log is None:
         self.log = Logging(user.username)
     else:
         self.log = log
示例#2
0
	def __init__(self, user, useType, sellType, log = None):
		self.safeid = user.safeid
		self.req = user.req
		self.useType = useType
		self.sellType = sellType
		if log is None:
			self.log = Logging(user.username)
		else:
			self.log = log
示例#3
0
 def __init__(self, username, password, log=None):
     self.loginStatus = False
     self._safeid = None
     self.username = username
     self.password = password
     self.req = KfReq()
     if log is None:
         self.log = Logging(username)
     else:
         self.log = log
示例#4
0
    def __init__(self, bebop):
        Logging.__init__(self)

        self.running = True

        self._tick_rate = 0.1

        self.thread = None

        self.bebop = bebop
        self._movement_vector = Vector()
    def __init__(self):
        """
			Loads the types to block and allow from env. variables. Initialization fails
			if there are types listed both as blocked and allowed at the same time.
		"""
        self.block_types = self.load_types("BLOCK_TYPES")
        self.allow_types = self.load_types("ALLOW_TYPES")

        if len(list(set(self.block_types) & set(self.allow_types))) > 0:
            Logging.log(
                "Some types of requests are listed as allowed and also as blocked - choose one!",
                Logging.LEVEL_ERROR)
            exit()
示例#6
0
def set_song_info(file_name, user, path='.'):
    try:
        song = eyed3.load(path + '/downloads/' + file_name + '.mp3')
        song_artist, song_title = file_name.split(' - ')
        song.tag.artist = song_artist
        # song.tag.album = "Free For All Comp LP"
        if song.tag.album_artist is None:
            song.tag.album_artist = song_artist
        song.tag.title = song_title
        # song.tag.track_num = 3
        song.tag.save()
        Logging('Complete changing of description of song: "{0}"'.format(file_name), user.logfile)
    except Exception as err:
        Logging("[ERROR] (Can't change song description) " + str(err), user.logfile)
示例#7
0
class UserTask(object):

    run = True

    def __init__(self,
                 username,
                 password,
                 openBoxType=[True, True, True, True],
                 smeltEquipType=[True, True, True, False],
                 useItemType=[True, True, True, True, True, True],
                 sellItemType=[True, True, True, True, True, True],
                 buyExp=True,
                 log=None):
        self.username = username
        self.password = password
        self.openBoxType = openBoxType
        self.smeltEquipType = smeltEquipType
        self.useItemType = useItemType
        self.sellItemType = sellItemType
        if log is None or len(logfilePath) == 0:
            self.log = Logging(self.username)
        else:
            self.log = log
        self.buyExp = buyExp
        self.statistic = {"username": self.username}

    def init(self):
        self.user = User(self.username, self.password)
        self.user.login()
        self.attacker = Attacker(self.user, log=self.log)
        self.box = Box(self.user, self.openBoxType)
        self.equip = Equip(self.user, self.smeltEquipType)
        self.item = Item(self.user, self.useItemType, self.sellItemType)
        self.shop = Shop(self.user)
        self.growup = Growup(self.user)
        self.card = Card(self.user)

    def task(self):
        stage = self.attacker.autoAttack()
        self.statistic['stage'] = stage

        self.box.autoOpenBox()
        self.equip.autoSmelt()
        self.item.autoItemCommand()
        # if self.buyExp is True:
        # 	self.shop.autoBuy()
        self.growup.growup()
        # self.card.getCard()
        self.log.info('============= END USER TASK ================')
示例#8
0
class Shop(object):

    __SHOP_PAGE = constants.DOMAIN + '/kf_fw_ig_shop.php'

    __SHOP_ITEM = {'101': '等级经验药丸', '102': '等级经验药丸(蛋)'}

    def __init__(self, user, log=None):
        self.safeid = user.safeid
        self.req = user.req
        if log is None:
            self.log = Logging(user.username)
        else:
            self.log = log

    def getCurMoney(self):
        res = self.req.get(self.__SHOP_PAGE)
        htmlTree = etree.HTML(res)
        kfbStr = (''.join(
            htmlTree.xpath(
                '//*[@id="alldiv"]/div[3]/div[1]/div[1]/a[2]/text()')))
        return int(re.search('^(\d*)KFB', kfbStr).group(1))

    def buy(self, id):
        payload = dict(buy=id, safeid=self.safeid)
        res = self.req.post(self.__SHOP_PAGE, data=payload)
        return res

    def autoBuy(self):
        self.log.info('--开始自动购买经验--')
        kfb = self.getCurMoney()
        self.log.info('当前KFB: ' + str(kfb))
        while True:
            buyId = -1
            used = 0
            if kfb >= 10000:
                buyId = '102'
                used = 10000
            elif kfb >= 5000:
                buyId = '101'
                used = 5000
            else:
                break
            self.buy(buyId)
            self.log.info(
                str(kfb) + '\t' + self.__SHOP_ITEM[buyId] + '\tUSED' +
                str(used) + '\t' + str(kfb - used))
            kfb = kfb - used
        self.log.info('--自动购买经验结束--')
        self.log.info()
示例#9
0
def download_song(infofile_name, user, path='.'):
    # function to download song by filename (data file), user (session) and path (song will save in this place)
    Logging('Try to download song: "{0}". Getting url'.format(
        infofile_name), user.logfile)
    with open('./data/{0}/Normal_Songs/{1}.json'.format(user.user_id, infofile_name), 'r') as info:
        song = json.load(info)
    Logging('Start download: "{0}"'.format(infofile_name), user.logfile)
    r = requests.get(song["url"])
    if not os.path.exists(path + '/downloads'):
        os.mkdir(path + '/downloads')
    if r.status_code == 200:
        with open(path + '/downloads/{0} - {1}.mp3'.format(song["artist"], song["title"]), 'wb') as song_mp3:
            song_mp3.write(r.content)
            Logging('Download complete successfull. Starting description changing', user.logfile)
            set_song_info(infofile_name, user, path)
示例#10
0
 def authorization(self):
     login = self.inputLogin.text()
     password = self.inputPassword.text()
     try:
         self.user = auth.auth(login, password, True)
         self.user.session_start()
         Logging('Load main GUI', self.user.logfile)
         self.mainroot = mainroot.Root(self.user)
         self.mainroot.show()
         self.mainroot.get_all_songs()
         Logging('Main file loading complete', self.user.logfile)
         self.close()
     except Exception as err:
         self.errors.setText(str(err))
         self.errors.setFont(QFont('Arial', 12))
         self.errors.setStyleSheet("color: rgb(255, 0, 0)")
示例#11
0
    def __init__(self):
        super(DataCollectUI, self).__init__()
        self.setupUi(self)

        # sqlite
        self.sqlite = SqlLiteManage()

        # 日志
        self.logger = Logging()

        # 摄像头
        self.capture = cv2.VideoCapture()

        # 定时器
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.update_frame)

        # 当前人脸ID
        self.faceID = 0

        # 是否进行人脸采集
        self.isCollect = False
        self.isContinueCollect = False

        # 是否打开摄像头
        self.isOpenCapture = False

        # 自定义参数
        self.count = 0  # 人脸采集计数
        self.MaxCount = 50  # 采集人脸数量
        self.scale_factor = 1.1  # 数值越大计算越快,太快会丢失人脸
        self.minNeighbors = 3  # 控制着误检测

        # 预处理选择
        self.isGaussianBlur = False  # 高斯
        self.isBlur = False  # 均值
        self.isMedianBlur = False  # 中值
        self.isEqualizeHist = False  # 直方图均衡

        # 级联分类器
        self.face_detector = cv2.CascadeClassifier(
            "E:\Opencv\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml"
        )

        # 人脸数量
        self.max_face_count = 1
示例#12
0
 def download(self):
     counter = 0
     counter_broak = 0
     max_counter = len(self.to_download)
     self.progress.setMinimum(counter)
     self.progress.setMaximum(max_counter)
     for i in self.to_download:
         try:
             music.download_song(i, self.user, self.path)
             counter += 1
         except OSError:
             Logging("Can't download song: {0}".format(i[:-5:]),
                     self.user.logfile)
             counter_broak += 1
         self.progress.setValue(counter)
     self.progress.reset()
     text_info = '''Complete downloading. Total: {0}. Successful: {1}. Broak: {2}'''.format(
         max_counter, counter, counter_broak)
     Logging(text_info, self.user.logfile)
示例#13
0
 def __init__(self,
              username,
              password,
              openBoxType=[True, True, True, True],
              smeltEquipType=[True, True, True, False],
              useItemType=[True, True, True, True, True, True],
              sellItemType=[True, True, True, True, True, True],
              buyExp=True,
              log=None):
     self.username = username
     self.password = password
     self.openBoxType = openBoxType
     self.smeltEquipType = smeltEquipType
     self.useItemType = useItemType
     self.sellItemType = sellItemType
     if log is None or len(logfilePath) == 0:
         self.log = Logging(self.username)
     else:
         self.log = log
     self.buyExp = buyExp
     self.statistic = {"username": self.username}
示例#14
0
def get_songs_info(user):
    '''
    This function get all info about user music
    It put its into JSON-files (data files)
    If song has bad-decoding name or author (not-unicode), its put
    it in folder "Bad_Songs" with song ID as name
    Else its put it in folder "Normal_Songs" (Name = 'Author' - 'Title')
    '''
    if not os.path.exists('./data/{0}'.format(user.user_id)):
        os.makedirs('./data/{0}'.format(user.user_id))
    with open('./data/{0}/vk_audio_list.txt'.format(user.user_id), 'w') as f:
        bad_songs = 0
        Logging('Looking for a user songs. It may take time if you have a lot of music', user.logfile)
        songs = user.music.get(owner_id=user.user_id)
        Logging('Find {0} songs. Trying get info about it'.format(
            len(songs)), user.logfile)
        counter = 0
        for i in songs:
            counter += 1
            try:
                f.write(i["artist"] + ' - ' + i["title"] + '\n')
                if not os.path.exists('./data/{0}/Normal_Songs'.format(user.user_id)):
                    os.makedirs('./data/{0}/Normal_Songs'.format(user.user_id))
                normal_song = make_name_normal(
                    str(i['artist'] + ' - ' + i['title']))
                with open('./data/{0}/Normal_Songs/'.format(user.user_id) + normal_song + '.json', 'w') as good_file:
                    json.dump(i, good_file, indent=2, ensure_ascii=False)
                Logging('Get info about {0}/{1} songs. Current song: "{2} - {3}"'.format(
                    counter, len(songs), i["artist"], i["title"]), user.logfile)
            except UnicodeEncodeError:
                bad_songs += 1
                if not os.path.exists('./data/{0}/Broken_Songs'.format(user.user_id)):
                    os.makedirs('./data/{0}/Broken_Songs'.format(user.user_id))
                with open('./data/{0}/Broken_Songs/'.format(user.user_id) + str(i['id']) + '.json', 'w') as bad_file:
                    json.dump(i, bad_file, indent=2, ensure_ascii=True)
                Logging('[WARNING]Get info about {0}/{1} songs. Bad decoding name error'.format(
                    counter, len(songs)), user.logfile)
        if bad_songs:
            f.write("\nCan't write songs(bad name decoding): " + str(bad_songs))
    Logging('Songs info received', user.logfile)
class EmailUI(QtWidgets.QMainWindow, Ui_Form):
    def __init__(self):
        super(EmailUI, self).__init__()
        self.setupUi(self)
        self.logger = Logging()
        self.read_email_conf()

    # 保存邮箱配置
    def save_email_conf(self):
        receiver_email = self.lineEdit.text()
        sender = self.lineEdit_2.text()
        receiver = self.lineEdit_3.text()
        if not (receiver_email and sender and receiver):
            QMessageBox.warning(self, '警告', '有字段为空')
            self.logger.log_error('email info save filed')
            return
        conf = {
            'receiver_email': receiver_email,
            'sender': sender,
            'receiver': receiver
        }
        with open('email_conf/conf.yaml', 'w', encoding='utf-8') as f:
            f.write(str(conf))
        QMessageBox.about(self, 'info', '保存成功')
        self.logger.log_info('email info save success')

    # 读取邮箱配置
    def read_email_conf(self):
        if os.path.exists('email_conf/conf.yaml'):
            with open('email_conf/conf.yaml', 'r', encoding='utf-8') as f:
                conf = eval(f.read())
            if conf:
                self.lineEdit.setText(conf['receiver_email'])
                self.lineEdit_2.setText(conf['sender'])
                self.lineEdit_3.setText(conf['receiver'])
            else:
                return
        else:
            return
示例#16
0
def create_app(config):
    """AUTH app factory method."""
    app = Flask(__name__)
    app.config.from_object(config)
    app.config.from_envvar("CONFIG_ENV", silent=True)
    db = SQLAlchemy(app)
    Session(app)
    Autodoc(app)
    handler = RotatingFileHandler(app.config.get('FLASK_LOG_PATH', "{0}/{1}". \
            format(os.path.abspath(os.path.dirname(__file__)), "authapp.log")), maxBytes=1024 * 1024 * 10, backupCount=13)
    app.config.setdefault('LOG_NAME', 'authapp')
    Logging(app, handler)
    return app, AppBuilder(app, db.session, security_manager_class=security_manager.SecurityManager, \
                            update_perms=app.config['AUTO_UPDATE_PERM'], indexview=security_manager.IndexView)
示例#17
0
 def session_start(self):
     self.session = vk_api.VkApi(login=self.login,
                                 password=self.password,
                                 auth_handler=two_factor_auth_handler,
                                 captcha_handler=captcha_handler,
                                 config_filename='vk_config.json')
     clear_last_log()
     self.set_logfile_name()
     Logging("Trying to start session", self.logfile)
     self.session.auth()
     Logging("Session started", self.logfile)
     Logging("Getting music api", self.logfile)
     self.api = self.session.get_api()
     self.music = audio.VkAudio(self.session)
     Logging("Complete successfully", self.logfile)
     self.get_id()
     with open('user.json', 'w') as f:
         user_data = {
             'login': self.login,
             'password': tools.encode(self.password)
         }
         json.dump(user_data, f, indent=2, ensure_ascii=False)
     return (self)
class Mail:
    def __init__(self):
        self.mail_host = 'smtp.qq.com'
        self.mail_pass = ''  # 授权码
        self.sender = ''  # 发送人
        self.receiver, self.sender_name, self.receiver_name = self.read_conf()
        self.logger = Logging()

    # 读取配置
    def read_conf(self):
        with open('E:/Opencv/FaceRecognition_demo/email_conf/conf.yaml',
                  'r',
                  encoding='utf-8') as f:
            conf = eval(f.read())
        return [conf['receiver_email']], conf['sender'], conf['receiver']

    # 发邮件
    def send(self, text):
        # 邮件内容
        content = text
        message = MIMEText(content, 'plain', 'utf-8')

        # 寄件人和收件人
        message['From'] = Header(self.sender_name, 'utf-8')
        message['To'] = Header(self.receiver_name, 'utf-8')

        subject = 'python_test'  # 发送的主题,可自由填写
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)
            smtpObj.login(self.sender, self.mail_pass)
            smtpObj.sendmail(self.sender, self.receiver, message.as_string())
            smtpObj.quit()
            self.logger.log_info('send mail success')
        except smtplib.SMTPException as e:
            self.logger.log_error('send mail failed')
示例#19
0
class Growup(object):

    __GROWUP_PAGE = constants.DOMAIN + '/kf_growup.php'

    def __init__(self, user, log=None):
        self.user = user
        self.req = user.req
        if log is None:
            self.log = Logging(user.username)
        else:
            self.log = log

    def growup(self):
        self.user.reloadSafeid()
        self.safeid = self.user.safeid
        self.log.info('--开始领取登录奖励--')
        growupUrl = self.__GROWUP_PAGE + '?ok=3&safeid=' + self.safeid
        res = self.req.get(growupUrl)
        self.log.info('--领取登录奖励结束--')
        self.log.info()
示例#20
0
import yaml
from key_generator import KeyGenerating

from log import Logging

HOME_KEY_DIR = "/home/yauheni/PyCharmProjects/student/security/RSA/key_capacity"

logger = Logging(name=__name__).get_logger()


class RSA:
    def __init__(self):
        self.q = None
        self.p = None
        self.n = None
        self.e = None
        self.public_exponent = None
        self.private_exponent = None

        self.key_gen = KeyGenerating()

    @staticmethod
    def euclid_checker(number_1: int, number_2: int) -> int:
        while number_1 != 0:
            number_1, number_2 = number_2 % number_1, number_1
        return number_2

    @staticmethod
    def save_key(key: list, file_name: str) -> None:
        with open('{}/{}'.format(HOME_KEY_DIR, file_name), 'w') as file:
            yaml.dump({'key': key}, file, default_flow_style=False, sort_keys=False)
示例#21
0
文件: proespm.py 项目: n-bock/proespm
            ["ec.txt", "0", "gwy"],
                hierarchy="sub",
                subfolder_name="_data",
        ):
            l.log_p(10, ">>> No data files were not moved.")
        if not multiple_move(
                proc_dir, src_dir, ["png"], hierarchy="sub",
                subfolder_name="_png"):
            l.log_p(10, ">>> No images files were not moved.")
        if not multiple_move(proc_dir, src_dir, ["html"], hierarchy="parent"):
            l.log_p(10, ">>> No HTML report was moved.")
    elif prep.check_network_file(src_dir[0]):
        l.log_p(9, ">>> Move data and remove temporary folder")
        multiple_move(proc_dir, src_dir, ["png", "0", "ec.txt", "html"])

    l.log_p(0, ">>>                  DONE                   <<<")


if __name__ == "__main__":
    temp = tempfile.mkdtemp(prefix="python_", suffix="_temp")
    l = Logging()

    try:
        src, fs, labj = prompt()
        pdir, proc = prepare(src, fs, temp)
        main(src, pdir, proc, labj)
        cleanup(src, pdir)
        l.save_log(src, config.log_f_name)
    finally:
        shutil.rmtree(temp)
示例#22
0
from log import Logging
import ConfigParser
import importlib
from os import walk
import printer
import re
import utilities
log = Logging()
uf = utilities.Utilities()


class Controller(object):
    def __init__(self):
        self.reloadClasses = False
        self.Printer = printer.Printer()  #Controller has a Printer

    def start(self):
        log.header(
            " _____      _       ____      _            ___     ___      ___  ",
            False)
        log.header(
            "|  __ \    | |     |___ \    | |          / _ \   |__ \    / _ \ ",
            False)
        log.header(
            "| |__) |___| |_ _ __ __) | __| |  __   __| | | |     ) |  | | | |",
            False)
        log.header(
            "|  _  // _ \ __| '__|__ < / _` |  \ \ / /| | | |    / /   | | | |",
            False)
        log.header(
            "| | \ \  __/ |_| |  ___) | (_| |   \ V / | |_| |_  / /_  _| |_| |",
示例#23
0
from cloudprovider import CloudProvider
import cloudfiles
import cloudfiles.errors
from log import Logging
_log = Logging().log


class Swift(CloudProvider):
    def __init__(self,
                 username=None,
                 api_key=None,
                 timeout=5,
                 servicenet=False,
                 useragent='com.whmcr.cloudsync',
                 auth_url=cloudfiles.uk_authurl):
        """
        Accepts keyword args for Swift Username and API Key

        @type username: str
        @param username: Swift Username
        @type api_key: str
        @param api_key: Swift API Key
        @type servicenet: bool
        @param servicenet: Use Service net - Rackspace Cloud files specific
        @type user_agent: str
        @param user_agent: A user agent string used for all requests
        @type timeout: int
        @param timeout: Timeout value in seconds for a request
        """
        self.connection_pool = None
        self.username = username
示例#24
0
class User:

    __LOGIN_PAGE = constants.DOMAIN + '/login.php'

    __INDEX_PAGE = constants.DOMAIN + '/'

    __SAFEID_PAGE = constants.DOMAIN + '/kf_fw_ig_index.php'

    __SM_PAGE = constants.DOMAIN + '/kf_growup.php'

    def __init__(self, username, password, log=None):
        self.loginStatus = False
        self._safeid = None
        self.username = username
        self.password = password
        self.req = KfReq()
        if log is None:
            self.log = Logging(username)
        else:
            self.log = log

    def login(self):
        self.log.info('--开始登录--')
        self.log.info('username:'******'password:'******'GBK'),
                       pwpwd=self.password,
                       submit='登录'.encode('GBK'))
        res = self.req.post(self.__LOGIN_PAGE, data=payload)
        self._safeid = None
        if '您已经顺利登' in res:
            self.log.info('登录成功')
            self.log.info('Cookies: ')
            self.log.info(str(self.req.cookies))
            self.log.info('')
            self.loginStatus = True
            return True
        else:
            self.log.info('登录失败')
            self.loginStatus = False
            return False

    def getSafeid(self):
        self.log.info('--开始获取safeid--')
        res = self.req.get(self.__SAFEID_PAGE)
        htmlTree = etree.HTML(res)
        jsCode = htmlTree.xpath(
            '//*[@id="alldiv"]/div[3]/div[2]/script[2]/text()')[0]
        _safeid = re.search("\"safeid=(.*)\"", jsCode).group(1)
        self.log.info('成功获取safeid: ' + _safeid)
        return _safeid

    def reloadSafeid(self):
        self._safeid = self.getSafeid()

    def getSM(self):
        self.log.info('--开始获取神秘系数--')
        res = self.req.get(self.__SM_PAGE)
        htmlTree = etree.HTML(res)
        sm = ''.join(
            htmlTree.xpath(
                '//*[@id="alldiv"]/div[3]/div[2]/div[1]/div[1]/text()'))
        sm = re.search('.*神秘系数\s(\d*).*', sm).group(1)
        self.log.info('--成功获取神秘系数:' + sm + '--')
        return int(sm)

    @property
    def safeid(self, force=False):
        if self.loginStatus:
            if self._safeid == None or force:
                self._safeid = self.getSafeid()
            return self._safeid
        else:
            self.log.error('未登录账号')
示例#25
0
class Box(object):

	__BOX_PAGE = constants.DOMAIN + '/kf_fw_ig_mybp.php'
	__BOX_OPEN_PAGE = constants.DOMAIN + '/kf_fw_ig_mybpdt.php'

	def __init__(self, user, boxType, log=None):
		self.safeid = user.safeid
		self.req = user.req
		self.boxType = boxType
		if log is None:
			self.log = Logging(user.username)
		else:
			self.log = log


	def getBoxQuantity(self):
		res = self.req.get(self.__BOX_PAGE)
		htmlTree = etree.HTML(res)
		print()
		return [
			int(''.join(htmlTree.xpath('//*[@id="alldiv"]/div[3]/div[2]/div[3]/table/tr[2]/td[1]/span[2]/text()'))),
			int(''.join(htmlTree.xpath('//*[@id="alldiv"]/div[3]/div[2]/div[3]/table/tr[2]/td[2]/span[2]/text()'))),
			int(''.join(htmlTree.xpath('//*[@id="alldiv"]/div[3]/div[2]/div[3]/table/tr[2]/td[3]/span[2]/text()'))),
			int(''.join(htmlTree.xpath('//*[@id="alldiv"]/div[3]/div[2]/div[3]/table/tr[2]/td[4]/span[2]/text()')))
		]

	def openSingleBox(self, openBoxType):
		payload = dict(
			do=3,
			id=openBoxType,
			safeid=self.safeid
		)
		openRes = self.req.post(self.__BOX_OPEN_PAGE, data=payload)
		return openRes

	def openBox(self):
		boxQuantity = self.getBoxQuantity()
		for i in range(0, 4):
			if self.boxType[i]:
				for n in range(0, boxQuantity[i]):
					openRes = self.openSingleBox(i+1)
					self.log.info(str(i+1)+':\t'+openRes)
					time.sleep(1)


	def autoOpenBox(self):
		self.log.info('--开始自动开盒--')
		self.log.info('获取盒子数:')
		boxQuantity = self.getBoxQuantity()
		self.log.info(' '.join(map(str, boxQuantity)))
		self.log.info('开始打开盒子')
		self.openBox()
		self.log.info('--自动开盒结束--')
		self.log.info()
示例#26
0
from log import Logging
from tools import GlobalMap as Gl
from manager.communication import Image
from manager.communication import Container
from manager.communication import System
from etc.sys_set import WEB_RESPONSE_HOST, WEB_RESPONSE_PORT

app = Flask(__name__)
# 镜像操作实例
_image = Image()
# 容器操作实例
_container = Container()
# 系统信息获取实例
_system = System()
# 日志操作实例
_logger = Logging('web_flask')
_logger.set_file('web_flask.txt')


@app.route('/')
def hello_world():
    return 'Hello World!'


def get_node_num(cluster_id):
    """  获取指定集群的节点个数

    :param cluster_id: 集群IP
    :return: 集群个数(int)
    """
    return Gl.get_value('CLUSTER_ALL_INFO_VAR',
示例#27
0
class SHA1:

    def __init__(self):
        self.logging = Logging()

    def calcNodeID_Sha1(self, text):
        self.logging.setSection('discovery')
        self.logging.msg(LogMsg.RETURNING_SHA1_HASH)
        return hashlib.sha1(text).hexdigest()

    def calcDist(self, node_id_1, node_id_2):
        self.logging.msg(LogMsg.RETURNING_PEER_DISTANCE)
        return long(node_id_1.hexdigest(), 16) ^ long(node_id_2.hexdigest(), 16)

    def readTor(self, torrent_location):
        read_file = None
        try:
            read_file = open(torrent_location, 'r').read()
            self.logging.msg(LogMsg.OPENING_TORRENT_FILE)
        except IOError as e:
            self.logging.msg(LogMsg.ERROR_TORRENT_FILE_DOESNT_EXIST + str(e))
        return read_file

    def getMetaD(self, torrent):
        self.logging.msg(LogMsg.CREATING_META_DATA_FROM_TORRENT)
        return bencode.bdecode(torrent)

    def createIHFrom(self, meta_data):
        hash_contents = bencode.bencode(meta_data['info'])
        self.logging.msg(LogMsg.CREATING_INFO_HASH_FROM_META_DATA)
        return self.calcNodeID_Sha1(hash_contents)

    def createMLFrom(self, info_hash):
        self.logging.setSection('calculation')
        self.logging.msg(LogMsg.CREATING_MAGNET_LINK_FROM_INFO_HASH)
        return 'magnet:?xt=urn:btih:' + info_hash

    def createServer(self):
        self.logging.msg(LogMsg.CREATING_KADEMLIA_SERVER)
        kademlia_server = kademlia.network.Server()
        return kademlia_server
示例#28
0
 def __init__(self):
     self.logging = Logging()
示例#29
0
    def an_packet(self):
        _ip = self.__get_netcard()
        _mysql_packet_op = mysql_packet(**dict({'_type':self._type},**{'_ip':_ip}))
        session_status = {}
        while 1:
            if not self.queue.empty():
                buf,_cur_time = self.queue.get()
                eth = dpkt.ethernet.Ethernet(buf)

                if not isinstance(eth.data, dpkt.ip.IP):
                    Logging(msg='Non IP Packet type not supported %s\n' % eth.data.__class__.__name__,level='error')
                    continue

                ip = eth.data
                tcp = dpkt.tcp.TCP(str(ip.data))
                if (tcp.dport == self.kwargs['port'] or tcp.sport == self.kwargs['port']) and len(tcp.data) > 0 \
                        and 'interface' not in tcp.data and 'tbl_sessions' not in tcp.data:
                    if len(tcp.data) > 5:
                        session, packet_response, client_packet_text, packet_header, packet_seq_id,response_type,response_status=_mysql_packet_op.Unpacking(
                                                                                data=tcp.data,srchost=self.inet_to_str(ip.src),
                                                        srcport=tcp.sport,dsthost=self.inet_to_str(ip.dst),dstport=tcp.dport)
                    else:
                        continue

                    if client_packet_text:
                        session_status[session] = {'start_time':_cur_time,'request_text':client_packet_text,
                                                   'request_header':packet_header,'seq_id':packet_seq_id,'response_type':response_type}
                        if packet_header == 0x16:
                            session_status[session]['com_pre'] = True
                        elif packet_header == 0x17 and 'com_pre' in session_status[session]:
                            del session_status[session]['com_pre']
                    elif packet_response:
                        if session in session_status and packet_response in session_status[session]['response_type']:
                            if packet_seq_id - 1 == session_status[session]['seq_id'] and 'com_pre' not in session_status[session]:
                                session_status[session]['end_time'] = _cur_time
                                session_status[session]['status'] = self.check_packet_type(packet_response)
                                session_status[session]['response_status'] = response_status

                del_session = []
                for session in session_status:
                    if 'status' in session_status[session]:
                        execute_time = float('%.5f' % (session_status[session]['end_time'] - session_status[session]['start_time']))
                        if session_status[session]['request_header'] == 0x03:
                            sql, values = self.sql_parser(session_status[session]['request_text'])
                        else:
                            sql, values = session_status[session]['request_text'],None
                        _session = eval(session)

                        Logging(msg=
                            'source_host: {} source_port: {} destination_host: {} destination_port: {} sql: {} values: {} '
                            'execute_time:{}  status:{}'.format(_session[0], _session[1], _session[2],_session[3],
                                                                sql, values,
                                                                execute_time,
                                                                session_status[session]['response_status']),level='info')
                        del_session.append(session)

                for session in del_session:
                    del session_status[session]

            else:
                time.sleep(0.01)
示例#30
0
class Attacker(object):

    __LOOT_PAGE = constants.DOMAIN + '/kf_fw_ig_index.php'
    __ATTACK_PAGE = constants.DOMAIN + '/kf_fw_ig_intel.php'

    def __init__(self, user, log=None):
        self.safeid = user.safeid
        self.req = user.req
        if log is None:
            self.log = Logging(user.username)
        else:
            self.log = log
        self.attackTime = None

    def checkOnlineBattleIsOver(self, htmlTree=None):
        if htmlTree is None:
            res = self.req.get(self.__LOOT_PAGE)
            htmlTree = etree.HTML(res)
        pk_log = ''.join(htmlTree.xpath('//*[@id="pk_text"]/li/text()'))
        attacked = (pk_log == '今日战斗已完成,请重置后再战。')
        return attacked

    def checkOffLineBattleIsOver(self):
        if self.attackTime is None:
            return None
        attacked = (datetime.datetime.now().day - self.attackTime.day) == 0
        return attacked

    def checkAttacked(self):
        offLineBattleIsOver = self.checkOffLineBattleIsOver()
        self.log.info('检查线下争夺记录: ' + str(offLineBattleIsOver))
        if offLineBattleIsOver is None:
            onLineBattleIsOver = self.checkOnlineBattleIsOver()
            self.log.info('检查线上争夺记录: ' + str(onLineBattleIsOver))
            return onLineBattleIsOver
        else:
            return offLineBattleIsOver

    def getServerStatus(self, htmlTree):
        status = ''.join(
            htmlTree.xpath(
                '//*[@id="alldiv"]/div[3]/div[2]/div[3]/table/tr[1]/td/span/text()'
            ))
        return status[-2:]

    def attack(self):
        res = self.req.post(self.__ATTACK_PAGE, data=dict(safeid=self.safeid))
        return res

    def attackToEnd(self):
        stage = '0'
        while True:
            self.log.info('查询服务器状态')
            lootPage = self.req.get(self.__LOOT_PAGE)
            lootPageTree = etree.HTML(lootPage)
            serverStatus = self.getServerStatus(lootPageTree)
            self.log.info(serverStatus)
            if serverStatus in ['空闲', '正常']:
                self.log.info('开始争夺')
                attackRes = self.attack()
                #self.log.info(attackRes)
                if attackRes == 'no':
                    break
                m = re.finditer(r'<li((?!</li>).)*</li>', attackRes)
                for s in m:
                    tmp = ''.join(etree.HTML(s.group()).xpath('//text()'))
                    if re.search('.*\s(\d*)\s层.*', tmp) != None:
                        stage = re.search('.*\s(\d*)\s层.*', tmp).group(1)
                    self.log.info(tmp)
                self.log.info()
                time.sleep(1)
            else:
                self.log.info('等待服务器状态变化...')
                time.sleep(60 * 5)
        return stage

    def autoAttack(self):
        self.log.info('--开始自动争夺--')
        self.log.info('检查是否已争夺')
        attacked = self.checkAttacked()
        stage = '0'
        if attacked:
            self.log.info('今日已进行争夺')
        else:
            stage = self.attackToEnd()
        self.log.info('--自动争夺结束--')
        self.log.info()
        self.attackTime = datetime.datetime.now()
        return stage
示例#31
0
import sys
sys.path.insert(0, "./libs")
sys.path.insert(1, "./libs/gui")
import login
from log import Logging
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtRemoveInputHook
from logging import getLogger
getLogger().setLevel('ERROR')
pyqtRemoveInputHook()

try:
    app = QApplication(sys.argv)
    ui = login.Log_root()
    ui.show()
    sys.exit(app.exec_())
except KeyboardInterrupt:
    Logging("Stop programm by yourself", user.logfile)
    raise SystemExit
except Exception as err:
    Logging('[ERROR]' + str(err), user.logfile)
    raise SystemExit
示例#32
0
class Card(object):

    __CARD_PAGE = constants.DOMAIN + '/kf_fw_ig_mycard.php'

    def __init__(self, user, log=None):
        self.safeid = user.safeid
        self.req = user.req
        self.user = user
        if log is None:
            self.log = Logging(user.username)
        else:
            self.log = log

    def getNowCard(self):
        self.log.info('--开始获取现有卡片信息--')
        res = self.req.get(self.__CARD_PAGE)
        cardHtml = etree.HTML(res)
        cardTable = cardHtml.xpath(
            '//*[@id="alldiv"]/div[3]/div[2]/div[3]/div[2]/table/tr')
        cardList = []
        for card in cardTable:
            level = ''.join(card.xpath('td[1]/div/text()'))
            if len(level) == 0:
                continue
            level = re.search(".*等级上限\s(\d*).*", level).group(1)
            temp = ''.join(card.xpath('td[2]/text()'))
            skill = re.search('.*技能位:(\d*).*卡片品质:(\d*)', temp).group(1)
            quality = re.search('.*技能位:(\d*).*卡片品质:(\d*)', temp).group(2)
            cardId = ''.join(card.xpath('td[1]/div/a/@href'))
            cardId = re.search('.*cardid=(.*)&.*', cardId).group(1)
            cardList.append({
                "level": int(level),
                "skill": int(skill),
                "quality": int(quality),
                "cardid": cardId
            })
        self.log.info('--获取现有卡片信息结束--')
        return cardList

    def deleteCard(self, cardId):
        deleteUrl = self.__CARD_PAGE + '?card=del&safeid=' + self.safeid + '&cardid=' + cardId
        res = self.req.get(deleteUrl)

    def getCard(self):
        self.log.info('--开始领取卡片--')
        cardList = self.getNowCard()
        sm = self.user.getSM()
        if len(cardList) == 3:
            minCardId = None
            minCardVal = sys.maxsize
            hopeLevel = sm * 2 + 30
            hopeSkill = 4
            hopeQuality = 8
            for card in cardList:
                val = int(
                    (card['level'] / hopeLevel + card['skill'] / hopeLevel +
                     card['quality'] / hopeQuality) * 1000)
                if val < minCardVal:
                    minCardVal = val
                    minCardId = card['cardid']
            self.deleteCard(minCardId)
        growupUrl = self.__CARD_PAGE + '?card=new&safeid=' + self.safeid
        res = self.req.get(growupUrl)
        self.log.info('--领取卡片结束--')
        self.log.info()
示例#33
0
def main():
    data_config_file = 'data_config.json'
    email_config_file = 'email_config.json'
    stored_posts_file = 'stored_posts.json'
    log_file = datetime.now().strftime('%Y-%m-%dT%H:%M:%S%z') + '.log'

    global Log
    Log = Logging(log_file)

    data_config = LoadJson(data_config_file)
    email_config = LoadJson(email_config_file)

    if int(data_config['logging_enabled']):
        Log.start()

    cl_listings = []

    if not IsEmpty(stored_posts_file):
        sp = LoadJson(stored_posts_file)
        [cl_listings.append(CL_Post(stored_post)) for stored_post in sp]
        Log.log('Imported ' + str(len(cl_listings)) + ' saved posts')

    socket.setdefaulttimeout(10)

    threads_required = 0
    for _ in data_config['locations']:
        for __ in data_config['categories']:
            threads_required += 1

    threads = [None] * threads_required
    results = [None] * threads_required

    index = 0
    for location in data_config['locations']:
        for category in data_config['categories']:
            threads[index] = Thread(target=PullFeeds, args=(location, category, results, index))
            threads[index].start()
            index += 1

    [threads[i].join() for i in range(threads_required)]
    [ParseFeed(feed, data_config, cl_listings) for feed in results]

    if len(cl_listings) > 0:
        if CheckNotityInterval(data_config['notification_intervals']):
            email = CL_Email(email_config)
            email.write(cl_listings)
            email.send()
            Log.log('Email sent to ' + str(email.recipient))

            if not IsEmpty(stored_posts_file):
                MakeEmpty(stored_posts_file)
                Log.log('Emptied contents of ' + str(stored_posts_file))
        else:
            Log.log('Storing posts to ' + str(stored_posts_file))
            WriteJson(stored_posts_file, cl_listings)
            Log.log('Successful write to ' + str(stored_posts_file))
    else:
        Log.log('No new posts detected')

    data_config['notification_intervals'] = UpdateIntervals(data_config['notification_intervals'])
    WriteJson(data_config_file, data_config)
    Log.log('Updated contents of ' + str(data_config_file))