root / snf-image-helper / inject-files.py @ b873aac3
History | View | Annotate | Download (2 kB)
1 |
#!/usr/bin/env python
|
---|---|
2 |
|
3 |
"""Inject files into a directory
|
4 |
|
5 |
This program injects files into a target directory.
|
6 |
The files are passed to the program through a JSON string either read from a
|
7 |
file or from standard input.
|
8 |
|
9 |
"""
|
10 |
|
11 |
import sys |
12 |
import os |
13 |
import json |
14 |
import datetime |
15 |
import base64 |
16 |
from optparse import OptionParser |
17 |
|
18 |
|
19 |
def timestamp(): |
20 |
now = datetime.datetime.now() |
21 |
current_time = now.strftime("%Y%m%d.%H%M%S")
|
22 |
return current_time
|
23 |
|
24 |
def parse_arguments(input_args): |
25 |
usage = "Usage: %prog [options] <target>"
|
26 |
parser = OptionParser(usage=usage) |
27 |
parser.add_option("-i", "--input", |
28 |
action="store",type='string', dest="input_file", |
29 |
help="get input from FILE instead of stdin",
|
30 |
metavar="FILE")
|
31 |
|
32 |
opts, args = parser.parse_args(input_args) |
33 |
|
34 |
if len(args) != 1: |
35 |
parser.error('target is missing')
|
36 |
|
37 |
target = args[0]
|
38 |
if not os.path.isdir(target): |
39 |
parser.error('target is not a directory')
|
40 |
|
41 |
input_file = opts.input_file |
42 |
if input_file is None: |
43 |
input_file = sys.stdin |
44 |
else:
|
45 |
if not os.path.isfile(input_file): |
46 |
parser.error('input file does not exist')
|
47 |
input_file = open(input_file,'r') |
48 |
|
49 |
return (input_file, target)
|
50 |
|
51 |
|
52 |
def main(): |
53 |
(input_file, target) = parse_arguments(sys.argv[1:])
|
54 |
|
55 |
files = json.load(input_file) |
56 |
for f in files: |
57 |
real_path = target + '/' + f['path'] |
58 |
if os.path.lexists(real_path):
|
59 |
backup_file = real_path + '.bak.' + timestamp()
|
60 |
os.rename(real_path, backup_file) |
61 |
|
62 |
parentdir = os.path.dirname(real_path) |
63 |
if not os.path.exists(parentdir): |
64 |
os.makedirs(parentdir) |
65 |
|
66 |
newfile = open(real_path, 'w') |
67 |
newfile.write(base64.b64decode(f['contents']))
|
68 |
newfile.close() |
69 |
os.chmod(real_path, 0440)
|
70 |
sys.stderr.write('Successful personalization of Image\n')
|
71 |
|
72 |
input_file.close() |
73 |
return 0 |
74 |
|
75 |
|
76 |
if __name__ == "__main__": |
77 |
sys.exit(main()) |
78 |
|
79 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|