|
#!/usr/bin/env python
#coding:utf-8
import etcd
import time
import json
import socket
import fcntl
import struct
import uuid
import commands
from optparse import OptionParser
import sys
import os
from collections import OrderedDict
from multiprocessing import cpu_count
ttl= 300
processname="cmdb_agent"
def uniquecheck(processname,pid):
print commands.getstatusoutput("ps -ef|grep %s|grep -v grep|grep -v %s|awk '{print $2}'|xargs kill -9" %(processname,pid))
def setetcddata(hostname,pushjson,ttl):
client = etcd.Client(host='172.16.110.47', port=2379,read_timeout=20)
client.write('/cmdb/{0}'.format(hostname),pushjson, ttl=ttl)
def getoptparse():
parser = OptionParser()
parser.add_option("-p",dest="projectname",help=u"项目名称")
parser.add_option("-i",dest="ifname",
help=u"默认网卡",default = "ens33")
parser.add_option("-P", dest="pre",
help=u"hostname前缀", default="auto")
(options, args) = parser.parse_args()
if not options.projectname:
print u"项目名称为空"
sys.exit()
projectname = options.projectname
ifname = options.ifname
hostnamepre=options.pre
print projectname,ifname,hostnamepre
return projectname,ifname,hostnamepre
def create_hostname(projectname,ip,hostnamepre):
ipsplit = ip.split(".")
if hostnamepre == "auto":
if int(ipsplit[1]) > 100:
hostnamepre= "qm-hd2a"
else:
hostnamepre = "qm-hd2b"
hostname = "{0}-{1}-{2}_{3}".format(hostnamepre,projectname,ipsplit[2],ipsplit[3])
print hostname
return hostname
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
def get_mac_address():
mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
return ":".join([mac[e:e+2] for e in range(0,11,2)])
def get_serverconfig():
meminfo = OrderedDict()
try:
with open('/proc/meminfo') as f:
for line in f:
meminfo[line.split(':')[0]] = line.split(':')[1].strip()
MemTotal = meminfo.get("MemTotal")
MemTotal = float(MemTotal.split()[0]) / 1024 / 1024
except:
MemTotal = 0
return str(cpu_count()),'%.2fG' %MemTotal
def set_hostname(hostname):
locahostname = socket.getfqdn(socket.gethostname())
if locahostname == hostname:
return 1
print commands.getstatusoutput('hostname {0}'.format(hostname))
print commands.getstatusoutput("sed -i 's/^HOSTNAME=.*$/HOSTNAME={0}/' /etc/sysconfig/network".format(hostname))
if __name__=='__main__':
selfpid = str(os.getpid())
uniquecheck(processname,selfpid)
projectname, ifname, hostnamepre = getoptparse()
ip = get_ip_address(ifname)
hostname=create_hostname(projectname,ip,hostnamepre)
macaddr = get_mac_address()
cputotal,memtotal = get_serverconfig()
print set_hostname(hostname)
pushjson = json.dumps({"macaddr":macaddr,"ip":ip,"hostname":hostname,"projectname":projectname,"cputotal":cputotal,"memtotal":memtotal})
setetcddata(hostname, pushjson, ttl)
|
|
|