def menu_main(l,w) :                        #write the logic of the menu
	while True:                             #makes it so we are inside the script as long as we give a valid input
		try:
			sub_main(l,w)
			print("	")
			print("	")
			print("	")
			selection=int(input("What would you like to do:\n ".center(w)))  #input needed to choose between the various options
			if selection==1:                                                 
				cleanup()                                                           
				wlan1.monitor_set()                                          #acceSs the monitor_set() method from wlan1 to set the interface into monitor mode
				l = l - 20
			elif selection==2:      
				cleanup()
				os.system("sudo service network-manager restart")#restarts the network manager services from linux 
				l = lines()
				spacer(l)
				tprint("net   restarting...".center(w-70))
				time.sleep(2)
				cleanup()
			elif selection==3:
				cleanup()
				sms_sender.SMS_sender()                                       #access SMS_sender() from sms_sender to send sms (this is a test to see if the credentials are right)
			elif selection==4:
				cleanup()
				email_sender.email_sender()                                   #access email_sender() from email_sender to send an email (this is a test to see if the credentials are right)
			elif selection==5:
				cleanup()
				os.system("sudo ./finalscanner.py")                           #launch the scanner to start sniffing (requires interface into monitor mode)
			elif selection==6:
				cleanup()
				l = lines()
				spacer(l)
				os.system("sudo ./deauth.py")                                 #launch the menu to send a deauth attack to disconnect possible victims from the malicious network
			elif selection==7:  
				cleanup()
				break                                                         #exits the script
			elif selection==0:
				cleanup()
				wifi.wifi_set()                                               #connect to a wifi AP
				l = l - 20
			else:
				break
		except ValueError:                                                    #in case the value is outside the range
			print("invalid choise".center(w))
	exit
	cleanup()
	l = lines()
	spacer(l)
	time.sleep(1)
	tprint("End of session".center(w-60))                                       
	print("Thank you for using the software".center(w))                       #when we exit the script
Exemple #2
0
 def create(self,request,*args,**kwargs):
     unit=get_object_or_404(WorkUnit,id=request.data.get('printer'))
     # import pdb;pdb.set_trace()
     cartridges=unit.printer.cartridge.all()
     unit.status_cartridge=False
     unit.save()
     for cartridge in cartridges:
         if cartridge.count!=0:
             cartridge.count-=1
             cartridge.reserved_count+=1
             cartridge.save()
             act=ActCartridge()
             act.cartridge=cartridge
             act.printer=unit
             act.save()
             text= '*Поcтупление новой заявки на картридж* \n\n'+act.cartridge.name+ '\n\n_Район:_ '+act.printer.cabinet.city.name + '\n\n_Данный картридж забронирован_'
             telegram.send(text)
             sender=email_sender()
             sender.send_mail_on_adress('Заказ на картридж от '+str(act.date) + ' принят в работу.','Картридж ' + act.cartridge.name +' для вашего района отправлен на заправку.',act.printer.cabinet.city.email_city)
             return Response({"results":"Картридж заказан"},status=status.HTTP_201_CREATED)
     act=ActCartridge()
     act.cartridge=cartridges.first()
     act.printer=unit
     act.status=1
     text= '*Поcтупление новой заявки на картридж*:\n\n'+act.cartridge.name+ '\n\n_Район:_ '+act.printer.cabinet.city.name + '\n\n _Необходимо отдать на заправку_'
     telegram.send(text)
     act.save()
     return Response({"results":"Картридж заказан"},status=status.HTTP_201_CREATED)
Exemple #3
0
 def __init__(self):
     cmd2.Cmd.__init__(self)
     self.cr = config_reader()
     self.utility = utility()
     self.feedback = feedback()
     self.statistics = statistics()
     self.es = email_sender()
     self.late_submit_checker = late_submit_checker()
     os.chdir('ASSIGNMENTS')
Exemple #4
0
 def patch(self, request):
     act_id = request.data.get('id')
     act=get_object_or_404(ActCartridge,id=act_id)
     serializer = ActCartridgeSerializer(act, data={"status":2},partial=True)
     if serializer.is_valid():
         serializer.save()
         sender=email_sender()
         sender.send_mail_on_adress('Изменение статуса заказа на картридж '+str(act.id)+' от '+str(act.date),'Картридж ' + act.cartridge.name +'для вашего района отправлен на заправку.',act.printer.cabinet.city.email_city)
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def packet_checkers(packet):  #go trough the packets and their content
    unchecked_layers = [
        beacon, response
    ]  #gives the arguments to check the DOT11 specification and a DOT11 probe response
    unckecked_packets = False
    for layer in unchecked_layers:  #checks all the layers that haven't been visited by the script yet
        if packet.haslayer(layer):  #checks if the packet has different layers
            unckecked_packets = True  #marks them to be checked
    if not unckecked_packets:  #no layers have been found
        return
    network_name = packet[Dot11Elt].info.decode(
    )  #set up a variable with a 802.11 Information Element as argument giving us the name of the network
    client = packet[
        Dot11].addr1  #set up a variable with the address of the broadcast
    mac_adress = packet[
        Dot11].addr2  #set up a variable with the mac adress of the spoofer
    if network_name in to_be_checked.keys(
    ):  #checks all the current networks against the given whitelisted network_name and mac adresses
        print("  ")
        logging.info(f" match with network_name: {network_name}")
        logging.info(f"with a mac_adress: {mac_adress}")
        if mac_adress not in to_be_checked[
                network_name]:  #if the mac adresses do not match with the whitelisted ones
            if packet.haslayer(beacon):  #checks for layers
                malicious_bssid = f"malicious network found for: '{network_name}' - malicious mac adress: {mac_adress}"
                db_log_malicious_bssid(
                    malicious_bssid)  #log the case in the db
                logging.warning(
                    malicious_bssid)  #outputs the malicious mac_adress
                global seen
                if seen == 0 or seen % 14 == 0:
                    seen = seen + 1
                    sms_sender.SMS_sender()
                    email_sender.email_sender()
            elif packet.haslayer(response):
                malicious_bssid = f"client '{client}' received a  malicious response to probe from BSSID: {mac_adress}"
                logging.warning(
                    malicious_bssid)  #logs the warning with the mac adress
                db_log_malicious_bssid(
                    malicious_bssid)  #logs the warning into the db
Exemple #6
0
def answer():
    if request.method == "POST":
        email = request.form["email_name"]
        height = int(request.form["height_name"])
        connection = sqlite3.connect("height_db.db")
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE IF NOT EXISTS height_table("
                       "email TEXT UNIQUE PRIMARY KEY, height INTEGER);")
        connection.commit()
        try:
            cursor.execute("INSERT INTO height_table VALUES(?, ?);",
                           (email, height))
            connection.commit()
        except sqlite3.IntegrityError:
            connection.close()
            return render_template("error.html")
        heights = cursor.execute("SELECT height from height_table")
        data = heights.fetchall()
        connection.close()
        average_height = calculate_average(data)
        email_sender(email, height, average_height, len(data))
    return render_template("success.html")
Exemple #7
0
 def destroy(self,request):
     act_id=request.data.get('id')
     act=get_object_or_404(ActCartridge,id=act_id)
     if act.status==0:
         act.cartridge.reserved_count-=1
         act.cartridge.count+=1
         act.cartridge.save()
         act.printer.status_cartridge=True
         act.printer.save()
         act.delete()
         sender=email_sender()
         sender.send_mail_on_adress('Изменение статуса заказа на картридж '+str(act_id)+' от '+str(act.date),'Заказ на картридж ' + act.cartridge.name +' отклонен администратором.',act.printer.cabinet.city.email_city)
     else:
         act.delete()
     return Response({"results":"Заказ отменен администратором"},status=status.HTTP_200_OK)
Exemple #8
0
 def create(self, request, *args, **kwargs):
     printer_id=request.data.get('printer')
     act=ActPrinter(status=6)
     unit = get_object_or_404(WorkUnit,id=printer_id)
     act.comment="Устранено своими силами - "+request.data.get('comment',unit.status_note)
     serializer=ActPrinterSerializer(act,data=request.data)
     printer_serializer=WorkUnitSerializer(unit,data={"status":5,"status_note":"Принтер починен и ожидает в ИТ-отделе."},partial=True)
     if serializer.is_valid() and printer_serializer.is_valid():
         serializer.save()
         printer_serializer.save()
         sender=email_sender()
         sender.send_mail_on_adress('Изменение статуса принтера','Принтер ' + unit.printer.name + 'id:' + str(unit.id) + 'готов и ожидает в ОГУПе' ,unit.cabinet.city.email_city)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #9
0
def heardEnter(ev):
    i, o, e = select.select([sys.stdin], [], [], 0.0001)
    for s in i:
        if s == sys.stdin:
            input = sys.stdin.readline()
            input = input.replace("\r\n", "")
            input = input.replace("\n", "")
            if "exit" == input:
                ev.allow_running = False
                print "BYE BYE :-) "
                sys.exit(0)
            if "b" == input:
                ev.clear_cache()
                ev.set_cache_flag(True)
                print "-   -   -   -   -   -   -   -   -   -   -   -   begin,e for end\r\n"
            if "e" == input:
                ev.set_cache_flag(False)
                #print ev.get_cache_log()
                #ev.clear_cache()
                print "=   =   =  =   =   =  =   =   =  =   =   =  =   end\r\n"
            if "email" == input:
                content = ev.get_cache_log()
                es = email_sender.email_sender()
                now = datetime.datetime.now()
                today = datetime.date.today()
                module_name = "chain_mail_config"
                dyna_module = __import__(module_name)
                title = str(today) + " log email report"
                print "title:", title, " please wait for send over."
                html_content = """
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Language" content="zh-CN"> 
</head>
<body>
				"""
                html_content += content
                html_content += "</body></html>"
                plain_content = ""
                es.send_html_email(dyna_module.config_mail_smtp,
                                   dyna_module.config_mail_from,
                                   dyna_module.config_mail_from_password,
                                   dyna_module.config_mail_send_to,
                                   plain_content, html_content, title)
                print "send over"
            #send it ...
            return True
    return False
Exemple #10
0
 def patch(self, request):
     req_id = request.data.get('id')
     req = get_object_or_404(Req, id=req_id)
     executor_id = request.data.get('executor')
     req.executor = request.user
     req.status = "3"
     serializer = ReqSerializer(req, data=request.data, partial=True)
     if serializer.is_valid():
         serializer.save()
         sender = email_sender()
         sender.send_mail_on_adress(
             'Закрытие заявки: ' + req.shortname, 'Заявка ' + str(req_id) +
             ' закрыта\n\nСсылка на заявку http://192.168.28.131/requests/'
             + str(req_id), req.user.email)
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #11
0
 def create(self, request, *args, **kwargs):
     printer_id=request.data.get('printer')
     unit = get_object_or_404(WorkUnit,id=printer_id)
     comment=request.data.get('comment',unit.status_note)
     act=ActPrinter(status=3)
     act.comment=comment
     serializer=ActPrinterSerializer(act,data=request.data)
     printer_serializer=WorkUnitSerializer(unit,data={"status":3,"status_note":comment},partial=True)
     if serializer.is_valid() and printer_serializer.is_valid():
         serializer.save()
         printer_serializer.save()
         sender=email_sender()
         sender.send_mail_on_adress('Изменение статуса принтера','Принтер ' + unit.printer.name + 'id:' + str(unit.id) + 'принят в диагностику' ,unit.cabinet.city.email_city)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def heardEnter( ev ):
    i, o, e = select.select([sys.stdin], [], [], 0.0001)
    for s in i:
        if s == sys.stdin:
            input = sys.stdin.readline()
            input = input.replace("\r\n", "")
            input = input.replace("\n", "")
            if "exit" == input:
                ev.allow_running = False
                print "BYE BYE :-) "
                sys.exit(0)
            if "b" == input:
                ev.clear_cache()
                ev.set_cache_flag(True)
                print "-   -   -   -   -   -   -   -   -   -   -   -   begin,e for end\r\n"
            if "e" == input:
                ev.set_cache_flag(False)
                #print ev.get_cache_log()
                #ev.clear_cache()
                print "=   =   =  =   =   =  =   =   =  =   =   =  =   end\r\n"
            if "email" == input:
                content = ev.get_cache_log()
                es = email_sender.email_sender()
                now = datetime.datetime.now()
                today = datetime.date.today()
                module_name = "chain_mail_config"
                dyna_module = __import__(module_name)
                title = str(today) + " log email report"
                print "title:", title , " please wait for send over."
                html_content = """
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Language" content="zh-CN"> 
</head>
<body>
				"""
                html_content += content
                html_content += "</body></html>"
                plain_content = ""
                es.send_html_email(dyna_module.config_mail_smtp, dyna_module.config_mail_from,
                    dyna_module.config_mail_from_password, dyna_module.config_mail_send_to, plain_content, html_content,
                    title)
                print "send over"
            #send it ...
            return True
    return False
Exemple #13
0
 def patch(self, request):
     act_ids_not=request.data.get('ids',False)
     acts=ActCartridge.objects.filter(status=1)
     acts_for_edit=None
     if act_ids_not!=False:
         acts_subquery=ActCartridge.objects.filter(id__in=act_ids_not)
         acts_for_edit=acts.difference(acts_subquery)
     else: 
         acts_for_edit=acts
     for act in acts_for_edit:
         try:
             act.status=2
             act.save()
             sender=email_sender()
             sender.send_mail_on_adress('Изменение статуса заказа на картридж '+str(act.id)+' от '+str(act.date),'Картридж ' + act.cartridge.name +'для вашего района отправлен на заправку.',act.printer.cabinet.city.email_city)
         except:
             return Response({'message':'Ошибка.'},status=status.HTTP_400_BAD_REQUEST)
     return Response({"results":"Картриджи отправлены в заправку"},status=status.HTTP_200_OK)
Exemple #14
0
 def create(self, request, *args, **kwargs):
     comment=request.data.get('comment')
     printer_id=request.data.get('printer')
     act=ActPrinter(status=4)
     act.comment=comment
     serializer=ActPrinterSerializer(act,data=request.data)
     unit = get_object_or_404(WorkUnit,id=printer_id)
     printer_serializer=WorkUnitSerializer(unit,data={"status":4,"status_note":comment},partial=True)
     if serializer.is_valid() and printer_serializer.is_valid():
         serializer.save()
         printer_serializer.save()
         text='Добрый день!\n\nВышел из строя принтер '+unit.printer.name+'.\n\nПричина: '+comment
         sender=email_sender()
         sender.send_email(text)
         sender.send_mail_on_adress('Изменение статуса принтера','Принтер ' + unit.printer.name + 'id:' + str(unit.id) + 'отправлен в ремонт' ,unit.cabinet.city.email_city)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #15
0
 def create(self, request, *args, **kwargs):
     req_id = request.data.get('req')
     req = Req.objects.all().filter(id=req_id).first()
     comment = Comment(user=self.request.user, req=req)
     TOKEN = '1191171470:AAFD2RFpUR0-W_RTqO4uco2WpCAZOCT1b4M'
     bot = telebot.TeleBot(TOKEN)
     text = '*Новый комментарий*\n\n' + request.data[
         'text'] + '\n\n_Автор:_ ' + request.user.surname + '\n_Номер заявки:_ ' + req_id
     bot.send_message('-488020289', text, parse_mode="Markdown")
     serializer = self.serializer_class(comment, data=request.data)
     if serializer.is_valid():
         serializer.save()
         sender = email_sender()
         if req.user.id != self.request.user.id:
             sender.send_mail_on_adress(
                 'Новый комментарий к заявке: ' + req.shortname,
                 'К заявке ' + str(req_id) +
                 ' оставлен новый комментарий\n\n' + request.data['text'] +
                 '\n\nСсылка на заявку http://192.168.28.131/requests/' +
                 str(req_id), req.user.email)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemple #16
0
import sys

from email_sender import email_sender
from email_template import email_template
from image_converter import converter
from pdf_merger import merger
from pdf_watermarker import watermarker

option = sys.argv[1]
if option == 'converter':
    converter(sys.argv)
elif option == 'merger':
    merger(sys.argv)
elif option == 'watermarker':
    watermarker(sys.argv)
elif option == 'email':
    email_sender(sys.argv)
elif option == 'template':
    email_template()
else:
    print(f'Option \'{option}\' is invalid, please read documentation')
Exemple #17
0
                    slowk_float_value = (slowk.tail(1).values)[0]
                    slowd_float_value = (slowd.tail(1).values)[0]
                    kdj_is_dead_or_alive = slowd_float_value == slowk
                    print("K值,D值,J值:", slowk_float_value, slowd_float_value,
                          (3 * slowd_float_value - 2 * slowk_float_value))
                    if macd_is_dead_or_live and kdj_is_dead_or_alive:
                        subject = "金叉死叉提醒"
                        kdj_str = "slowd:" + str(
                            slowd_float_value) + ",slowk:" + str(
                                slowk_float_value)
                        macd_str = ",macd:" + str(
                            macd_float_value) + ",macdhist:" + str(
                                macdhist_float_value) + ",macdsignal:" + str(
                                    macdsignal_float_value)
                        content = kdj_str + macd_str
                        ms = email_sender.email_sender()
                        ret = ms.mail(content, subject)
                #print("MACD:",macd)
                #print("macd:",macd_arr[0])
                #print("macdsignal:",macdsignal.tail(1).values)
                #print("macdhist:",macdhist.tail(1).values)
                print(
                    '---------------------------------------------------------------------------------------------------------------------------------------------------------------------------'
                )
                #print()
                #KDJ

                # clear dict
                if len(kl1m_dict) >= 200:
                    l = len(kl1m_dict)
                    keys = list(kl1m_dict.keys())[0:int(l / 2)]
Exemple #18
0
def checkout_cart():
    cart_counter = []
    for i in session['cart_item']:
        cart_counter.append(dict(id=i['id'], count=i['count']))

    if request.method == "POST":
        firstname = request.form['lastname']
        lastname = request.form['lastname']
        username = request.form['username']
        email = request.form['email']
        country = request.form['country']
        city = request.form['city']
        postalcode = request.form['postalcode']
        address = request.form['address']
        address2 = request.form['address2']

        items = [i['id'] for i in session['cart_item']]
        data_set = Item.query.filter(Item.id.in_(items)).all()

        data = []
        for i in data_set:
            data.append(
                dict(id=i.id,
                     title=i.title,
                     price=i.price,
                     description=i.description))

        purchase_id = str(uuid.uuid4())

        purchase = []
        for i in data:
            for j in cart_counter:
                if i['id'] == j['id']:
                    purchase.append(
                        dict(customer_email=email,
                             purchase_id=purchase_id,
                             product_id=i['id'],
                             product_name=i['title'],
                             product_description=i['description'],
                             price=i['price'],
                             count=j['count']))

        email_order = []
        for i in purchase:
            email_order.append(
                dict(customer_email=email,
                     purchase_id=purchase_id,
                     product_id=i['product_id'],
                     product_name=i['product_name'],
                     product_description=i['product_description'],
                     price=i['price'],
                     count=i['count']))
            purchase = Purchase(customer_email=email,
                                purchase_id=purchase_id,
                                product_id=i['product_id'],
                                product_name=i['product_name'],
                                product_description=i['product_description'],
                                price=i['price'],
                                count=i['count'])
            db.session.add(purchase)
            db.session.commit()

        cart_product = []
        for i in data_set:
            cart_product.append(dict(id=i.id, price=i.price))

        data_sum = []
        for i in cart_product:
            for j in cart_counter:
                if i['id'] == j['id']:
                    data_sum.append(i['price'] * j['count'])
        product_sum = sum(data_sum)
        product_sum_formated = '{0:,}'.format(int(product_sum)).replace(
            ',', ' ')

        customer = Customer(firstname='customer', email=email, password='******')

        try:
            db.session.add(customer)
            db.session.commit()
        except:
            pass

        try:
            message = render_template('email_order.html',
                                      data=email_order,
                                      total=product_sum_formated,
                                      email=email)
            email_sender(email, message)
        except:
            pass

        url = '/stripe/' + purchase_id + '/' + 'OrderId: ' + purchase_id + '/' + str(
            product_sum) + '00'

        try:
            session.pop('purchase_id', None)
            session['purchase_id'] = [{'purchase_id': purchase_id}]
        except:
            session['purchase_id'] = [{'purchase_id': purchase_id}]

        return redirect(url)

    items = [i['id'] for i in session['cart_item']]
    data_set = Item.query.filter(Item.id.in_(items)).all()

    cart_product = []
    for i in data_set:
        cart_product.append(dict(id=i.id, price=i.price))

    data_sum = []
    for i in cart_product:
        for j in cart_counter:
            if i['id'] == j['id']:
                data_sum.append(i['price'] * j['count'])
    product_sum = sum(data_sum)
    product_sum_formated = '{0:,}'.format(int(product_sum)).replace(',', ' ')

    return render_template('checkout_cart.html',
                           data=data_set,
                           cart_counter=cart_counter,
                           product_sum_formated=product_sum_formated)
Exemple #19
0
    def get_realtime_kline_eos_btc(self, price_high, price_low, mail):
        print("EOS/BTC")
        while (1):
            try:
                ws = create_connection("wss://api.huobipro.com/ws")
                break
            except:
                print('connect ws error,retry...')

            time.sleep(5)

        # 订阅 KLine 数据
        tradeStr = """{"sub":"market.eosbtc.trade.detail"}"""

        # 请求 KLine 数据
        # tradeStr="""{"req": "market.ethusdt.kline.1min","id": "id10", "from": 1513391453, "to": 1513392453}"""

        # 订阅 Market Depth 数据
        # tradeStr="""{"sub": "market.ethusdt.depth.step5", "id": "id10"}"""

        # 请求 Market Depth 数据
        # tradeStr="""{"req": "market.ethusdt.depth.step5", "id": "id10"}"""

        # 订阅 Trade Detail 数据
        # tradeStr="""{"sub": "market.ethusdt.trade.detail", "id": "id10"}"""

        # 请求 Trade Detail 数据
        # tradeStr="""{"req": "market.ethusdt.trade.detail", "id": "id10"}"""

        # 请求 Market Detail 数据
        # tradeStr="""{"req": "market.ethusdt.detail", "id": "id12"}"""

        ws.send(tradeStr)
        #_thread.start_new_thread(self.recieve(ws,tradeStr), ("Thread-1", 2, ))
        count = 0
        while (count == 0):

            # def recieve(self,ws,tradeStr):
            compressData = ws.recv()
            result = str(gzip.decompress(compressData).decode('utf-8'))
            print("EB:", result)
            if result[:7] == '{"ping"':
                ts = result[8:21]
                pong = '{"pong":' + ts + '}'
                ws.send(pong)
                ws.send(tradeStr)
            else:
                # judge=json.load(result)
                result_json = json.loads(result)
                # print(result_json)
                try:
                    sub_json = dict(result_json["tick"])
                    data = sub_json['data']
                    cur_price = float(data[0]['price'])
                    print(cur_price, price_high, price_low)
                    if cur_price >= price_high or cur_price <= price_low:
                        print("发送邮件")
                        subject = "EOS/BTC"
                        content = cur_price
                        ms = email_sender.email_sender()
                        ret = ms.mail(content, subject, mail)
                        print(ret)
                        if ret:
                            #thread=threading.current_thread()
                            count = 1
                            #thread.join()
                            #sys.exit()
                        #email_sender.mail()
                except:
                    pass
    def move_nas_usdt_huobi_gateio(self,rate):
        gateio=ccxt.gateio()
        huobi  = ccxt.huobipro()
        huobi.apiKey='7548cd5e-b95cad3b-33ebac0a-f809d'
        huobi.secret='63a58654-0cf1b5fa-9ded4823-a9165'
        gateio.apiKey="1C465DD1-3657-4AEB-B6AA-62F558F397ED"
        gateio.secret=""
        while True:
            try:
                depth_huobi=huobi.fetch_order_book("NAS/USDT",limit=7)

                depth_gateio=gateio.fetch_order_book("NAS/USDT",limit=7)

                huobi_bids=list(depth_huobi['bids'])
                hb_bids_1=list(huobi_bids[0])
        #买一价
                hb_bids_1_price=float(hb_bids_1[0])
        #买一量
                hb_bids_1_amount=float(hb_bids_1[1])
        #获取卖一
                hb_huobi_asks=list(depth_huobi['asks'])
                hb_asks_1=list(hb_huobi_asks[0])
        #卖一价
                hb_aks_1_price=float(hb_asks_1[0])
        #卖一量
                hb_asks_1_amount=float(hb_asks_1[1])


                gateio_bids=list(depth_gateio['bids'])
                gate_bids_1=list(gateio_bids[0])
                gate_bids_7=list(gateio_bids[-1])
                gate_bids_7_price=float(gate_bids_7[0])
                gate_bids_1_price=float(gate_bids_1[0])
                gate_bids_1_amout=float(gate_bids_1[1])
                gateio_asks=list(depth_gateio['asks'])
                gate_asks_7=list(gateio_asks[-1])
                gate_asks_1=list(gateio_asks[0])
                gate_asks_1_price=float(gate_asks_1[0])
                gate_asks_7_price=float(gate_asks_7[0])
                gate_asks_1_amout=float(gate_asks_1[1])


                condition_1=float((hb_bids_1_price-gate_asks_1_price)/gate_asks_1_price)
                condition_2=float((gate_bids_1_price-hb_aks_1_price)/hb_aks_1_price)
                print("CONDITION_1:",condition_1,"CONDITION_2:",condition_2)


                if condition_1>=rate or condition_2>=rate:
                #获取火币余额
                    self. times+=1
                    huobi_all_balance=dict(huobi.fetch_balance()["info"])
                    huobi_data=dict(huobi_all_balance["data"])
                    huobi_list=list(huobi_data["list"])
                    for i,val in enumerate(huobi_list):
                        val=dict(val)
                    #print(val)
                        if val["type"]=="trade" and val["currency"]=="usdt":
                            self.huobi_usdt_balance=float(val["balance"])
                        if val["type"]=="trade" and val["currency"]=="nas":
                            self.huobi_nas_balance=float(val["balance"])
                #获取gate余额
                    gateio_all_balance=dict(dict(gateio.fetch_balance()["info"])["available"])
                    self.gate_nas_balance=float(gateio_all_balance["NAS"])
                    self.gate_usdt_balance=float(gateio_all_balance["USDT"])
                    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"-----交易前----","gate_NAS余额:",self.gate_nas_balance,"gate_USDT 余额:",self.gate_usdt_balance,"火币_NAS余额:",self.huobi_nas_balance,"火币USDT余额:",self.huobi_usdt_balance,"交易前NAS总量:",(self.gate_nas_balance+self.huobi_nas_balance),"交易前USDT总和:",(self.huobi_usdt_balance+self.gate_usdt_balance))

                    #if condition_1>=rate and hb_asks_1_amount
                    #条件2
                    if condition_1>=rate and hb_asks_1_amount>=2 and gate_bids_1_amout>=2 and self.gate_usdt_balance>=gate_asks_1_price and self.huobi_nas_balance>=1:
                        print("火币卖,gate买")
                        huobi_sell_order=huobi.create_market_sell_order("NAS/USDT",1)
                        gate_buy_order=gateio.create_limit_buy_order("NAS/USDT",1/0.998,gate_asks_1_price*1.05)
                        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"--交易订单:[","火币卖单-",huobi_sell_order,"],[gate买单-",gate_buy_order,"]")
                        #print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"-----交易后----","gateNAS余额:",self.gate_nas_balance,"gate USDT 余额:",self.gate_usdt_balance,"火币NAS余额:",self.huobi_nas_balance,"火币USDT余额:",self.huobi_usdt_balance,"交易后NAS总量:",self.gate_nas_balance+self.huobi_nas_balance,"交易后USDT总和:",self.huobi_usdt_balance+self.gate_usdt_balance)
                        self.counter+=1

                    else:
                        if self.gate_usdt_balance<gate_asks_1_price:
                            print("gate_usdt余额不足!")
                            subject="gate_usdt余额不足!"
                            content="gate_usdt余额不足!"
                            ms=email_sender.email_sender()
                            ret=ms.mail(content,subject,"*****@*****.**")
                        elif self.huobi_nas_balance<1:
                            print("火币_NAS余额不足!")
                            subject="火币_NAS余额不足!"
                            content="火币_NAS余额不足!"
                            ms=email_sender.email_sender()
                            ret=ms.mail(content,subject,"*****@*****.**")
                        elif hb_asks_1_amount<2 and gate_bids_1_amout<2:
                            print("火币卖gate买交易量不满足")

                    if condition_2 >=rate and hb_asks_1_amount>=2 and gate_bids_1_amout>=2 and self.huobi_usdt_balance>=hb_bids_1_price and self.gate_nas_balance>=1 :
                        print("火币买,gate卖")
                        huobi_buy_order=huobi.create_market_buy_order("NAS/USDT",(hb_bids_1_price)*(1.005/0.998))
                        gate_sell_order=gateio.create_limit_sell_order("NAS/USDT",1,gate_bids_7_price*0.95)
                        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"--交易订单:[","火币买单-",huobi_buy_order,"],[gate卖单-",gate_sell_order,"]")
                        self.counter+=1
                        #print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"-----交易后----","gateNAS余额:",self.gate_nas_balance,"gate USDT 余额:",self.gate_usdt_balance,"火币NAS余额:",self.huobi_nas_balance,"火币USDT余额:",self.huobi_usdt_balance,"交易后NAS总量:",self.gate_nas_balance+self.huobi_nas_balance,"交易后USDT总和:",self.huobi_usdt_balance+self.gate_usdt_balance)
                    else:
                        if self.huobi_usdt_balance<hb_bids_1_price:
                            print("火币_usdt余额不足!")
                            subject="火币_usdt余额不足!"
                            content="火币_usdt余额不足!"
                            ms=email_sender.email_sender()
                            ret=ms.mail(content,subject,"*****@*****.**")
                        elif self.gate_nas_balance<1:
                            print("GATE_NAS余额不足!")
                            subject="GATE_NAS余额不足!"
                            content="GATE_NAS余额不足!"
                            ms=email_sender.email_sender()
                            ret=ms.mail(content,subject,"*****@*****.**")
                        elif hb_asks_1_amount<2 and gate_bids_1_amout<2:
                            print("火币买gate卖交易量不满足")
                #time.sleep(0.0005)
                print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),"--已搬砖次数:",self.counter,"--检测到可搬砖次数:",self.times)
            except:
                pass