-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathmodify_files.py
143 lines (120 loc) · 4.38 KB
/
modify_files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/env python3
# Copyright (C) 2015-2020, Wazuh Inc.
# All rights reserved.
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License (version 2) as published by the FSF - Free Software
# Foundation.
import os
import sys
import random
import platform
import argparse
import logging
if platform.system() == 'Linux':
import pwd
import grp
if sys.version_info.major < 3:
print('ERROR: Python 2 is not supported.')
sys.exit(1)
def random_mode():
"""
Returns a random file permission
File permission in unix use octal format, but os.chmod expects a decimal.
Numbers 0 and 511 are the min and max (decimal) numbers accepted,
being 0 equivalent to 000 and 511 equivalent to 777 in octal.
"""
return random.randint(0, 511)
def modify_file(filepath, owner, group, mode):
"""
Modify a file owner, group and permissions.
:param str filepath: Full path of the file
:param str owner: File owner
:param str group: File group
:param int mode: File permissions in decimal format
:return: Returns a dictionary with the change metadata
"""
uid = pwd.getpwnam(owner).pw_uid
gid = grp.getgrnam(group).gr_gid
os.chown(filepath, uid, gid)
os.chmod(filepath, mode)
return {
'path': filepath,
'uid': uid,
'gid': gid,
'mode': oct(mode).split('o')[1].zfill(3) # convert to octal string
}
def modify_file_content(filepath):
"""
Modify file content by adding a random number of bytes
:param str filepath: The path of the file to modify
"""
content = 'qazxswedcvbnmklpoiuytggdfert' * random.randint(1, 10)
content += str(random.random())
if not os.path.exists(filepath):
raise FileNotFoundError
with open(filepath, 'ab') as f:
f.write(bytes(content, 'utf8'))
def modify_file_text_content(filepath, sentence):
"""
Modify file content by adding sentence at the end of filepath
in a new line.
:param str filepath: The path of the file to modify
:param str sentence: A setnence of 1 or more words.
"""
with open(filepath, 'a') as file:
file.write('\n'+sentence)
def log_modified_files(files_path, logfile):
"""
Creates a file that summarizes all the modified files
:param dict files_path: Contains the list of modified files
:param str logfile: File to write the list of paths
"""
if os.path.exists(logfile):
os.remove(logfile)
with open(logfile, 'w') as f:
for path in files_path:
f.write(path + '\n')
def main():
log_filename = 'modify_files.log'
logging.basicConfig(
filename=log_filename,
level=logging.DEBUG,
)
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input-list", type=str,
required=True, dest='input_file',
help="File containing the list of files to modify")
parser.add_argument("-o", "--output-list", type=str,
required=True, dest='output_file',
help="File containing the list of modified files")
parser.add_argument("-t", '--text-mode', default=False, action="store_true",
dest="text_mode", help="Modify text files instead of binary"
" (default is False)")
args = parser.parse_args()
input_file = args.input_file
output_file = args.output_file
text_mode = args.text_mode
changed_files = []
sentence = "Hello World"
with open(input_file) as flist:
for path in flist:
try:
if text_mode: # if text_mode, then add 'setence' at the end of 'path'
modify_file_text_content(path[:-1], sentence)
else:
modify_file_content(path[:-1])
changed_files.append(path[:-1])
except PermissionError:
logging.error("Not enough permissions to modify: {}".format(path[:-1]))
continue
except FileNotFoundError:
logging.error("File not found: {}".format(path[:-1]))
continue
except Exception:
logging.error("Unexpected error: ", exc_info=True)
continue
log_modified_files(changed_files, output_file)
if __name__ == "__main__":
main()