String Replacement Method in Python File Operation (Save to New File and Current File)

  • 2021-07-03 00:40:34
  • OfStack

Title:

1. First back up the file:/etc/selinux/config /etc/selinux/config.bak

2. Replace enforcing in:/etc/selinux/config with disabled


# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#   enforcing - SELinux security policy is enforced.
#   permissive - SELinux prints warnings instead of enforcing.
#   disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of three two values:
#   targeted - Targeted processes are protected,
#   minimum - Modification of targeted policy. Only selected processes are protected. 
#   mls - Multi Level Security protection.
SELINUXTYPE=enforcing

Method 1: Use replace


import os
import shutil
def selinux_config():
  """
   Shut down SELINUX
   Modify the contents of the file 
  :return:
  """
  file_selinux = '/etc/selinux/config'
  backup_file_selinux = file_selinux + '.bak'
  temp_file_selinux = file_selinux + '.temp'
  if not os.path.exists(backup_file_selinux):
    shutil.copy2(file_selinux, backup_file_selinux)
    with open(file_selinux, mode='r') as fr, open(temp_file_selinux, mode='w') as fw:
      origin_line = 'SELINUX=enforcing'
      update_line = 'SELINUX=disabled'
      for line in fr:
        fw.write(line.replace(origin_line, update_line))
    os.remove(file_selinux)
    os.rename(temp_file_selinux, file_selinux)
if __name__ == '__main__':
  selinux_config()

Method 2: Use re. sub


#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import shutil
def selinux_config():
  """
   Shut down SELINUX
   Modify the contents of the file 
  :return:
  """
  file_selinux = '/etc/selinux/config'
  backup_file_selinux = file_selinux + '.bak'
  temp_file_selinux = file_selinux + '.temp'
  if not os.path.exists(backup_file_selinux):
    shutil.copy2(file_selinux, backup_file_selinux)
    with open(file_selinux, mode='r') as fr, open(temp_file_selinux, mode='w') as fw:
      origin_line = 'SELINUX=enforcing'
      update_line = 'SELINUX=disabled'
      for line in fr:
        re_sub_list = re.sub(origin_line, update_line, line) #  Used here re.sub After replacement, put in  re_sub_list Medium 
        fw.writelines(re_sub_list) #  Putting each of the 1 Row is written. writelines Is to set every 1 Row is written. 
    os.remove(file_selinux)
    os.rename(temp_file_selinux, file_selinux)
if __name__ == '__main__':
  selinux_config()

Summarize


Related articles: