python關閉系統服務指令碼

來源:互聯網
上載者:User

標籤:python練習指令碼   python基礎練習   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)


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

python關閉系統服務指令碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.