#!/usr/bin/env python
from threading import Thread
import subprocess
from Queue import Queue
import re
import MySQLdb
import smtplib
#Import the email modules we'll need
from email.mime.text import MIMEText
num_ping_threads=10
num_arp_threads=10
in_queue=Queue()
out_queue=Queue()
sum=0
#ips=["iquadcore-01","amd64","aaaaa","xue"]
def Sql(count):
try:
connection=MySQLdb.connect(host="172.20.33.19",user="root",passwd="reqiq iu",db="hostlist")
except:
print "Could not connect to MySQL server."
try:
cursor= connection.cursor()
cursor.execute("select hostname from servers where area='beijing'")
print "Rows selected: ", cursor.rowcount
for row in cursor.fetchall():
print row[0]
count=count+1
print "Thread %s : Pinging %s" % (count,row[0])
ret= subprocess.call("ping -c 1 %s" %(row[0]),
shell=True,
stdout=open('/dev/null','w'),
stderr=subprocess.STDOUT)
if ret==0:
print "%s: is alive" %(row[0])
sql="update servers set status='OnLine' where hostname=%s"
param=(row[0])
cursor.execute(sql,param)
try:
f=open('status_online.txt','a')
f.write("%s OnLine\n" %(row[0]))
f.close()
except:
print "Could not open file."
#place valid ip address in next queue
else:
print "%s: did not respond" %(row[0])
try:
f=open('status_offline.txt','a')
f.write("%s OffLine\n" %(row[0]))
f.close()
except:
print "Could not open file."
cursor.close()
except:
print "Could not selete to MySQL server."
#mail function
def Mail():
mail_server= 'Your email server address'
mail_server_port=25
from_addr='Your mail address'
to_addr='Mail address'
fp=open('status_offline.txt','r')
msg=MIMEText(fp.read())
fp.close()
msg['Subject']='hosts status'
msg['From']=from_addr
msg['To']=to_addr
s=smtplib.SMTP(mail_server,mail_server_port)
s.sendmail(from_addr,to_addr,msg.as_string())
s.quit()
sql_queue=Sql(sum)
Mail_queue=Mail()