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
|
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'
fp = open ( '/home/ip.txt' , "w+" )
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()
if results is None :
print "No hosts found"
sys.exit( 1 )
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' )
fp.close()
|
1
2
3
4
5
6
7
|
cat test.sh
if [ `cat / etc / crontab|grep .sh|grep - v SHELL|awk '{print $8}' |uniq|wc - l` - gt 0 ];then
echo `ifconfig|grep 'inet ' |grep - v '127.0' |xargs|awk - F '[ :]' '{print $3}' `
echo `cat / etc / crontab|grep .sh|grep - v SHELL|awk '{print $8}' |uniq`
fi
|
1
2
3
|
cat qa_servers.txt
ip1
ip2
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import os,sys,re
sfile = "/home/ip.txt"
with open (sfile, 'r' ) as f:
rlist = f.readlines()
llen = len (rlist)
for i in range (llen - 1 ):
if i % 2 = = 0 :
ip = rlist[i].strip()
print "ansible -i /etc/ansible/hosts %s -m shell -a 'mkdir -p /home/run/%s'" % (ip,ip)
command = rlist[i + 1 ].strip()
comlist = command.split( ' ' )
for j in comlist:
print "ansible -i /etc/ansible/hosts %s -m synchronize -a 'mode=pull src=%s dest=/home/run/%s/'" \
% (ip,j,ip)
|
自动生成
1
2
|
ansible - i / etc / ansible / hosts ip1 - m shell - a 'mkdir -p /home/run/ip1'
ansible - i / etc / ansible / hosts ip1 - m synchronize - a 'mode=pull src=/home/jenkins.sh dest=/home/run/ip1/'
|
需要两个python脚本,生成最后的脚本,执行就可以同步各个客户端中/etc/crontab的脚本。
一个简单而笨的思路。
本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1925140,如需转载请自行联系原作者