python脚本在工作中的应用-复杂替换

背景:与某企业的合作项目,codereview中出现的不安全函数strcpy和sprintf整改问题。

整改方案如下:

1
2
3
4
5
6
7
8
9
//Noncompliant Code Example
sprintf(str, "%s", message); // Noncompliant
strcpy(str, message); // Noncompliant
//Compliant Solution
snprintf(str, sizeof(str), "%s", message);
strlcpy(str, message, sizeof(str));

strncpy(str, message, sizeof(str) -1); // Leave room for null
str[sizeof(str) - 1] = '\0'; // Make sure the string is null-terminated

在4个c文件中,一共有1千多处需要整改,工作量巨大,故写了个python脚本帮助替换,立刻就搞定了

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
import os
import shutil
import sys
def repalce_string(filepath):
print("----------------------开始替换文字----------------------")
tmppath = filepath+'.tmp'
tmpfile = open(tmppath,'w')
with open(filepath,'r') as f:
lines = f.readlines()
for line in lines:
if 'strcpy' in line:
index = line.find('(')
index2 = line.find(',')
index3 = line.find(');')
str1 = line[index+1:index2]
str2 = line[index2+1:index3]
repl = '''
strncpy({},{},sizeof({})-1);
{}[sizeof({})-1]='\0';
'''.format(str1,str2,str1,str1,str1)
tmpfile.write(repl)
else:
tmpfile.write(line)
tmpfile.close()
tmpfile = None
try:
shutil.copyfile(tmppath, filepath)
except Exception as e:
print("!!!!!!!!!!! 替换文字失败 !!!!!!!!!! ", e)
sys.exit()
finally:
os.remove(tmppath)

if __name__ == '__main__':
filepath = sys.argv[1]
repalce_string(filepath)