python--修改关键字

2021-04-21  本文已影响0人  w_dll

批处理修改tomcat server.xml的某个值
用shell行不通,原因是含有特殊字符
用python很方便的解决了这个问题

#!/usr/bin/env python
import io, time
import shutil
import os


os.chdir('/u01')
file_list = os.listdir('.')
tomcat_dir = None
for i in file_list:
  if 'tomcat8-fd' in i:
    tomcat_dir = i

if tomcat_dir != None and os.path.isdir(tomcat_dir):
  os.chdir(tomcat_dir)


if os.path.isdir('conf'):
  os.chdir('conf')
  res = os.getcwd()
  print(res)

if os.path.isfile('server.xml'):
  print('check ok')
else:
  print('not found ==> server.xml!')


old_file_name = 'server.xml'
new_file_name = 'new-server.xml'

old_file  =  io.open(old_file_name, 'r', encoding='utf-8')
new_file = io.open(new_file_name, 'w', encoding='utf-8')
data = old_file.readline()
tag = None
flag = 0
while data:
  if flag == 1 and tag != None:
    new_file.write(tag)
    flag = 0
  if 'Context path=' not in data:
    new_file.write(data)
  else:
    tag  = data
  if 'unpackWARs="true" autoDeploy="true">' in data:
    flag = 1
  data = old_file.readline()

old_file.close()
new_file.close()

time_tag = time.strftime("%Y-%m-%d_%H-%M-%s", time.localtime())

back_file = old_file_name + '_' + str(time_tag)
shutil.copy(old_file_name, back_file)
shutil.move(new_file_name, old_file_name)

# shell
#delete
#data=`cat server.xml | grep 'Context path='`
#delete_row=`cat -n server.xml | grep 'Context path=' | awk '{print $1}`
#sed -i ''$delete_row' d' $file_name
#add
#after_row=`cat -n server.xml | grep 'unpackWARs="true" autoDeploy="true">' | awk '{print $1}'`
上一篇下一篇

猜你喜欢

热点阅读