如何将特定变量写入conf / json文件而不使用python覆盖现有的dict变量

时间:2017-10-18 12:22:40

标签: python json python-2.7 dictionary

我正在尝试通过args从userinput加密密码并将其写入现有的conf文件,而不会覆盖conf文件中的现有dict变量。

我已尝试过以下脚本,请让我知道如何实现它或任何建议表示赞赏。

inputJson.conf

import json
from Crypto.Cipher import AES
import base64
import sys
import io

with open('conf.json') as inputParameters:
      readInputData = json.load(inputParameters)


class Test():
     def __init__(self,readInputData):
         self.__dict__=readInputData
         self.hostName = readInputData['MetadataInputs']['redHat']['hostName']
         self.userName = readInputData['MetadataInputs']['redHat']['userName']
         self.orgName = readInputData['MetadataInputs']['redHat']['organisationName']
         self.repostiroyName = readInputData['MetadataInputs']['redHat']['repository']

     def encryptPassword(self):
         try:
             args = sys.argv[1:]
             self.inputPassword = sys.argv[1]
             msg_text = self.inputPassword.rjust(32)
             secret_key = '1234567890123456'  
             cipher = AES.new(secret_key, AES.MODE_ECB)
             encoded = base64.b64encode(cipher.encrypt(msg_text))
             # self.password = {
             #        "MetadataInputs": {
             #            "redHat": {
             #                "password": encoded
             #            }
             #        }}
             with io.open('conf.json', 'w', encoding='utf8') as outfile:
                 self.password=outfile['MetadataInputs']['redHat']['password']
                 str_ = json.dump(self.password, outfile, indent=4, ensure_ascii=False)
                 outfile.write((str_))

         except Exception:
             print "Exception Occurred --- Please provide password "



obj = Test(readInputData)
obj.encryptPassword()

WriteJson.py

#include <exception>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    fs::path source = "path/to/source/folder";
    fs::path target = "path/to/target/folder";

    try {
        fs::copy(source, target, fs::copy_options::recursive);
    }
    catch (std::exception& e) { // Not using fs::filesystem_error since std::bad_alloc can throw too.
        // Handle exception or use error code overload of fs::copy.
    }
}

1 个答案:

答案 0 :(得分:0)

我得到了答案,我的做法是错误的。我用下面的答案纠正了它。如果有人对我正在尝试的任何事情有更好的处理方法,请发表你的答案。

import json
from Crypto.Cipher import AES
import base64
import sys

with open('outputJson.json') as inputParameters:
      readInputData = json.load(inputParameters)

class Test():
     def __init__(self,readInputData):
         self.__dict__=readInputData
         self.rhsnHostName = readInputData['MetadataInputs']['redHat']['hostName']
         self.rhsnUserName = readInputData['MetadataInputs']['redHat']['userName']
         self.rhsnOrgName = readInputData['MetadataInputs']['redHat']['organisationName']
         self.rhsnRepostiroyName = readInputData['MetadataInputs']['redHat']['repositoryName']

     def encryptPassword(self):
         try:
             args = sys.argv[1:]
             self.inputPassword = sys.argv[1]
             msg_text = self.inputPassword.rjust(32)
             secret_key = '1234567890123456'  # create new & store somewhere safe
             print "Secret Key length is "+ str(len(secret_key))
             cipher = AES.new(secret_key, AES.MODE_ECB)  # never use ECB in strong systems obviously
             encoded = base64.b64encode(cipher.encrypt(msg_text))
             print "Encoded password for %s is %s "%(encoded,self.inputPassword)
             print "\n"
             redHatPatchMetaDataConf = {}
             redHatPatchMetaDataConf={
                        "MetadataInputs": {
                            "redHat": {
                                "hostName": self.rhsnHostName,
                                "userName": self.rhsnUserName,
                                "password": encoded,
                                "organisationName": self.rhsnOrgName,
                                "repositoryName":self.rhsnRepostiroyName
                            }
                        }
                    }
             outfile = open('outputJson.json', 'w');
             json.dump(redHatPatchMetaDataConf, outfile, indent=4, skipkeys=True, sort_keys=True)
             outfile.close()
             with open('outputJson.json') as decodeJson:
                 try:
                     readInputData = json.load(decodeJson)
                     decPassword = readInputData['MetadataInputs']['redHat']['password']
                     print "decPassword is "+decPassword
                     decoded = cipher.decrypt(base64.b64decode(decPassword))
                     print "Decoded password for %s is %s"%(decPassword,decoded.strip())
                 except Exception:
                     print "Unable to Decode Password"
         except Exception as e:
             print e

obj = Test(readInputData)
obj.encryptPassword()