python 修改文件
#!/usr/bin/env python
# coding:utf8
import tempfile
import os
import sys
import re
file = tempfile.TemporaryFile()
oldFile = 'sshd_config'
if os.path.exists(oldFile):
openOldFile = open(oldFile, 'r')
else:
print "file %s not found" % oldFile
sys.exit()
for line in openOldFile:
line = re.sub(r'^#(PubkeyAuthentication)', '\g<1>', line, flags=re.M)
line = re.sub(r'^#(AuthorizedKeysFile)', '\g<1>', line, flags=re.M)
line = re.sub(r'(^PassWordAuthentication) yes', '\g<1> no', line, flags=re.M)
file.write(line)
openOldFile.close()
file.seek(0)
tmpFile = file.read()
if os.path.exists(oldFile):
os.remove(oldFile)
writeFile = open(oldFile, 'w')
writeFile.write(tmpFile)
file.close()
相关文章