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)


基本的思路:先把所有的系統服務列表輸出到文件,然後進行讀取,和需要開啓服務的列表做匹配,再調用系統命令進行關閉

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章