Q-Logo 我的学习笔记分享

Python fabric远程运维之查询系统状态

Fabric介绍

Fabric是一个Python库,可通过SSH在远程服务器上执行命令,返回有用的Python对象。其官网 是http://www.fabfile.org/ 。

Fabric is a high level Python (2.7, 3.4+) library designed to execute shell commands remotely over SSH, yielding useful Python objects in return

由于历史的原因,Fabric的版本比较混乱。可以参考 http://www.fabfile.org/upgrading.html#upgrading , http://www.fabfile.org/installing.html 及https://www.cnblogs.com/anliven/p/9186994.html 了解关于Fabric版本的更多信息。

Fabric安装

这里使用的是官方最新版的fabric,安装方式如下:

$ pip install fabric

创建Python文件

在本地机器上创建fabfile.py文件,此文件用于在一个或多个远程机器(在hosts中定义),上执行一系列的状态查询命令(在commands中定义,此处的远程机器系统为CentOS 或Redhat),并打印查询结果。

from fabric import Connection

hosts = [

{'hostname':'192.168.99.100', # host name of remote machine

'user':'username', # name of remote machine user

'password':'password', # password of user

},

# {other host ...},

]

commands = [

'date',

'hostname',

'uname -a',

'whoami',

'pwd',

'cat /etc/*release',

'cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c',

'df -h',

'mount',

'cat /etc/fstab',

'getconf LONG_BIT',

'cat /proc/meminfo',

'free -m',

'ifconfig -a',

'java -version',

'perl -V',

]

def get_many_info(c):

print('-'*20)

for cmd in commands:

result = c.run(cmd, hide=True, warn=True)

if result.failed:

msg_fail = 'Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}, \ngot stderr:\n{0.stderr}'

print(msg_fail.format(result))

else:

msg = 'Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}'

print(msg.format(result))

if __name__ == "__main__":

for host in hosts:

conn = Connection(host=host.get('hostname'),user=host.get('user'),connect_kwargs={'password':host.get('password')})

get_many_info(conn)

conn.close()

运行并查看结果

在本机命令行运行python fabric.py,即可批量查询并获取到结果。