Python系统管理员

       采用Python来管理UNIX®系统,同时结合良好的程序设计概念。 Python是一种容易学习,开源脚本语言,可以让系统管理员更快速地做他们的工作。它也可以让工作更有乐趣。

 

 

简介 

         作为系统管理员,您在众多的挑战和问题运行。管理用户,磁盘空间,进程,设备和备份可能会导致许多系统管理员失去他们的头发,性格开朗,还是理智。 Shell脚本可以帮助,但他们往往有令人沮丧的限制。这是一个全功能的脚本语言,如Python,可以把乏味的任务变成一种简单,我敢说,乐趣之一。 本文中的示例演示了不同的Python功能,您可以投入实际使用。如果你通过他们的工作,你会用自己的方式来理解Python中的力量。

 

 

 关于模块 

       模块是一个重要的Python概念。基本上,一个模块就是你才能使用它导入资源。这个过程相当于服用了一张纸出来一个文件柜,并把它放在你的办公桌上,随时使用。你利用import命令,它出现在每个示例程序的顶部模块。模块可用于数据库连接,网络编程,操作系统服务,和数以百计的其他有用的地方。

 

 

 

让Python的工作 

      Python是一个全功能的,强大的编程语言,正因为如此,它具有功能吨。学习它可能是百年难遇的任务。但是,请记住,许多Python的功能,如图形用户界面工具包,是有限的价值系统管理员。这就是为什么这篇文章使用具体的例子:他们证明你需要有效地编写Python脚本来管理系统的技能。

 

 

 

      这些示例注意事项 :
      每个例子包括一试:和除外:与代码周围的段。这是一个基本的错误处理的实现。 Python有处理所有类型的异常广泛的支持,但是,对于这些示例程序的目的,我已经把它简单。 
     这些实例都运行在Python 2.5中对Linux®的机器上运行,但它们应该在任何UNIX/ Linux机器。 
     毫无疑问,你会想办法,这些脚本可以得到改善。这是好事! Python脚本的性质是它们能很容易地修改和,而无需重新编译代码定制。

 

 

例1:搜索文件,并在一个友好的格式下显示权限

 

      第一实施例的程序(参见清单1)搜索匹配的模式(基于用户输入),该文件并把结果显示在屏幕上,伴随着分配给该特定文件的访问权限。起初,你可能会认为这个方案并没有做更多的事情比执行find命令;然而,结果显示在一个定制的方式,你的选项来显示这种增强的发现是无限的。该示例显示了如何利用系统命令,并使其更好(或者至少是更加个性化)。 
       该脚本主要执行三项任务: 
     1、获得来自用户的搜索模式。 
     2、执行搜索。 
     3、结果提交给用户。 
      在写剧本,不断地问自己这个问题:“哪个任务是这段代码支持?”问自己这个问题,可以提高您的工作和效率的重点。

 

 

 

Listing 1. Search for files and list results with file permissions

 Python Code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

 

import stat, sys, os, string, commands

#Getting search pattern from user and assigning it to a list

try:
    #run a 'find' command and assign results to a variable
    pattern = raw_input("Enter the file pattern to search for:\n")
    commandString = "find " + pattern
    commandOutput = commands.getoutput(commandString)
    findResults = string.split(commandOutput, "\n")

    #output find results, along with permissions
    print "Files:"
    print commandOutput
    print "================================"
    for file in findResults:
        mode=stat.S_IMODE(os.lstat(file)[stat.ST_MODE])
        print "\nPermissions for file "file":"
        for level in "USR""GRP""OTH":
            for perm in "R""W""X":
                if mode & getattr(stat,"S_I"+perm+level):
                    print level, " has ", perm, " permission"
                else:
                    print level, " does NOT have ", perm, " permission"
except:
    print "There was a problem - check the message above"

 该方案遵循以下步骤:
      1、问一个搜索模式(行7-9)的用户。
      2、打印中(行12-14)文件的列表。
      3、使用统计模块,获得权限找到的每个文件,并将其显示在屏幕上(行15-23)。
当程序运行时,输出如清单2所示。

 

 

Listing 2. Output of the first example

$ python example1.py
Enter the file pattern to search for:
j*.py

FILES FOUND FOR PATTERN  j*.py :
jim.py
jim2.py
================================

Permissions for file  jim.py :
USR     R
USR     W
USR     X
GRP     -
GRP     -
GRP     -
OTH     -
OTH     -
OTH     -

Permissions for file  jim2.py :
USR     R
USR     W
USR     X
GRP     R
GRP     -
GRP     X
OTH     R
OTH     -
OTH     X

 

 

 

例2:执行操作一个tar归档是基于菜单的选择上的

   在前面的例子提示搜索模式使用的用户。另一种方式来获得用户信息是通过一个命令行参数。清单3中的程序展示了如何做到这一点的Python:该代码将一个tar文件名作为命令行参数,然后提示用户有多种选择。 这个例子也说明一种新的方式来攻击问题。

    第一个例子中使用的命令模块运行find命令,并捕获输出。这种方法可以笨拙,是不是很“Python化”。本示例使用tar文件模块打开一个tar文件,里面有让你使用,你操作文件Python的属性和方法的优势。与提供Python的许多模块,你可以做的事情,无法通过命令行来完成。 
      这是在Python中实现菜单系统的一个很好的例子。该程序执行根据您选择不同的操作: 
           如果按1,程序会提示您在存档中提取当前目录下的文件名,然后提取该文件。 
           如果按2,程序会提示您输入文件名,然后显示该文件的信息。 
           如果按3,程序会列出在档案中的所有文件。

 

Listing 3. Perform actions on a tar archive based on your menu selection

 Python Code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

 

import tarfile, sys

try:
    #open tarfile
    tar = tarfile.open(sys.argv[1], "r:tar")

    #present menu and get selection
    selection = raw_input("Enter\n\
    1 to extract a file\n\
    2 to display information on a file in the archive\n\
    3 to list all the files in the archive\n\n")

    #perform actions based on selection above
    if selection == "1":
        filename = raw_input("enter the filename to extract:  ")
        tar.extract(filename)
    elif selection == "2":
        filename = raw_input("enter the filename to inspect:  ")
        for tarinfo in tar:
            if tarinfo.name == filename:
                print "\n\
                Filename:\t\t", tarinfo.name, "\n\
                Size:\t\t", tarinfo.size, "bytes\n\
    elif selection == "3":
        print tar.list(verbose=True)
except:
    print "There was a problem running the program"

      该方案遵循以下步骤:
          打开tar文件(第5行)。
          目前该菜单并得到用户选择(8-11行)。
          如果按1(行14-16),提取归档文件。
          如果按2(行17-23),有关所选文件的显示信息。
          如果按3(行24-25),约在档案中的所有文件显示信息。
输出如清单4所示。

 

 

Listing 4. User menu for second example

$ python example2.py jimstar.tar
Enter
1 to extract a file
2 to display information on a file in the archive
3 to list all the files in the archive

 

 

 

例3:检查正在运行的进程,并显示信息,在友好的格式

     一个系统管理员最重要的职责是检查正在运行的进程。清单5中的脚本给你一些想法。该方案利用了UNIX的上一个命令,它可以让你自动地缩小数据Python有解析生成的输出运行grep命令的能力优势。 
     这个程序也使用string模块。了解该模块 - 你经常使用它。

 

Listing 5. Display information on a running process in a friendly format

 Python Code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

 

import commands, os, string

program = raw_input("Enter the name of the program to check: ")

try:
    #perform a ps command and assign results to a list
    output = commands.getoutput("ps -f|grep " + program)
    proginfo = string.split(output)

    #display results
    print "\n\
    Full path:\t\t", proginfo[5], "\n\
    Owner:\t\t\t", proginfo[0], "\n\
    Process ID:\t\t", proginfo[1], "\n\
    Parent process ID:\t", proginfo[2], "\n\
    Time started:\t\t", proginfo[4]
except:
    print "There was a problem with the program."

       该方案遵循以下步骤:
       获取一个进程的名字来检查,并将其分配给一个变量(第3行)。
      运行ps命令的结果赋值给一个列表(第7-8行)。
      显示与英语术语(行11-16)过程中的详细信息。
输出如清单6所示。

Listing 6. Output of the third example

$ python example3.py
Enter the name of the program to check: xterm

    Full path:          /usr/bin/xterm
    Owner:              knowltoj
    Process ID:         3220
    Parent process ID:  4308
    Time started:       16:51:46

 

 

例4:检查用户ID和密码政策合规

      管理安全是任何系统管理员的工作的重要组成部分。蟒蛇使得这项工作更容易,因为最后一个例子说明。 
清单7中的程序使用密码模块来访问口令数据库。它会检查用户ID和密码的安全策略符合性(在这种情况下,用户ID,至少6个字符长的密码至少包含8个字符)。 
       有两点需要说明: 
       这个程序只有当你有充分的权利,/ etc / passwd文件。 
       如果您使用shadow密码,该脚本将不能正常工作(但是,Python 2.5中确实有做的作业SPWD模块)。

 

Listing 7. Check userids and passwords for compliance with security policy

 Python Code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

 

import pwd

#initialize counters
erroruser = []
errorpass = []

#get password database
passwd_db = pwd.getpwall()

try:
    #check each user and password for validity
    for entry in passwd_db:
        username = entry[0]
        password = entry [1]
        if len(username) < 6:
            erroruser.append(username)
        if len(password) < 8:
            errorpass.append(username)

    #print results to screen
    print "The following users have an invalid userid (less than six characters):"
    for item in erroruser:
        print item
    print "\nThe following users have invalid password(less than eight characters):"
    for item in errorpass:
        print item
except:
    print "There was a problem running the script."

      该方案遵循以下步骤: 
      初始化计数器名单(第4-5行)。 
      打开密码数据库和数据分配到一个列表(第8行)。 
      检查用户名和密码的有效性(行12-18)。 
      输出无效的用户名和密码(行21-26)。 
输出如清单8所示。

Listing 8. Output of the fourth example

$ python example4.py
The following users have an invalid userid (less than six characters):
Guest

The following users have invalid password(less than eight characters):
Guest
johnsmith
joewilson
suejones

Other uses for scripts

     您可以通过多种方式来管理系统中使用Python。一个你能做的最好的事情是分析自己的工作,确定任务,反复进行,并探索的Python模块是否可以帮助你完成这些任务,几乎可以肯定他们是。 
      有一些特定的领域,Python可以有很大的帮助,如下所示: 
          管理服务器:检查补丁级别在一组服务器上的特定应用程序,并自动更新它们。 
          日志记录:自动发送的电子邮件,如果一个特定类型的错误出现在系统日志。 
          网络:让Telnet连接到服务器并监视连接的状态。 
          测试Web应用程序:使用免费的工具来模拟Web浏览器,并验证Web应用程序的功能和性能。 
这些只是几个例子,我敢肯定,你可以添加你自己有用的意见。

 

 

总结

凭借其易于学习语言;它能够处理文件,进程,字符串和数字;其几乎是无止境的辅助模块阵列,Python是一种脚本语言,看起来是为系统管理员。这对于任何系统管理员工具箱中的有价值的工具。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值