MMoSP004- steem-python Modifying and managing keys through JSON files(通过JSON文件修改和管理密码)

avatar

Preface notes(前言备注):

This is the first bilingual post after the combination of Chinese and English. Most people may not be used to it, especially the simple and efficient developers. However, there is no way. In order to avoid being downvoted by some people in the steem community, we can only use bilingual in the same post.
=》这是中英文合并后的双语第一帖,可能大多数人会很不习惯,特别是讲究简单高效的开发者.但,没办法,为了避免因此而被steem社区有的人踩,只能双语同文.

Therefore, we need to talk less nonsense and directly focus on:
=》所以,更要少废话,直接说重点:

  1. Save the steem account information and key with JSON file
    =》用json文件保存steem账号信息和密钥
  2. steem-python obtains master key from JSON file and modifies the whole set of steem key
    =》steem-python 从json文件中获取master key,修改整套steem密钥.
  3. Save the modified set of keys to the JSON file
    =》将修改后的整套密钥,保存到json文件中.
  4. In the future, once the key is at risk, you can use this tool to quickly change and save the keys of steem account.
    =》日后,一但密钥出现风险,可以直接用此工具快速更改和保存密码.

Format of JSON file storage(/bots.json):
=>json文件存储的格式(/bots.json):

{
    "nodes": [
        "https://anyx.io",
        "https://steemd.minnowsupportproject.org",
        "https://api.steemit.com"
    ],
    "steems": {
        "myaccount": {
        }
    }
}

Demo for changing the keys and saving it into a JSON file
=>这里就示范 steem-python 修改密码并存入json文件(change_keys_steem.py):


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# 修改 steem 帐号密码
# 1. 优先指定steem账号名,否则命令行输入(当无输入时,返回)
# 2. 优先从文件中获取密钥导入,否则命令行输入
# change all keys of special acc1,acc2 to the local Wallet
# python change_keys_steem.py acc1,acc2

import sys
import json
import steem
import steembase
from steem.steemd import Steemd
from steem.account import Account
from steem.amount import Amount
from steem.instance import set_shared_steemd_instance
from steembase.account import BrainKey, Address, PublicKey, \
    PrivateKey, PasswordKey
from steembase import operations

# 默认的 steem API 节点
steemd_api_nodes = [
    'https://anyx.io',
    'https://steemd.minnowsupportproject.org',
    'https://rpc.esteem.app',
    'https://api.steemit.com'
]
# 输入要修改keys的steem账号
account_list = []
if not len(account_list):
    try:
        # 命令行参数指定需要修改密码的 steem 账号: acc1,acc2
        accounts = sys.argv[1]
    except Exception as e:
        accounts = input('steem accounts(acc1,acc2),Enter for all: ')
    print('accounts:', accounts)

    if not accounts:
        conAll = input('confirm for change all keys in wallet(Y/N):')
        if conAll != 'Y':
            sys.exit()
        print("will change all keys in wallet!")
    else:
        print("will change all keys of", accounts)
        account_list = accounts.split(",")
    print('account_list:', account_list)

accounts_file = '/bots.json'

with open(accounts_file, 'r', encoding='utf-8') as f:
    # 直接用load()传入文件对象,将文件中字符串内容转为json字典
    accounts_dict = json.load(f)
    # print('old.accounts_dict:', accounts_dict)
    # 优先使用配置文件中指定的steem API 节点
    if 'nodes' in accounts_dict:
        steemd_api_nodes = accounts_dict['nodes']

    stm = Steemd(nodes=steemd_api_nodes)
    set_shared_steemd_instance(stm)

    # 如果没有输入steem账号名,则从本地钱包中获取所有steem账号
    if not len(account_list):
        accounts = stm.wallet.getAccounts()
        for account in accounts:
            if account["name"] not in account_list:
                account_list.append(account["name"])
    print("account_list:", account_list)

    for acc in account_list:
        # for acc in accounts_dict['steems']:
        print('acc:', acc)
        # oldWif:steem账户名旧的 owner key 或 private Key
        if acc in accounts_dict['steems']:
            accountInfo = accounts_dict['steems'][acc]
            oldWif = accountInfo['keys']['private']
        else:
            oldWif = input('Current Owner or Private Key: ')
            if oldWif:
                accountInfo = {
                    "name": acc,  # steem 账号名称
                    "nick": "sample",  # 昵称
                    "email": "sample@,pwd",  # steem 注册 email
                    "mobile": "sample9,from",  # steem 注册 手机号
                    "keys": {
                        "private": oldWif,  # steem 账号当前的私钥
                        "history": [oldWif],  # steem 账号的私钥的修改记录
                        "owner": oldWif,  # steem 账号的 owner 私钥
                    }
                }
        if not oldWif:
            print("invalid key for", acc)
            continue
        print("change keys of", acc)
        print("oldWif:", oldWif)
        # 生成一套新密码
        bk = BrainKey()
        brainkey = str(bk.get_brainkey())
        print('brain key:', brainkey)
        prikey = str(bk.get_private())
        print('private key:', prikey)
        pubkey = format(bk.get_public(), "STM")
        print('public key:', str(pubkey))

        new_keys = {}  # 获取整套密钥
        new_privkey = {}  # 提取整套密钥中的私钥
        new_pubkey = {}  # 提取整套密钥中的公钥
        for role in ["posting", "active", "owner",  "memo"]:
            new_keys[role] = PasswordKey(acc, prikey, role)
            new_privkey[role] = str(new_keys[role].get_private_key())
            new_pubkey[role] = str(new_keys[role].get_public_key())
        print('new_privkey:', json.dumps(new_privkey, indent=4))
        print('new_pubkey:', json.dumps(new_pubkey, indent=4))

        try:
            old_owner_key = str(PasswordKey(
                acc, oldWif, "owner").get_private_key())

            client = steem.Steem(nodes=steemd_api_nodes, keys=[old_owner_key])
            new_data = {
                "account": acc,
                "json_metadata": {},
                "owner": {
                    "key_auths": [
                        [new_pubkey["owner"], 1]
                    ],
                    "account_auths": [],
                    "weight_threshold": 1
                },
                "active": {
                    "key_auths": [
                        [new_pubkey["active"], 1]
                    ],
                    "account_auths": [],
                    "weight_threshold": 1
                },
                "posting": {
                    "key_auths": [
                        [new_pubkey["posting"], 1]
                    ],
                    "account_auths": [],
                    "weight_threshold": 1
                },
                "memo_key": new_pubkey["memo"]
            }
            print("New data:", new_data)

            op = operations.AccountUpdate(**new_data)
            result = client.commit.finalizeOp(op, acc, "owner")
            print("Result:", result)
            accountInfo['keys']['brain'] = brainkey
            accountInfo['keys']['private'] = prikey
            accountInfo['keys']['public'] = pubkey
            accountInfo['keys']['history'].append(prikey)
            accountInfo['keys']['memo_key'] = new_pubkey['memo']
            for role in ["posting", "active", "owner",  "memo"]:
                accountInfo['keys'][role] = new_privkey[role]
            accounts_dict['steems'][acc] = accountInfo
        except Exception as err:
            print(acc, " err:", err)

with open(accounts_file, 'w', encoding='utf-8') as f:
    # 用dump()传入字典和文件对象,将json字典转为字符串,存入文件
    json.dump(accounts_dict, f, indent=4, ensure_ascii=False)

Run it(执行程序):python change_keys_steem.py dappcoder
Results consistent with expectations:
=>执行结果,和预期一致:



0
0
0.000
1 comments