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

时间:2021-09-07 20:26:34

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

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

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

1 个解决方案

#1


0  

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

#1


0  

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