python脚本:salt api

简述

saltstack感觉非常强大,常用于自动化运维,使用salt api与目标主机进行通信,然后管理主机资源等

  • 安装salt
yum install salt-master salt-minion salt-api
pip install PyOpenSSL
  • 自制ssl证书


    TIM图片20180707111954.png
  • 配置salt api

mkdir /etc/salt/master.d
mkdir /etc/salt/master.d
touch api.conf eauth.conf
  • api.conf
rest_cherrypy:
  port: 8081
  disable_ssl: True
  • eauth.conf
external_auth:
  pam:
    saltapi:
      - .*
      - '@wheel'
      - '@runner'
  • 启动salt master minion api
systemctl start salt-master
systemctl start salt-minion
systemctl start salt-api
  • 导入依赖包
import requests
# salt-pepper,封装了salt api http方式的请求
from pepper import Pepper
  • salt api登陆
url = 'http://127.0.0.1:8081'
username = 'saltapi'
password = 'saltapi'
eauth = 'pam'
salt_con = Pepper(url)
ret = salt_con.login(username, password, eauth)
print(ret)

# 返回结果
{
    'perms': ['.*', '@wheel', '@runner'],
    'start': 1530939127.623945,
    'token': '36d8ed121d6abbfc7d496c5b9bc99dc82357e1c3',
    'expire': 1530982327.623945,
    'user': 'saltapi',
    'eauth': 'pam'
}
  • 执行命令(eg: test.ping)
low = {
    'client': 'local',
    'tgt': 'minion1',
    'fun': 'test.ping'
}
salt_con.low([low])

# 返回结果
{'return': [{'minion1': True}]}
  • 执行命令(ps: 通过ip管理minion)
low = {
    'client': 'local',
    'tgt': '192.168.88.128',
    'expr_form': 'ipcidr',
    'fun': 'test.ping'
}
salt_con.low([low])

# 返回结果
{'return': [{'minion1': True}]}
  • 获取grains的部分信息
low = {
    'client': 'local',
    'tgt': 'minion1',
    'fun': 'grains.item',
    'arg': ['id', 'os']
}
salt_con.low([low])

# 返回结果
{'return': [{'minion1': {'os': 'CentOS', 'id': 'minion1'}}]}
  • 异步执行任务
low = {
    'client': 'local_async',
    'tgt': 'minion1',
    'fun': 'cmd.run',
    'arg': ['fdisk -l']
}
salt_con.low([low])

# 返回结果
{'return': [{'jid': '20180707131021897781', 'minions': ['minion1']}]}
  • 获取异步任务的结果
low = {
    'client': 'runner',
    'tgt': 'minion1',
    'fun': 'jobs.lookup_jid',
    'jid': '20180707131021897781'
}
salt_con.low([low])

# 返回结果
{
    'return': [{
        'minion1':  \
    Disk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk label type: dos
    Disk identifier: 0x000ac8a7
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/sda1   *        2048     2099199     1048576   83  Linux
    /dev/sda2         2099200    41943039    19921920   8e  Linux LVM
    
    Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk label type: dos
    Disk identifier: 0x2aafce60
    
       Device Boot      Start         End      Blocks   Id  System
    /dev/sdb1            2048    41943039    20970496   83  Linux
    ]}

你可能感兴趣的:(python脚本:salt api)