Saltstack Python API使用笔记

From: 印象笔记

Date: 2017-10-26

1. ClientAPI介绍

ClientAPI官方文档

# 直接调用多台机器,用list
>>> local.cmd(tgt_type='list', tgt=['centos7_161019', 'centos7-170624'], fun='test.ping')
{'centos7-170624': False, 'centos7_161019': True}

# 通过grains调用含指定信息的机器
>>> local.cmd(tgt_type='grain', tgt='os:Centos', fun='test.ping')
{'centos7-170624': False, 'centos7_161019': True}

# 调用所有机器
>>> local.cmd(tgt='*', fun='test.ping')
{'centos7-170624': False, 'centos7_161019': True}
1.1 tgt_type说明
"""
:param tgt_type: The type of ``tgt``. Allowed values:
    * ``glob`` - Bash glob completion - Default
    * ``pcre`` - Perl style regular expression
    * ``list`` - Python list of hosts
    * ``grain`` - Match based on a grain comparison
    * ``grain_pcre`` - Grain comparison with a regex
    * ``pillar`` - Pillar data comparison
    * ``pillar_pcre`` - Pillar data comparison with a regex
    * ``nodegroup`` - Match on nodegroup
    * ``range`` - Use a Range server for matching
    * ``compound`` - Pass a compound match string
    * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address.
"""
1.2 func说明

Saltstack官方Modules

"""
:param fun: The module and function to call on the specified minions of
    the form ``module.function``. For example ``test.ping`` or
    ``grains.items``.
    Compound commands
        Multiple functions may be called in a single publish by
        passing a list of commands. This can dramatically lower
        overhead and speed up the application communicating with Salt.
        This requires that the ``arg`` param is a list of lists. The
        ``fun`` list and the ``arg`` list must correlate by index
        meaning a function that does not take arguments must still have
        a corresponding empty list at the expected index.
:type fun: string or list of strings
:param arg: A list of arguments to pass to the remote function. If the
    function takes no arguments ``arg`` may be omitted except when
    executing a compound command.
:type arg: list or list-of-lists
:param kwarg: A dictionary with keyword arguments for the function.
:param kwargs: Optional keyword arguments.
    Authentication credentials may be passed when using
    :conf_master:`external_auth`.
    For example: ``local.cmd('*', 'test.ping', username='saltdev',
    password='saltdev', eauth='pam')``.
    Or: ``local.cmd('*', 'test.ping',
    token='5871821ea51754fdcea8153c1c745433')``
"""

2. 操作案例

# which方式:返回cmds列表里第一个找到的值
>>> local.cmd(tgt='centos7_161019', fun='cmd.which_bin', kwarg={'cmds': ['python', 'python2']})
{'centos7_161019': '/usr/bin/python'}

# 执行一个普通的date命令
>>> local.cmd(tgt='centos7_161019', fun='cmd.run', kwarg={'cmd': 'date'})
{'centos7_161019': 'Wed Oct 18 11:16:41 CST 2017'}

# 查看root用户的crontab列表
>>> local.cmd(tgt='centos7_161019', fun='cron.ls', kwarg={'user': 'root'})
{
    "centos7_161019": {
        "env": [],
        "crons": [],
        "special": [],
        "pre": [
            "0 0 * * * /home/work/log.sh",
            "*/3 * * * * /usr/sbin/ntpdate 1.cn.pool.ntp.org",
            "*/1 * * * * /home/work/grafana/insert_test_data.sh"
        ]
    }
}

# 跑iostate
>>> local.cmd(tgt='centos7_161019', fun='disk.iostat', kwarg={'interval': 1, 'count': 5})
{
    "centos7_161019": {
        "sda": {
            "await": 0.17,
            "wkB/s": 5.34,
            "w_await": 0.35,
            "avgqu-sz": 0.0,
            "w/s": 0.11,
            "svctm": 0.11,
            "%util": 0.04,
            "r/s": 0.6,
            "avgrq-sz": 10.71,
            "wrqm/s": 1.16,
            "rrqm/s": 0.21,
            "r_await": 0.14,
            "rkB/s": 13.67
        },
        "dm-0": {
            "await": 0.18,
            "wkB/s": 0.57,
            "w_await": 0.41,
            "avgqu-sz": 0.0,
            "w/s": 0.08,
            "svctm": 0.11,
            "%util": 0.03,
            "r/s": 0.56,
            "avgrq-sz": 8.15,
            "wrqm/s": 0.0,
            "rrqm/s": 0.0,
            "r_await": 0.15,
            "rkB/s": 12.49
        },
        "dm-1": {
            "await": 0.36,
            "wkB/s": 4.7,
            "w_await": 0.41,
            "avgqu-sz": 0.0,
            "w/s": 1.18,
            "svctm": 0.01,
            "%util": 0.0,
            "r/s": 0.25,
            "avgrq-sz": 1.6,
            "wrqm/s": 0.0,
            "rrqm/s": 0.0,
            "r_await": 0.1,
            "rkB/s": 1.0
        },
        "sys": {
            "%steal": 0.0,
            "%system": 0.57,
            "%user": 0.76,
            "%idle": 98.65,
            "%iowait": 0.01,
            "%nice": 0.0
        }
    }
}

# 校验服务器文件的哈希值
>>> local.cmd(tgt='centos7_161019', fun='file.check_hash', kwarg={'path': '/tmp/a', 'file_hash': '939916e1974db06f4d4963320a64c55d'})
{'centos7_161019': True}

# 修改文件属性:正确返回None
>>> local.cmd(tgt='centos7_161019', fun='file.chown', kwarg={'path': '/tmp/a', 'user': 'nobody', 'group': 'nobody'})
{'centos7_161019': None}

# 从本地(salt-master)发送文件a到远端服务器的send_file_to_server
>>> local.cmd(tgt='centos7_161019', fun='file.copy', kwarg={'src': '/tmp/a', 'dst': '/tmp/send_file_to_server'})
{'centos7_161019': True}

3. Windows官方Modules

模块名称说明备注
salt.modules.win_autoruns列出windows自启动服务
salt.modules.win_certutil module管理cert管理器(https)
salt.modules.win_dacl管理访问控制
salt.modules.win_disk磁盘信息
salt.modules.win_dism module部署映像服务和管理
salt.modules.win_dns_client管理dns配置
salt.modules.win_dsc*
salt.modules.win_file管理和查看文件属性
salt.modules.win_firewallwindows防火墙
salt.modules.win_groupadd查看和管理用户群组
salt.modules.win_iis moduleIIS管理
salt.modules.win_ipwindows网卡
salt.modules.win_lgpo本地策略(组策略,例如gpedit.msc)
salt.modules.win_license modulewindows正版序列号
salt.modules.win_network网络信息,网络连通性
salt.modules.win_ntp获取、设置ntp server
salt.modules.win_pathwin系统环境变量
salt.modules.win_pkg软件包管理需要windows repo
salt.modules.win_pki module通过pki client管理“证书管理器”
salt.modules.win_powercfg电源管理器
salt.modules.win_psget module通过psget管理powershellpowershellget
salt.modules.win_repo管理windows software repo
salt.modules.win_servermanager通过server manager powershell管理服务器服务的安装包
salt.modules.win_service管理windows服务
salt.modules.win_shadowwindows账号管理用户禁用启用、改密码,登陆超时
salt.modules.win_smtp_server module管理IIS下的smtp服务器
salt.modules.win_snmp modulesnmp服务
salt.modules.win_status服务器状态cpu,磁盘,进程数,salt内存,uptime
salt.modules.win_system主机管理(基本信息、关机重启)主机名、工作组、域等
salt.modules.win_taskWindows Task Scheduler计划任务?
salt.modules.win_timezone时区hwclock也在这里
salt.modules.win_updatewindows更新废弃,使用win_wua
salt.modules.win_useradd账号管理,增删查、改密码、功能多功能和依赖都比shadow多很多
salt.modules.win_wua下载安装卸载都可最低要2008,没找到列出已更新

4. Windows补丁安装测试

4.1 完整代码段
import salt.client
import json
result = local.cmd(tgt_type='grain',
                   tgt='os_family:Windows',
                   fun='win_wua.download',
                   kwarg={'names': ['KB2911501']},
                   timeout=999999999)
result_str = json.dumps(result, indent=4, ensure_ascii=False)
print(result_str)
4.2 windows更新下载测试
# 执行
result = local.cmd(tgt_type='grain',
                   tgt='os_family:Windows',
                   fun='win_wua.download',
                   kwarg={'names': ['KB2911501']},
                   timeout=999999999)
# 结果
{
    "win7_160130": {
        "Updates": {
            "bd4aa95a-8bcb-4061-a2f2-c9ba118d705d": {
                "AlreadyDownloaded": false,
                "Result": "Download Succeeded",
                "Title": "用于 x64 系统的 Windows 7 和 Windows Server 2008 R2 SP1 上的 Microsoft .NET Framework 3.5.1 的安全更新程序 (KB2911501)"
            }
        },
        "Success": true,
        "Message": "Download Succeeded"
    }
}
4.3 windows更新安装测试
# 下载完后安装,失败了,错误不明
result = local.cmd(tgt_type='grain',
                   tgt='os_family:Windows',
                   fun='win_wua.install',
                   kwarg={'names': ['KB2911501']},
                   timeout=999999999)
# 结果1失败
{
    "win7_160130": "ERROR: Unknown Failure: (-2147352567, '发生意外。', (0, None, None, None, 0, -2147012866), None)"
}

# 再执行一次,结果2成功
# 结果
{
    "win7_160130": {
        "Updates": {
            "bd4aa95a-8bcb-4061-a2f2-c9ba118d705d": {
                "Result": "Installation Succeeded",
                "Title": "用于 x64 系统的 Windows 7 和 Windows Server 2008 R2 SP1 上的 Microsoft .NET Framework 3.5.1 的安全更新程序 (KB2911501)",
                "AlreadyInstalled": false,
                "RebootBehavior": "Poss Reboot"
            }
        },
        "Success": true,
        "NeedsReboot": false,
        "Message": "Installation Succeeded"
    }
}

5. salt异步方案

5.1 命令行异步任务

命令行加入参数--async

# 发起任务,返回job id:JID
salt -G 'os:windows' --async test.ping

# 根据JID查询任务状态及结果
salt-run jobs.lookup_jid "$jid" --output=json

可以获得先执行完的主机,未执行完毕的没有结果

5.2 python中执行异步任务

官方示例

import salt.client
local = salt.client.LocalClient()
local.cmd_async(tgt, fun, kwarg)

查询结果

In [1]: import salt.runner

In [2]: opts = salt.config.master_config('/etc/salt/master')

In [3]: runner = salt.runner.RunnerClient(opts)

In [4]: a = runner.cmd(fun='jobs.lookup_jid', kwarg={'jid': '20181102114908937128'})
salt-srvns-01:
    Fri Nov  2 11:49:09 CST 2018
    Fri Nov  2 11:49:39 CST 2018

In [5]: a
Out[5]: {'salt-srvns-01': 'Fri Nov  2 11:49:09 CST 2018\nFri Nov  2 11:49:39 CST 2018'}

查询某台主机的执行情况,会返回状态及PID

local.cmd(
    tgt='salt-srvns-01',
    fun='saltutil.find_job',
    kwarg={'jid': '20181102133130044435'}
)

转载于:https://www.cnblogs.com/tutuye/p/11590599.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值