范例 参考http://john88wang.blog.51cto.com/2165294/1745339
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
|
#!/usr/bin/python
""
" Check Zookeeper Cluster
zookeeper version should be newer than 3.4.x
# echo mntr|nc 127.0.0.1 2181
zk_version 3.4.6-1569965, built on 02
/20/2014
09:09 GMT
zk_avg_latency 0
zk_max_latency 4
zk_min_latency 0
zk_packets_received 84467
zk_packets_sent 84466
zk_num_alive_connections 3
zk_outstanding_requests 0
zk_server_state follower
zk_znode_count 17159
zk_watch_count 2
zk_ephemerals_count 1
zk_approximate_data_size 6666471
zk_open_file_descriptor_count 29
zk_max_file_descriptor_count 102400
# echo ruok|nc 127.0.0.1 2181
imok
""
"
import
sys
import
socket
import
re
import
subprocess
from StringIO
import
StringIO
import
os
zabbix_sender =
'/opt/app/zabbix/sbin/zabbix_sender'
zabbix_conf =
'/opt/app/zabbix/conf/zabbix_agentd.conf'
send_to_zabbix = 1
############# get zookeeper server status
class ZooKeeperServer(object):
def __init__(self, host=
'localhost'
, port=
'2181'
, timeout=1):
self._address = (host, int(port))
self._timeout = timeout
self._result = {}
def _create_socket(self):
return
socket.socket()
def _send_cmd(self, cmd):
""
" Send a 4letter word command to the server "
""
s = self._create_socket()
s.settimeout(self._timeout)
s.connect(self._address)
s.send(cmd)
data = s.recv(2048)
s.close()
return
data
def get_stats(self):
""
" Get ZooKeeper server stats as a map "
""
data_mntr = self._send_cmd(
'mntr'
)
data_ruok = self._send_cmd(
'ruok'
)
if
data_mntr:
result_mntr = self._parse(data_mntr)
if
data_ruok:
result_ruok = self._parse_ruok(data_ruok)
self._result = dict(result_mntr.items() + result_ruok.items())
if
not self._result.has_key(
'zk_followers'
) and not self._result.has_key(
'zk_synced_followers'
) and not self._result.has_key(
'zk_pending_syncs'
):
##### the tree metrics only exposed on leader role zookeeper server, we just set the followers' to 0
leader_only = {
'zk_followers'
:0,
'zk_synced_followers'
:0,
'zk_pending_syncs'
:0}
self._result = dict(result_mntr.items() + result_ruok.items() + leader_only.items() )
return
self._result
def _parse(self, data):
""
" Parse the output from the 'mntr' 4letter word command "
""
h = StringIO(data)
result = {}
for
line
in
h.readlines():
try:
key, value = self._parse_line(line)
result[key] = value
except ValueError:
pass
# ignore broken lines
return
result
def _parse_ruok(self, data):
""
" Parse the output from the 'ruok' 4letter word command "
""
h = StringIO(data)
result = {}
ruok = h.readline()
if
ruok:
result[
'zk_server_ruok'
] = ruok
return
result
def _parse_line(self, line):
try:
key, value = map(str.strip, line.
split
(
'\t'
))
except ValueError:
raise ValueError(
'Found invalid line: %s'
% line)
if
not key:
raise ValueError(
'The key is mandatory and should not be empty'
)
try:
value = int(value)
except (TypeError, ValueError):
pass
return
key, value
def get_pid(self):
# ps -ef|grep java|grep zookeeper|awk '{print $2}'
pidarg =
''
'ps -ef|grep java|grep zookeeper|grep -v grep|awk '
{print $2}
' '
''
pidout = subprocess.Popen(pidarg,shell=True,stdout=subprocess.PIPE)
pid = pidout.stdout.readline().strip(
'\n'
)
return
pid
def send_to_zabbix(self, metric):
key =
"zookeeper.status["
+ metric +
"]"
if
send_to_zabbix > 0:
#print key + ":" + str(self._result[metric])
try:
subprocess.call([zabbix_sender,
"-c"
, zabbix_conf,
"-k"
, key,
"-o"
, str(self._result[metric]) ], stdout=FNULL, stderr=FNULL, shell=False)
except OSError, detail:
print
"Something went wrong while exectuting zabbix_sender : "
, detail
else
:
print
"Simulation: the following command would be execucted :\n"
, zabbix_sender,
"-c"
, zabbix_conf,
"-k"
, key,
"-o"
, self._result[metric],
"\n"
def usage():
""
"Display program usage"
""
print
"\nUsage : "
, sys.argv[0],
" alive|all"
print
"Modes : \n\talive : Return pid of running zookeeper\n\tall : Send zookeeper stats as well"
sys.
exit
(1)
accepted_modes = [
'alive'
,
'all'
]
if
len(sys.argv) == 2 and sys.argv[1]
in
accepted_modes:
mode = sys.argv[1]
else
:
usage()
zk = ZooKeeperServer()
# print zk.get_stats()
pid = zk.get_pid()
if
pid !=
""
and mode ==
'all'
:
zk.get_stats()
# print zk._result
FNULL =
open
(os.devnull,
'w'
)
for
key
in
zk._result:
zk.send_to_zabbix(key)
FNULL.close()
print pid
elif
pid !=
""
and mode ==
"alive"
:
print pid
else
:
print 0
|
我对比上面搞了自己的
1
2
3
4
5
|
1.
cat
qa_servers.txt
[dev]
t8 ansible_ssh_user=root ansible_ssh_host=xx
[cs]
t7 ansible_ssh_user=root ansible_ssh_host=xx
|
1
2
3
4
5
|
2.
cat
test
.sh
#!/bin/bash
if
[ `
ps
-ef|
grep
tomcat|
grep
/opt
|
wc
-l` -gt 0 ];
then
echo
`
ifconfig
|
grep
'inet '
|
grep
-
v
'127.0'
|
xargs
|
awk
-F
'[ :]'
'{print $3}'
`
fi
|
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
|
3.
cat
test
.sh
#!/bin/bash
if
[ `
ps
-ef|
grep
tomcat|
grep
/opt
|
wc
-l` -gt 0 ];
then
echo
`
ifconfig
|
grep
'inet '
|
grep
-
v
'127.0'
|
xargs
|
awk
-F
'[ :]'
'{print $3}'
`
fi
[root@jk home]
# cat test.py
import
ansible.runner
from ansible.color
import
stringc
import
sys
import
socket
import
re
import
subprocess
host_list=
'qa_servers.txt'
private_key_file=
'/root/.ssh/id_rsa'
pattern=
'*'
forks=10
timeout=30
module_name=
'script'
module_args=
'test.sh'
# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
host_list=host_list,
private_key_file=private_key_file,
pattern=pattern,
forks=forks,
timeout=timeout,
module_name=module_name,
module_args=module_args
).run()
#print results
if
results is None:
print
"No hosts found"
sys.
exit
(1)
print results
for
(
hostname
, result)
in
results[
'contacted'
].items():
if
not
'failed'
in
result:
ip=result[
'stdout'
].strip()
if
ip !=
""
:
output=
open
(
'/home/ip.txt'
,
'a'
)
output.write(ip)
output.write(
'\n'
)
|
1
2
3
|
4.运行 python
test
.py
验证
cat
/home/ip
.txt
简单来说,就是处理ansible的输出
|
本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1812500,如需转载请自行联系原作者