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

in #hive-1809328 months ago

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.

Therefore, we need to talk less nonsense and directly focus on:

  1. Save the steem account information and key with JSON file
  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
  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):

    "nodes": [
    "steems": {
        "myaccount": {

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

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

# 修改 steem 帐号密码
# 1. 优先指定steem账号名,否则命令行输入(当无输入时,返回)
# 2. 优先从文件中获取密钥导入,否则命令行输入
# change all keys of special acc1,acc2 to the local Wallet
# python 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 = [
# 输入要修改keys的steem账号
account_list = []
if not len(account_list):
        # 命令行参数指定需要修改密码的 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':
        print("will change all keys in wallet!")
        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)

    # 如果没有输入steem账号名,则从本地钱包中获取所有steem账号
    if not len(account_list):
        accounts = stm.wallet.getAccounts()
        for account in accounts:
            if account["name"] not in account_list:
    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']
            oldWif = input('Current Owner or Private Key: ')
            if oldWif:
                accountInfo = {
                    "name": acc,  # steem 账号名称
                    "nick": "sample",  # 昵称
                    "email": "[email protected],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)
        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))

            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']['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 dappcoder
Results consistent with expectations: