ansible 是做部署的好工具,不过感觉太大太复杂了。于是折腾了下用python调putty写了个简单点的实现复制和远程执行命令的脚本。Linux 下调试,windows没试过。
下面是代码
import os
import re
import sys
def runCommand(cmdline):
iod = os.popen(cmdline)
return iod.read()
def readFileContent(filepath):
f = open(filepath, "r")
content = f.read()
f.close()
return content
def parseAnsibleInventory(inventoryFile):
result = {}
content = readFileContent(inventoryFile)
lines = content.splitlines()
for l in lines:
#{
r = re.split(r'\s+', l)
if len(r)>1:
#{
result[r[0]] = {}
for a in r[1:]:
#{
if a.find("=")>0:
#{
b = a.split("=")
result[r[0]][b[0]]=b[1].replace("\"", "")
#}
#}
#}
#}
return result
hostInfos = parseAnsibleInventory(sys.argv[1])
specHost = sys.argv[2]
opr = sys.argv[3]
localfile = sys.argv[4]
if len(sys.argv)==6:
remotefile = sys.argv[5]
tempStrip = localfile.strip()
if opr=="from" and tempStrip[len(tempStrip)-1:]=="*":
print("local should not end with *")
exit(-1);
if opr=="from" or opr=="to":
#{
for h in hostInfos.keys():
#{
if specHost=="all" or h==specHost:
#{
if opr=="from":
#{
runCommand("echo n|./pscp -P %s -l %s -pw %s -q -r %s:%s %s"%(hostInfos[h]["ansible_ssh_port"],
hostInfos[h]["ansible_ssh_user"],
hostInfos[h]["ansible_ssh_pass"],
hostInfos[h]["ansible_host"],
remotefile,
localfile))
#}
elif opr=="to":
#{
runCommand("echo n|./pscp -P %s -l %s -pw %s -q -r %s %s:%s"%(hostInfos[h]["ansible_ssh_port"],
hostInfos[h]["ansible_ssh_user"],
hostInfos[h]["ansible_ssh_pass"],
localfile,
hostInfos[h]["ansible_host"],
remotefile))
#}
#}
#}
#}
elif opr=="shell":
#{
for h in hostInfos.keys():
#{
if specHost=="all" or h==specHost:
#{
content = runCommand("echo n|./plink -P %s -l %s -pw %s %s \"%s\""%(hostInfos[h]["ansible_ssh_port"],
hostInfos[h]["ansible_ssh_user"],
hostInfos[h]["ansible_ssh_pass"],
hostInfos[h]["ansible_host"],
localfile.replace("\"", "\\\"")))
if content!=None:
print()
print(content)
#}
#}
#}
# python3 ansibleSimilar.py /mnt/ansible/hosts hostid to /tmp/srcfile /tmp/
# python3 ansibleSimilar.py /mnt/ansible/hosts hostid shell "ls -l"
# python3 ansibleSimilar.py /mnt/ansible/hosts hostid shell "ps -ef|grep programName |grep -v grep|awk '{print \\\$2}'| xargs kill "