简体   繁体   English

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

[英]How to write specific variable into conf/json file without overwriting existing dict variables using python

I am trying to encrypt password from userinput through args and write it to an existing conf file without overwriting existing dict variables in conf file. 我正在尝试通过args从userinput加密密码,并将其写入现有的conf文件,而不会覆盖conf文件中的现有dict变量。

I have tried following script, Please let me know how to achieve it or any suggestions are appreciated. 我已经尝试过以下脚本,请让我知道如何实现它或任何建议,我们将感激不尽。

inputJson.conf inputJson.conf

{
    "MetadataInputs": {
        "redHat": {
            "hostName": "10.110.20.30",
            "userName": "admin",
            "password": "admin123",
            "organisationName": "networks",
            "repository":"Red Hat"
        }
    }
}

WriteJson.py WriteJson.py

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()

I got the answer for this , my approach was wrong . 我得到了答案,我的方法是错误的。 I have corrected it with the below answer.If anyone has better approach for whatever i am trying , please post your answer. 我已使用以下答案进行了更正。如果有人对我正在尝试的方法有更好的处理方法,请发表您的答案。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不覆盖数据的情况下写入现有的 excel 文件(使用熊猫)? - How to write to an existing excel file without overwriting data (using pandas)? 写文件而不用python覆盖吗? - Write a file without overwriting with python? 如何在不覆盖现有文件的情况下在 python 中创建文件 - How do I create a file in python without overwriting an existing file 将数据添加到现有 JSON 文件而不覆盖它 - Adding data to an existing JSON file without overwriting it 如何在 excel 文件的特定单元格中写入数据而不覆盖数据(使用熊猫)? - How do you write data in a specific cell in an excel file without overwriting data (using pandas)? 如何在python中使用for循环在不覆盖现有数据帧的情况下附加数据帧 - how to append a dataframe without overwriting existing dataframe using for loop in python 如何在Python中使用FTPLIB防止覆盖现有文件? - How to Prevent Overwriting a Existing File Using FTPLIB in Python? 在现有文件中写入 xls cel 而不会覆盖 rest 文件 - write xls cel in existing file without overwriting rest file 使用Python覆盖XLSX文件中的现有单元格 - Overwriting existing cells in an XLSX file using Python 写入 excel csv 文件 python 中的特定行而不覆盖其他列。 python - write to specific rows in excel csv file python without overwriting other columns. python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM