2

Python与系统日常管理

 2 years ago
source link: http://wwj718.github.io/post/%E6%8A%80%E6%9C%AF/python-for-system-administrators/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

大多时间都在linux下工作,虽说不算系统管理员,也免不了要处理许多系统相关的东西。对linux还算熟悉,偶尔也在公司客串系统管理员的角色。于是就免不了要写许多自动化脚本的东西,来方便系统日常管理了。

bash脚本挺让人恶心的,属于dirty and quick一类。而Python语法清新可人,Python与系统的交互也极其便利,写自动化脚本再合适不过。

在此就分享些自己在写自动化脚本时中意的Python工具:


build-in

  • glob:文件名的匹配,比如
    • glob.glob(‘somedir/*.py’)
  • pathlib python3支持,路径处理的瑞士军刀
  • subprocess
    • 启动一个子进程建议的方式是使用下面的便捷函数:subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
      • subprocess.call([“ls”, “-l”])
    • 对于更高级的使用场景当它们不能满足你的需求时,可以使用底层的Popen接口。
    • subprocess.call([“sed”, “-i”, “-e”, ’s/hello/helloworld/g’, “www.txt”])
    • 单行:subprocess.call([“sed -i -e ’s/hello/helloworld/g’ www.txt”], shell=True)

sh

sh is a full-fledged subprocess replacement for Python 2.6 - 3.4 that allows you to call any program as if it were a function

使用sh可以用 Python 函数的语法去调用 shell 命令,比subprocess舒服多了

有了sh,就可以方便地用python写逻辑,而与系统的交互依然使用shell指令

sh并没有自己去实现一遍系统指令(也不现实),sh的原理很有趣,是通过ModuleType来实现的。有兴趣的同学可以参考源码

from sh import tail

def process_log_line(line):
    if "ERROR" in line:
        send_an_email_to_support(line)

process = tail("-f", "info.log", _out=process_log_line)

# ... do other stuff here ...

process.wait()

path.py

简化文件系统相关操作。与文件系统的相关操作,在python中有些分散,path.py把它们聚合在一个类文件对象里

path.py implements a path objects as first-class entities, allowing common operations on files to be invoked on those path objects directly

from path import Path
d = Path('/home/guido/bin')
for f in d.files('*.py'):
    f.chmod(0755)

###Watchdog 监视文件系统改动.事件驱动真是适合用来写监控逻辑啊

Python library and shell utilities to monitor filesystem events

可以在python中使用,也提供shell指令

###pythonpy

the swiss army knife of the command line

让python更方便与shell配合使用,行为更像过滤器

ls | py -x '"mv `%s` `%s.txt`" % (x,x)' | sh

###psutil

A cross-platform process and system utilities module for Python

方便用来查看系统信息(CPU, memory, disks, network)

###Fabric

Simple, Pythonic remote execution and deployment.

自动化运维工具,也可用于自动化本地任务,本地机器无非也只是一个普通的host

###ansible 大大有名的自动化运维工具,热度已远超Fabric,当部署环境巨复杂是,ansible playbook就是救星了。当然学习成本也是在不低,edX就是用它来自动化部署的,有700+ task好像


#用户身份与进程权限

顺便提一下用户身份与进程权限,python脚本中与系统交互(操作文件等),必然涉及到权限问题,所以我们需要了解linux的权限机制

linux中,子进程将继承了父进程的所有权限

当Linux加载内核文件以后,就开始运行第一个程序 /sbin/init,它的作用是初始化系统环境,init是第一个运行的程序,它的进程编号(pid)为1。其他所有进程都从它衍生,都是它的子进程。init进程在运行各种开机启动的程序之后,会执行一个login的子进程。我们将用户名和密码传递给login子进程。login在查询了/etc/passwd和/etc/shadow,并确定了其合法性之后,运行(利用exec)一个shell进程,shell进程有效身份被设置成为该用户的身份。

终于轮到我们的python进程登场啦,python进程从shell中启动,python权限为执行它的用户的权限,此后python中调用的shell指令则为python的子进程,权限与python相同


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK