-
Notifications
You must be signed in to change notification settings - Fork 0
/
salt.py
113 lines (99 loc) · 3.47 KB
/
salt.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
from errbot import BotPlugin, botcmd, ShlexArgParser
from optparse import OptionParser
import json
import shlex
import logging
import requests
log = logging.getLogger(name='errbot.plugins.Salt')
try:
import pepper
except ImportError:
log.error("Please install 'salt-pepper' python package")
class Salt(BotPlugin):
"""Plugin to run salt commands on hosts"""
def get_configuration_template(self):
""" configuration entries """
config = {
'paste_api_url': None,
'api_url': None,
'api_user': None,
'api_pass': None,
'api_auth': None,
}
return config
def pastebin(self, data):
''' Post the output to pastebin '''
clean_data = data
url = requests.post(
self.config['paste_api_url'],
data={
'content': clean_data,
},
)
log.debug('url: {}'.format(url))
return url.text.strip('"')
@botcmd
def salt(self, msg, args):
''' executes a salt command on systems
example:
!salt log*.local cmd.run 'cat /etc/hosts'
!salt log*.local test.ping
'''
parser = OptionParser()
(options, args) = parser.parse_args(shlex.split(args))
if len(args) < 2:
response = '2 parameters required. see !help salt'
self.send(msg.frm,
response,
message_type=msg.type,
in_reply_to=msg,
groupchat_nick_reply=True)
return
targets = args.pop(0)
action = args.pop(0)
api = pepper.Pepper(self.config['api_url'], debug_http=False)
auth = api.login(self.config['api_user'],
self.config['api_pass'],
self.config['api_auth'])
ret = api.local(targets,
action,
arg=args,
kwarg=None,
expr_form='pcre')
results = json.dumps(ret, sort_keys=True, indent=4)
self.send(msg.frm,
self.pastebin(results),
message_type=msg.type,
in_reply_to=msg,
groupchat_nick_reply=True)
@botcmd(split_args_with=ShlexArgParser())
def salt_grains(self, msg, args):
''' executes a salt command on systems
example:
!salt grains 'os:Centos' cmd.run 'cat /etc/hosts'
'''
if len(args) < 2:
response = '2 parameters required. see !help salt'
self.send(msg.frm,
response,
message_type=msg.type,
in_reply_to=msg,
groupchat_nick_reply=True)
return
targets = args.pop(0)
action = args.pop(0)
api = pepper.Pepper(self.config['api_url'], debug_http=False)
auth = api.login(self.config['api_user'],
self.config['api_pass'],
self.config['api_auth'])
ret = api.local(targets,
action,
arg=args,
kwarg=None,
expr_form='grain')
results = json.dumps(ret, sort_keys=True, indent=4)
self.send(msg.frm,
self.pastebin(results),
message_type=msg.type,
in_reply_to=msg,
groupchat_nick_reply=True)