1#!/usr/bin/env python
2
3import argparse
4from argparse import RawDescriptionHelpFormatter
5
6description = """
7Replace a string in one file with a secret from a second file.
8
9Since the secret is read from a file, it won't be leaked through
10'/proc/<pid>/cmdline', unlike when 'sed' or 'replace' is used.
11"""
12
13parser = argparse.ArgumentParser(
14 description=description,
15 formatter_class=RawDescriptionHelpFormatter
16)
17parser.add_argument("string_to_replace", help="the string to replace")
18parser.add_argument("secret_file", help="the file containing the secret")
19parser.add_argument("file", help="the file to perform the replacement on")
20args = parser.parse_args()
21
22with open(args.secret_file) as sf, open(args.file, 'r+') as f:
23 old = f.read()
24 secret = sf.read().strip("\n")
25 new_content = old.replace(args.string_to_replace, secret)
26 f.seek(0)
27 f.write(new_content)
28 f.truncate()