顺德公农庄 发表于 2018-8-9 10:57:15

python关闭系统服务脚本

  我们在初始化系统时需要关闭一些不必要的服务,保留一些我们常用的,比如sshd、network等,要关的系统服务比较多,这时我们需要借用脚本来完成任务。
  刚自学完python一点基础,只是用来练习~~~~~~
  需求:只开启crond|network|sshd|rsyslog|sysstat服务,其余设置为关闭状态
  shell脚本实现过程:
  #!/bin/bash
  for i in `chkconfig --list|grep "3:启用"|awk '{print $1}'|grep -vE "crond|network|sshd|rsyslog|sysstat"`
  do
  chkconfig $i off
  done
  Python脚本实现过程:
  #!/usr/local/python3/bin/python3
  import subprocess
  import re
  chushi = ["crond","network","sshd","rsyslog","sysstat"]
  data = subprocess.getoutput("chkconfig --list")
  def file_w(datas):
  with open("/tmp/output.txt","w",encoding="utf-8") as f_w:
  for line in datas:
  f_w.write(line)
  f_w.write("\n")
  return chushi
  def file_r(lis):
  guanbi = []
  with open("/tmp/output.txt","r",encoding="utf-8") as f_r:
  for line in f_r:
  #print(line.strip())
  valu = re.search("\w+",line.strip()).group()
  #print(valu)
  if valu not in lis:
  guanbi.append(valu)
  else:
  pass
  return guanbi
  def send_os(gb):
  for item in gb:
  subprocess.getoutput("chkconfig %s off" % item)
  a = file_w(data)
  b = file_r(a)
  send_os(b)
  基本的思路:先把所有的系统服务列表输出到文件,然后进行读取,和需要开启服务的列表做匹配,再调用系统命令进行关闭
页: [1]
查看完整版本: python关闭系统服务脚本