예제 #1
0
 def _qrcode(self, data, style='img'):
     logger.debug(data)
     if style == 'img':
         image = qrcode.make(data)
         image.save('qrcode.png')
     elif style == 'terminal':
         qrcode_terminal.draw(data)
예제 #2
0
def new_session():
    session_id, session_key = query_create_meeting()
    enc_recn(session_key)
    upload_recn(session_id, session_key)
    os.system("rm " + session_key)
    qrcode_terminal.draw(server_url + "/app/" + session_id)  # TODO
    return session_id
예제 #3
0
def use_text_mode(args):
    if args.command == "qrcode":
        system_config = json.loads(file.read_file("./config/system.json"))
        from common import install_module
        install_module.install_and_import("qrcode_terminal")
        import qrcode_terminal
        if len(system_config["API_Password"]) == 0 or len(system_config["Project_URL"]) == 0:
            console.log("Error", "Check the API_Password and Project_URL configuration items")
            exit(1)
        try:
            password_md5 = json.loads(system_config["API_Password"])["hash_password"]
        except (ValueError, KeyError, TypeError):
            exit(1)
        console.log("Info", "Please use the client to scan the following QR Code")
        config_json = json.dumps({"url": system_config["Project_URL"], "password": password_md5})
        qrcode_terminal.draw(config_json)
        exit(0)
    if args.command == "upgrade":
        from manage import upgrade
        if upgrade.upgrade_check():
            if not args.yes:
                start_to_pull = input('Find new version, do you want to upgrade? [y/N]')
            if start_to_pull.lower() == 'yes' or start_to_pull.lower() == 'y' or args.yes:
                upgrade.upgrade_pull()
                exit(0)
        console.log("Info", "No upgrade found")
        exit(0)
    if args.command == "build-page":
        from manage import build_static_page
        build_static_page.publish()
        exit(0)
    from manage import build_rss, post_manage
    if args.command == "new":
        config = None
        if args.config is not None:
            config = json.loads(file.read_file(args.config))
        if config is None:
            print("Please enter the title of the article:")
            title = input().strip()
            if len(title) == 0:
                console.log("Error", "The title can not be blank.")
                exit(1)
            name = get.get_name(title)
            print("Please enter the slug [{}]:".format(name))
            name2 = input().strip()
            if len(name2) != 0:
                name = get.filter_name(name2)
            if os.path.exists("./document/{}.md".format(name)):
                console.log("Error", "File [./document/{}.md] already exists".format(name))
                exit(1)
        if len(name) != 0 and len(title) != 0:
            config = {"title": title, "name": name}
            post_manage.new_post(config, args.independent)
            build_rss.build_rss()
        exit(0)
    if args.command == "update":
        if post_manage.update_post():
            build_rss.build_rss()
        exit(0)
예제 #4
0
def generate(id):
    psecret = pyotp.random_base32()
    file_path = open('totpauth/' + str(id) + '.txt', 'a')
    file_path.write(psecret)
    #os.system('echo ' + psecret + '>totpauth/' + str(id) + '.txt')
    print('Scan the QR or input this code manually: ' + psecret)
    qrcode_terminal.draw(
        pyotp.totp.TOTP(psecret).provisioning_uri(str(id) + "@example",
                                                  issuer_name="Lock"))
예제 #5
0
def drawqrcode():
    """扫码登陆

    使用扫码登陆,待补充
    """
    URL = decode(Image.open('111.png'), symbols=[
                 pyzbar.pyzbar.ZBarSymbol.QRCODE])

    qrcode_terminal.draw(URL)
예제 #6
0
def show_qrcode_in_terminal(image_file):
    img = Image.open(image_file)
    result = decode(img)

    data = None
    for i in result:
        data = i.data.decode("utf-8")

    qr_code_info = data
    qrcode_terminal.draw(data, 5)
    return qr_code_info
예제 #7
0
 def generate_login_qrcode(self):
     r = self.res.get(
         'https://login.dingtalk.com/user/qrcode/generate.jsonp?callback=angular.callbacks._0'
     )
     html = re.findall('\((.*?)\)', r.text, re.S)[0]
     callback = json.loads(html)
     if callback['success'] == True:
         self.code = callback['result']
         self.qr_url = 'http://qr.dingtalk.com/action/login?code=' + self.code
         qrcode_terminal.draw(self.qr_url, 3)
         # callback['result']
     else:
         print('Error01:返回值为否')
    def handle(self, **options):
        username = options['user']
        user_model = get_user_model()

        try:
            user = user_model.objects.get(username=username)
        except user_model.DoesNotExist:
            self.log_message(f"User {username} not found.")
            return False

        token, created = Token.objects.get_or_create(user=user)

        if not created:
            self.log_message(f"{username} already has a token assigned.")
            return False

        token.save()
        qrcode_terminal.draw(token.qr)
예제 #9
0
async def _test_main():
    jd = JDQrCode()
    await jd.init()
    qrcode_terminal.draw(await jd.generate_jd_qrcode_url())
    print("成功生成二维码,请扫码登录狗东商城。")
    await asyncio.sleep(10)
    while True:
        errcode, cookie, resp_json = await jd.get_jd_cookie()
        if errcode == 0:
            print("\n扫码登录成功\n")
            print(cookie)
        elif errcode == 21:
            print("二维码失效\n")
        elif errcode == 176:
            await asyncio.sleep(5)
            continue
        else:
            print(f"其他异常: {resp_json}")
        break
예제 #10
0
    def channel_payment(self, arguments):
        """

        :param arguments:
        :return:
        """
        asset_type = get_arg(arguments, 1)
        if not check_support_asset_type(asset_type):
            console_log.error(
                "No support asset, current just support {}".format(
                    SupportAssetType.SupportAssetType))
            return None
        value = TrinityNumber(get_arg(arguments, 2).strip()).number
        if not value:
            console_log.error("command not give the count")
            return None
        try:
            if 0 >= value or not check_float_decimals(value, asset_type):
                console_log.error("value should not be less than 0")
                return None
        except ValueError:
            console_log.error("value format error")
            return None
        comments = " ".join(arguments[3:])
        comments = comments if comments else "None"
        if len(comments) > 128:
            console_log.error("comments length should be less than 128")
            return None
        try:
            hash_r, rcode = Payment.create_hr()
            Channel.add_payment(None, hash_r, rcode, value)
            paycode = Payment.generate_payment_code(self.Wallet.url,
                                                    asset_type, value, hash_r,
                                                    comments, True)
        except Exception as e:
            LOG.error(e)
            console_log.error("Get payment link error, please check the log")
            return None
        if self.qrcode:
            qrcode_terminal.draw(paycode, version=4)
        console_log.console(paycode)
        return None
예제 #11
0
 def QR(self, name, secretKey):
     qr = qrcode.QRCode(version=1,
                        error_correction=qrcode.constants.ERROR_CORRECT_H,
                        box_size=7,
                        border=4)
     qrdata = f'otpauth://totp/{name}?secret={secretKey}'
     qr.add_data(qrdata)
     qr.make(fit=True)
     img = qr.make_image()
     img.save("/tmp/test.png")
     return qrcode_terminal.draw(qrdata)
예제 #12
0
파일: zhihu.py 프로젝트: DLHTX/zhihu_py
 def checkQuestion(self):
     type = input('翻页输入s 返回首页输入q 手机观看输入qr :')
     if type == 's':
         if self.isend == False:
             url = self.qRes['paging']['next']
             self.question(url)
             print('下一个回答' + '*' * 50)
         else:
             print('无更多回答!正在返回首页')
             time.sleep(2)
             self.recommend()
     elif type == 'q':
         self.recommend()
     elif type == 'qr':  ##打印二维码
         url = 'https://www.zhihu.com/question/' + str(
             self.question_id) + '/answer/' + str(self.answer_id)
         qrcode_terminal.draw(url)
         self.checkQuestion()
     else:
         print('输入错误')
         self.checkQuestion()
예제 #13
0
	def getQRcode(self):

		global	hostname

		url = 'https://%s/v2/users/%s' \
			'/authenticators/%s/activation_string/v2.txt' % \
			( hostname, self.userId, self.authenticatorId )

		headers = {
			'Content-Type':		'application/json',
			'accept':		'application/json',
			'bcaccesskey':		self.bcaccesskey,
			'bcentitykey':		self.bcentitykey,
			'bctoken':		self.bctoken
		}

		# Send our GET request to the server
		result = requests.get(url, headers=headers)

		if result == False:
			# Error: we did not receive an HTTP/200
			print(headers)
			print(result.content)
			sys.exit("Error: unable to get QR code")

		try:
			# Parse the JSON reply
			reply = json.loads(result.content.decode('utf-8'))

		except ValueError:
			print(headers)
			print(result.content)
			sys.exit("Error: unexpected reply for QR code")
	
		# Extract the activation URL for this mobile phone
		activationString = reply.get("activation_string","")

		# Display the QR code on the terminal
		qrcode_terminal.draw(activationString)
		print("%s\n" % activationString)
예제 #14
0
def inialize():
    '''
    Initializes ip address, port.
    Asks user if they want to view qr code.
    Checks if OS  is recognized or not.
    '''
    ip_addr = find_ip()
    port_number = 8000

    ask = input("do you want to see the qr Code? ")

    if ask.lower() == 'y' or ask.lower() == 'yes':
        qrcode_terminal.draw(f'http://{ip_addr}:{port_number}')
    else:
        print('-' * 50 + '\n' * 5)
        print(f"Type this in Apple watch app =>  {ip_addr}:{port_number}")
        print('\n' * 5 + '-' * 50)

    print("\n\nminimize this application\n\n")
    print("Your ip:", ip_addr)
    print("Port:", port_number)
    print("OS:", myOS.name)

    return (ip_addr, port_number)
예제 #15
0
def inialize():
    """
    Initializes ip address, port.
    Asks user if they want to view qr code.
    Checks if OS  is recognized or not.
    """
    ip = find_ip()
    port_num = 8000

    ask = input("do you want to see the qr Code? ")

    if ask.lower() == "y" or ask.lower() == "yes":
        qrcode_terminal.draw(f"http://{ip}:{port_num}")
    else:
        print("-" * 50 + "\n" * 5)
        print(f"Type this in Apple watch app =>  {ip}:{port_num}")
        print("\n" * 5 + "-" * 50)

    print("\n\nminimize this application\n\n")
    print("Your ip:", ip)
    print("Port:", port_num)
    print("OS:", myOS.name)

    return (ip, port_num)
예제 #16
0
#   Autor: Arthur Novais
#

# server.py
import qrcode_terminal as qr
import netifaces as ni
import sys
import os

PORT = 9000

ip = ni.ifaddresses('eno1')[ni.AF_INET][0]['addr']
server = "http://" + ip + ":" + str(PORT)

print("The server is running on", server)

srv = "python3 -m http.server " + str(PORT)

try:
    dir = sys.argv[1]
    command = srv + " -d " + str(dir)

    print("Vai abrir um servidor em ", srv, dir)

    #print(command)
    qr.draw(server)
    os.system(command)

except:
    print("Error")
예제 #17
0
import qrcode_terminal

print(
    ' \n \033[1;31;0m  \033[1;31m 在这个1024的特殊日子里 扫描下面👇代码生产的二维码,和我一起守护艾泽拉斯吧~ (长按识别有惊喜哟) \n'
)

qrcode_terminal.draw('https://www.ruoduan.cn/css/images/wechatImage.jpg')
예제 #18
0
from time import sleep
import socket
import qrcode
from PIL import Image
import qrcode_terminal

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))  # this sees if device is connected to internet
ip = s.getsockname()[0]
s.close()

port_num = 8000

ask = input("do you want to see the qr Code? ")
if ask.lower() == 'y' or ask.lower() == 'yes':
    qrcode_terminal.draw(f'http://{ip}:{port_num}')
print('-' * 10)
print(f"\n Type this in Apple watch app =>  {ip}:{port_num}\n")
print('-' * 10)

app = Flask(__name__)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/press")
def do_press():
    # query is key and the default value is None
예제 #19
0
def vw_show_conf(args: argparse.Namespace) -> int:

    conf_content: str = ""
    network_name, node_name = args.interface[0], args.nodes

    # config = common.Config()
    # if not config.load(network_name):
    #     print("vwgen: Unable to find configuration file '{}.conf'".format(
    #         network_name),
    #           file=sys.stderr)
    #     return errno.ENOENT
    config = args.config
    network = config.network()
    nodes = config.nodes()
    blacklist = config.blacklist()

    if node_name not in nodes:
        print("vwgen: Network '{}' does not have node '{}'".format(
            network_name, node_name),
              file=sys.stderr)
        return errno.ENOENT
    node = nodes[node_name]

    print()

    conf_content += '[Interface]\n'
    conf_content += 'ListenPort = {:d}\n'.format(node.get('ListenPort', 0))

    if 'PrivateKey' in node:
        conf_content += 'PrivateKey = {}\n'.format(node['PrivateKey'])
    if 'LinkLayerAddress' in node:
        conf_content += 'Address = {}\n'.format(', '.join(
            node['LinkLayerAddress']))
    conf_content += 'MTU = {}\n'.format(
        int(network.get('VxlanMTU', 1500)) + 50)
    conf_content += 'Table = off\n'
    if node.get('FwMark', 0) != 0:
        conf_content += 'FwMark = {:x}\n'.format(node['FwMark'])

    if node.get('SaveConfig', False):
        conf_content += 'SaveConfig = true\n'
    for script in node.get('PreUp', []):
        conf_content += 'PreUp = {}\n'.format(script)
    mac_address = common.generate_pubkey_macaddr(node)
    mac_address_cmdline = ''
    if mac_address:
        mac_address_cmdline = 'address {} '.format(mac_address)

    conf_content += 'PreUp = ip link add v%i {}mtu {} type vxlan id {} dstport {} ttl 1 noudpcsum || true\n'.format(
        mac_address_cmdline, network.get('VxlanMTU', 1500),
        network.get('VxlanID', 0), network.get('VxlanPort', 4789))

    conf_content += 'PreUp = ethtool -K v%i tx off rx off\n'
    conf_content += 'PreUp = sysctl -w net.ipv4.conf.v%i.accept_redirects=0 net.ipv4.conf.v%i.send_redirects=0 net.ipv6.conf.v%i.accept_redirects=0\n'
    for address in node.get('Address', []):
        conf_content += 'PreUp = ip address add {} dev v%i || true\n'.format(
            address)
    pubkey_ipv6 = common.generate_pubkey_ipv6(network, node)
    if pubkey_ipv6:
        conf_content += 'PreUp = ip address add {} dev v%i || true\n'.format(
            pubkey_ipv6)
    if node.get('UPnP', False) and node.get('ListenPort', 0) != 0:
        conf_content += 'PreUp = upnpc -r {} udp &\n'.format(
            node['ListenPort'])
    for peer_name, peer in nodes.items():
        if peer_name == node_name:
            continue
        in_blacklist = common.NamePair(node_name, peer_name) in blacklist
        comment_prefix = '#' if in_blacklist else ''

        for address in peer.get('LinkLayerAddress', []):
            conf_content += '{}PostUp = bridge fdb append 00:00:00:00:00:00 dev v%i dst {} via %i\n'.format(
                comment_prefix,
                str(address).split('/', 1)[0])
 
    conf_content += 'PostUp = ip link set v%i up\n'
    for script in node.get('PostUp', []):
        conf_content += 'PostUp = {}\n'.format(script)
    for script in node.get('PreDown', []):
        conf_content += 'PreDown = {}\n'.format(script)
    conf_content += 'PreDown = ip link set v%i down\n'
    conf_content += 'PostDown = ip link delete v%i\n'

    for script in node.get('PostDown', []):
        conf_content += 'PostDown = {}\n'.format(script)
    conf_content += '\n'

    for peer_name, peer in nodes.items():
        if peer_name == node_name:
            continue
        in_blacklist = common.NamePair(node_name, peer_name) in blacklist
        comment_prefix = '#' if in_blacklist else ''
        conf_content += '{}# Peer node {}\n'.format(comment_prefix, peer_name)
        conf_content += '{}[Peer]\n'.format(comment_prefix)

        if peer.get('PrivateKey'):
            secret_base64: str = peer['PrivateKey']
            secret: bytes = binascii.a2b_base64(secret_base64)
            if len(secret) != 32:
                print("vwgen: Node '{}' has incorrect PrivateKey".format(
                    peer_name),
                      file=sys.stderr)
            else:
                pubkey = binascii.b2a_base64(common.pubkey(secret),
                                             newline=False).decode('ascii')
                conf_content += '{}PublicKey = {}\n'.format(
                    comment_prefix, pubkey)

        if peer.get('AllowedIPs'):
            conf_content += '{}AllowedIPs = {}\n'.format(
                comment_prefix, ', '.join(peer['AllowedIPs']))
        if peer.get('Endpoint'):
            conf_content += '{}Endpoint = {}\n'.format(comment_prefix,
                                                       peer['Endpoint'])
        if peer.get('PersistentKeepalive', 0) != 0:
            conf_content += '{}PersistentKeepalive = {}\n'.format(
                comment_prefix, node['PersistentKeepalive'])
        conf_content += '\n'
    print(conf_content)
    if args.qr_printable:
        qrcode_terminal.draw(conf_content)

    return 0
예제 #20
0
def _generateKeys(master_wallet,
                  user_index,
                  number_of_accounts,
                  extra_data=None):
    directory = tempfile.mkdtemp()
    user_key = master_wallet.get_child(user_index,
                                       is_prime=True)  # m/user_index'

    data = {
        'user_key': user_key.serialize_b58(),
        'accounts': [],
    }
    if extra_data:
        data.update(extra_data)

    first = None
    for idx in range(number_of_accounts):
        account_entry = {}
        child = user_key.get_child(0).get_child(
            idx)  # m/user_index'/0/idx BIP32 compliant external accounts

        if idx == 0:
            first = child

        account_entry['wif'] = child.export_to_wif()
        account_entry['address'] = child.to_address()

        img = qrcode.make(account_entry['wif'])
        qr_filename = os.path.join(directory,
                                   'child{}.priv.png'.format(idx + 1))
        img.save(qr_filename)

        img = qrcode.make(account_entry['address'])
        qr_filename = os.path.join(directory,
                                   'child{}.pub.png'.format(idx + 1))
        img.save(qr_filename)

        data['accounts'].append(account_entry)

    if 'master_shard' in data:
        salt = os.urandom(SALT_LENGTH)
        shard = data.pop('master_shard')
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=salt,
                         iterations=100000,
                         backend=default_backend())
        words = [word_gen.next() for x in range(PASSPHRASE_WORD_LENGTH)]
        passphrase = ' '.join(words)
        key = base64.urlsafe_b64encode(kdf.derive(passphrase))
        f = Fernet(key)
        token = f.encrypt(shard)

        data['encrypted_shard'] = '{}${}'.format(
            base64.urlsafe_b64encode(salt), base64.urlsafe_b64encode(token))
        data['passphrase'] = passphrase
        shard_img = qrcode.make(data['encrypted_shard'])
        shard_img_filename = os.path.join(
            directory, 'child{}_shard.png'.format(user_index + 1))
        shard_img.save(shard_img_filename)

    filename = os.path.join(directory,
                            'user_info.priv.json'.format(user_index + 1))
    json_data = json.dumps(data)
    with open(filename, 'w+b') as f:
        f.write(json_data)

    _print(('Key for user {user_index}:\n'
            'Data has been written to {filename}\n'
            'QR codes have been written for {number_of_accounts} account(s)'
            ).format(number_of_accounts=number_of_accounts,
                     filename=filename,
                     user_index=user_index + 1),
           formatters=[term.clear, term.blue])
    _print()
    _print('Take the time to copy these files before continuing\n'
           'After leaving this screen, the files will be destroyed')
    _print()
    _print(
        'BE EXTREMELY CAREFUL WITH THE ACCOUNT AND SHARD INFORMATION\n'
        'Especially when handling data in the QR form. A picture of the QR code may be enough to steal your entire account\n'
        'and potentially compromise the other linked accounts',
        formatters=[term.red, term.bold])
    _print()

    if first:
        _print(
            'Your first account address is being displayed here for your convenience'
        )
        _print()
        address = first.to_address()
        _print(address)
        _print()
        qrcode_terminal.draw(address)
        _print()
    _get_input('Press enter to continue when ready')

    shutil.rmtree(directory)
    _print(term.clear)
예제 #21
0
    def run(self):
        #开启一个session会话用来获取基础cookies以及获取二维码及其cookies
        base = requests.session()
        #访问获取基础cookies的地址
        result = base.get(self.login_get_cookies_url)
        base_cookies = result.cookies  #基础cookies
        #获取二维码图片并获取二维码cookies
        result = base.get(self.get_ptqrshow)
        ptqr_cookies = result.cookies  #二维码cookies
        #将二维码图片上传解码后进行二维码生成并打印到终端
        self.code.write(result.content)
        self.code.close()
        cookies = dict(base_cookies.items() + ptqr_cookies.items())
        #进行ptqrtoken计算
        qrsig = cookies['qrsig']
        e = 0
        n = len(qrsig)
        for i in range(0, n):
            e = e + (e << 5) + ord(qrsig[i])
        ptqrtoken = 2147483647 & e
        #计算完成
        #上传二维码图片解码,然后打印二维码到控制台
        try:
            rtext = requests.post(self.jm,
                                  files={'file': open('code.png', 'rb')})
        except Exception as e:
            self.logger.debug('upload qcord error')
        if rtext.status_code == 200:
            try:
                jtext = json.loads(rtext.text)
            except ValueError as e:
                self.logger.error('二维码解析返回不正常')
                return {'result': '-1', 'reason': '二维码解析返回不正常'}
            self.logger.info('请扫描屏幕中的二维码')
            url = jtext['jiema']
            #将二维码打印到控制台
            qrcode_terminal.draw(url)
            #循环验证二维码状态
            l = 0
            k = 0
            j = 0
            while True:
                result = requests.get(
                    "https://ssl.ptlogin2.qq.com/ptqrlogin?ptqrtoken=" +
                    str(ptqrtoken) +
                    "&webqq_type=10&remember_uin=1&login2qq=1&aid=501004106&u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=0-0-32750&mibao_css=m_webqq&t=undefined&g=1&js_type=0&js_ver=10197&login_sig=&pt_randsalt=0",
                    cookies=cookies)
                if '二维码未失效' in result.text:
                    if l == 0:
                        self.logger.info('二维码未失效,等待扫码验证中')
                        l = l + 1
                if '已失效' in result.text:
                    if k == 0:
                        self.logger.info('二维码已经失效')
                        k = k + 1
                        return {'result': '-1', 'reason': '二维码已经失效'}
                if '认证中' in result.text:
                    if j == 0:
                        self.logger.info('二维码已被扫描,正在认证中')
                        j = j + 1
                if '登录成功' in result.text:
                    checksig_url = result.text.split("','")[2]
                    user_cookies = result.cookies
                    break
                time.sleep(1)
            #获取cookie中ptwebqq
            ptwebqq = user_cookies['ptwebqq']
            result = requests.get(checksig_url,
                                  cookies=user_cookies,
                                  allow_redirects=False)
            user2_cookies = result.cookies
            #合并两个cookies
            user3_cookies = dict(user_cookies.items() + user2_cookies.items())
            #获取vfwebqq
            headers = {
                "Referer":
                "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1"
            }
            vfwebqq = requests.get(self.getvfwebqq.replace(
                '{ptwebqq}', ptwebqq),
                                   cookies=user3_cookies,
                                   headers=headers).text
            vfwebqq = json.loads(vfwebqq)['result']['vfwebqq']
            #二次登陆,真正的登录
            data = {
                'r':
                '{"ptwebqq":"' + ptwebqq +
                '","clientid":53999199,"psessionid":"","status":"online"}'
            }
            headers = {
                'Host': 'd1.web2.qq.com',
                'Referer':
                'http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2',
                'Origin': 'http://d1.web2.qq.com'
            }
            result = requests.post(self.login2,
                                   data=data,
                                   cookies=user3_cookies,
                                   headers=headers)
            jresult = json.loads(result.text)
            if jresult['retcode'] == 0:
                self.logger.info('登录成功')
                uin = jresult["result"]["uin"]
                headers = {
                    'Host':
                    'd1.web2.qq.com',
                    'Referer':
                    'http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2'
                    ''
                }
                requests.get(self.online.replace('{vfwebqq}', vfwebqq).replace(
                    '{psessionid}', jresult['result']['psessionid']),
                             cookies=user3_cookies,
                             headers=headers)
                return {
                    'result': '0',
                    'reason': '登录成功',
                    'cookies': user3_cookies,
                    'psessionid': jresult['result']['psessionid'],
                    'vfwebqq': vfwebqq,
                    'uin': uin
                }
            else:
                self.logger.info('登录失败')
                return {'result': '-2', 'reason': '登录失败'}

        else:
            self.logger.error('解码发生错误,系统即将退出')
            return {'result': '-1', 'reason': '解码发生错误,系统即将退出'}
예제 #22
0
    def showQrcodeTerminal(self):

        qcode = "https://login.weixin.qq.com/l/" + self.uuid
        # qt is qrcode_terminal lib
        qt.draw(qcode)
예제 #23
0
파일: menu.py 프로젝트: fossabot/silverblog
def use_text_mode(args):
    if args.command == "qrcode":
        system_config = json.loads(file.read_file("./config/system.json"))
        try:
            import qrcode_terminal
        except ImportError:
            console.log(
                "Error",
                "Please install the qrcode-terminal package to support this feature"
            )
            install_dependency = input(
                'Do you want to install qrcode-terminal now? [y/N]')
            if install_dependency.lower() == 'yes' or install_dependency.lower(
            ) == 'y':
                import os
                os.system("python3 -m pip install qrcode-terminal")
        if len(system_config["API_Password"]) == 0 or len(
                system_config["Project_URL"]) == 0:
            console.log(
                "Error",
                "Check the API_Password and Project_URL configuration items")
            exit(1)
        try:
            password_md5 = json.loads(
                system_config["API_Password"])["hash_password"]
        except (ValueError, KeyError, TypeError):
            exit(1)
        console.log("Info",
                    "Please use the client to scan the following QR Code")
        config_json = json.dumps({
            "url": system_config["Project_URL"],
            "password": password_md5
        })
        qrcode_terminal.draw(config_json)
        exit(0)
    if args.command == "upgrade":
        from manage import upgrade
        if upgrade.upgrade_check():
            start_to_pull = input(
                'Find new version, do you want to upgrade? [y/N]')
            if start_to_pull.lower() == 'yes' or start_to_pull.lower() == 'y':
                upgrade.upgrade_pull()
                exit(0)
        console.log("info", "No upgrade found")
        exit(0)
    if args.command == "build-page":
        from manage import build_static_page
        build_static_page.publish()
        exit(0)

    from manage import build_rss
    if args.command == "new":
        from manage import new_post
        config = None
        if args.config is not None:
            config = json.loads(file.read_file(args.config))
        if config is None:
            print("Please enter the title of the article:")
            title = input()
            if len(title) != 0:
                name = new_post.get_name(title)
            print("Please enter the slug [{}]:".format(name))
            name2 = input()
            if len(name2) != 0:
                name = name2
        if len(name) != 0 and len(title) != 0:
            config = {"title": title, "name": name}
            new_post.new_post_init(config, args.independent)
            build_rss.build_rss()
        exit(0)
    if args.command == "update":
        from manage import update_post
        if update_post.update():
            build_rss.build_rss()
        exit(0)
예제 #24
0
 def _qrcode(self, data, style='img'):
     logger.debug(data)
     if style == 'img':
         qrcode.make(data)
     elif style == 'terminal':
         qrcode_terminal.draw(data)
예제 #25
0
def main():
    """
    Run autosub as a command-line program.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('source_path', help="Path to the video or audio file to subtitle",
                        nargs='?')
    parser.add_argument('-C', '--concurrency', help="Number of concurrent API requests to make",
                        type=int, default=DEFAULT_CONCURRENCY)
    parser.add_argument('-o', '--output',
                        help="Output path for subtitles (by default, subtitles are saved in \
                        the same directory and name as the source path)")
    parser.add_argument('-F', '--format', help="Destination subtitle format",
                        default=DEFAULT_SUBTITLE_FORMAT)
    parser.add_argument('-S', '--src-language', help="Language spoken in source file",
                        default=DEFAULT_SRC_LANGUAGE)
    parser.add_argument('-D', '--dst-language', help="Desired language for the subtitles",
                        default=DEFAULT_DST_LANGUAGE)
    parser.add_argument('-K', '--api-key',
                        help="The Google Translate API key to be used. \
                        (Required for subtitle translation)")
    parser.add_argument('--list-formats', help="List all available subtitle formats",
                        action='store_true')
    parser.add_argument('--list-languages', help="List all available source/destination languages",
                        action='store_true')

    args = parser.parse_args()

    if args.list_formats:
        print("List of formats:")
        for subtitle_format in FORMATTERS:
            print("{format}".format(format=subtitle_format))
        return 0

    if args.list_languages:
        print("List of all languages:")
        for code, language in sorted(LANGUAGE_CODES.items()):
            print("{code}\t{language}".format(code=code, language=language))
        return 0

    if not validate(args):
        return 1

    try:
        if BAIDU_APIKEY == '' and BAIDU_SKEY == '' and BAIDU_TOKEN == '':
            qrcode_terminal.draw("https://u.wechat.com/EKIKepo_1J_khuq9avrjPgE")
            print("由于没有设置百度开发者key,无法进行语音转字幕")
            print("扫描以上的二维码加我微信好友,获取临时token,可以使用24小时")
            print("然后打开autosub/constants.py 将临时token填入到BAIDU_TOKEN中即可")
            return 1

        subtitle_file_path = generate_subtitles(
            source_path=args.source_path,
            concurrency=args.concurrency,
            src_language=args.src_language,
            dst_language=args.dst_language,
            api_key=args.api_key,
            subtitle_file_format=args.format,
            output=args.output,
        )
        print("Subtitles file created at {}".format(subtitle_file_path))
    except KeyboardInterrupt:
        return 1

    return 0
예제 #26
0
e_headers = ['名字', '备注名字', '签名', '性别', '省份', '城市']
headers = {
    'User-Agent':
    'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'
}
try:

    url = 'https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage&fun=new&lang=zh_CN&_=1530078655980'
    html = request.urlopen(url)
    mybytes = html.read()
    mybytes = str(mybytes, encoding="utf-8")
    pm = re.findall(r"\"\w+==\"", mybytes)
    uuid = pm[0]
    uuid = uuid[1:-1]

    qrcode_terminal.draw('https://login.weixin.qq.com/l/' + uuid)
    print('-' * 12 + "请扫码登录" + '-' * 12)
    while (1):
        urlogin = "******" + uuid + "&tip=0&r=-1224738251&_=1530233069169"
        html_Login = request.urlopen(urlogin)
        loginCode = re.findall(r"\d\d\d", html_Login.read().decode('utf-8'))
        if loginCode[0] == '201':
            print('-' * 12 + "扫码成功" + '-' * 12)
            print('-' * 10 + "请在手机点击登录" + '-' * 9)
        elif loginCode[0] == '200':
            print('-' * 12 + "登录成功" + '-' * 12)
            break
    urlogin = "******" + uuid + "&tip=0&r=-1224738251&_=1530233069169"
    html_Login = request.urlopen(urlogin)
    loginURL = html_Login.read().decode('utf-8')[38:-2]
예제 #27
0
import pyotp
import qrcode_terminal
import io

# key = pyotp.random_base32()
key = 'mhayk'
output = pyotp.totp.TOTP(key).provisioning_uri("*****@*****.**",
                                               issuer_name="Mhayk Python App")

# stream = io.StringIO()
print(key)
qrcode_terminal.draw(output)
예제 #28
0
 def _run(self):
     #开启一个会话
     session = requests.session()
     result = session.get(self.get_base_cookies)
     if result.status_code == 200:
         header = {
             'Host': 'login.wx.qq.com',
             'Referer': 'https://wx.qq.com/'
         }
         result = session.get(self.get_ptqr_url, headers=header)
         if result.status_code == 200:
             pat = re.compile('window.QRLogin.uuid = "(.*?)"', re.S)
             self.target = pat.findall(result.text)
             if len(self.target) == 1:
                 qrcode = self.qrcode + self.target[0]
                 self.logger.info('正在获取二维码图片')
                 result = session.get(qrcode)
                 self.code.write(result.content)
                 self.code.close()
                 try:
                     rtext = requests.post(
                         self.jm, files={'file': open('code.png', 'rb')})
                 except Exception as e:
                     self.logger.debug('upload qcord error')
                 if rtext.status_code == 200:
                     try:
                         jtext = json.loads(rtext.text)
                     except ValueError as e:
                         self.logger.error('二维码解析返回不正常')
                         return {'result': '-1', 'reason': '二维码解析返回不正常'}
                     self.logger.info('请扫描屏幕中的二维码')
                     url = jtext['jiema']
                     # 将二维码打印到控制台
                     qrcode_terminal.draw(url)
                     self.logger.info('二维码获取结束')
                     flag = True
                     while flag:
                         result = requests.get(
                             self.check.replace('{uuid}', self.target[0]))
                         pat = re.compile('window.code=(.*?);', re.S)
                         self.c = pat.findall(result.text)
                         if self.c[0] == '200':
                             self.logger.info('登录成功')
                             break
                         if self.c[0] == 408:
                             self.logger.info('等待扫码')
                         if self.c[0] == 201:
                             self.logger.info('扫码成功,请在手机端点击确认')
                     pat = re.compile('window.redirect_uri="(.*?)";', re.S)
                     self.redurl = pat.findall(result.text)
                     if len(self.redurl) == 1:
                         url = self.redurl[0]
                         result = requests.get(url, allow_redirects=False)
                         real_cookies = result.cookies
                         for node in xml.dom.minidom.parseString(
                                 result.text).documentElement.childNodes:
                             if len(node.childNodes) == 0:
                                 continue
                             else:
                                 data = node.childNodes[0].data
                                 if node.nodeName == 'ret':
                                     self.info['ret'] = data
                                     if data == '0':
                                         continue
                                     else:
                                         self.logger.info('登录失败')
                                         break
                                 if node.nodeName == 'skey':
                                     self.info['skey'] = data
                                 if node.nodeName == 'wxsid':
                                     self.info['wxsid'] = data
                                 if node.nodeName == 'wxuin':
                                     self.info['wxuin'] = data
                                 if node.nodeName == 'pass_ticket':
                                     self.info['pass_ticket'] = data
                                 if node.nodeName == 'isgrayscale':
                                     self.info['isgrayscale'] = data
                         if self.info['ret'] == '0':
                             self.info['DeviceID'] = 'e' + repr(
                                 random.random())[2:17]
                             header = {
                                 "Host": "wx2.qq.com",
                                 "Origin": "https://wx2.qq.com",
                                 "Referer":
                                 "https://wx2.qq.com/?&lang=zh_CN"
                             }
                             data = json.dumps({
                                 "BaseRequest": {
                                     "Uin": self.info['wxuin'],
                                     "Sid": self.info['wxsid'],
                                     "Skey": self.info['skey'],
                                     "DeviceID": self.info['DeviceID']
                                 }
                             })
                             #初始化
                             result = requests.post(
                                 self.baseinfo + self.info['pass_ticket'],
                                 cookies=real_cookies,
                                 headers=header,
                                 data=data)
                             result.encoding = "utf-8"
                             jresult = json.loads(result.text)
                             if jresult['BaseResponse']['Ret'] == 0:
                                 SyncKey = jresult['SyncKey']['List']
                                 uin = jresult['User']['Uin']
                                 username = jresult['User']['UserName']
                                 skey = jresult['SKey']
                                 data = {
                                     'BaseRequest': {
                                         'Uin':
                                         uin,
                                         'Sid':
                                         self.info['wxsid'],
                                         'Skey':
                                         skey,
                                         'DeviceID':
                                         'e' + repr(random.random())[2:17]
                                     },
                                     'Code': 3,
                                     'FromUserName': username,
                                     'ToUserName': username,
                                     'ClientMsgId': '1488531367081'
                                 }
                                 data = json.dumps(data)
                                 result = requests.post(
                                     self.statusnotify,
                                     cookies=real_cookies,
                                     headers=header,
                                     data=data)
                                 result.encoding = "utf-8"
                                 reparam = {
                                     'SyncKey': SyncKey,
                                     'Uin': uin,
                                     'Sid': self.info['wxsid'],
                                     'Skey': skey,
                                     'cookies': real_cookies,
                                 }
                             else:
                                 self.logger.info('登录失败')
                                 return False
                         else:
                             return False
                     else:
                         self.logger.info('登录失败,可能是二维码已超时')
                         return False
                 else:
                     self.logger.info('网络连接有问题,请检查后重试')
                     return False
             else:
                 self.logger.info(
                     '网络出错,请在github上给我发issue,我的github地址为https://github.com/sml2h3'
                 )
                 return False
         else:
             self.logger.info('网络连接有问题,请检查后重试')
             return False
     else:
         self.logger.info('网络连接有问题,请检查后重试')
         return False
예제 #29
0
 def print_qrcode(self):
     print('Address: ')
     qrcode_terminal.draw(self._address)
예제 #30
0
def initialize():
    host = find_ip()
    port = 5000

    draw(f"http://{host}:{port}")