Python连接Mysql数据库
#!/usr/bin/python #-- coding: utf-8 --
import MySQLdb import os import time import sys
''' Created on 2016年9月1日
desc:检查传入的IP列表是否已经部署
@author: tingyu '''
conn= MySQLdb.connect( host='132.121.130.18', port = 3306, user='root', passwd='hdp123', db ='test', ) cur = conn.cursor()
''' 根据IP列表文件路径,读取文件内的IP列表,判断该IP是否已经部署成功,如果已经部署成功则跳过 '''
logfile = os.getcwd() + os.sep + "deployIp.log"
def check(path): createLogFile(logfile) f = open(logfile, 'a') for line in open(path): if line is not None and line !='': line = line.strip('\n') line = line.strip(' ') print '当前处理的ip是: %s' % line sql = "select * from mondo_all where deploy_success='Y' and ip='"+line+"'" time.sleep(1) cunt = cur.execute(sql) if cunt ==0: f.write(line + '\n'); f.close()
def createLogFile(logpath):
print logpath
try:
if os.path.isfile(logpath):
os.remove(logpath)
else:
f = file(logpath,'w')
f.close()
except:
print '创建日志文件出错.........'
if name == 'main': iplist = 'G:\ips.txt' if len(sys.argv)==2: iplist = sys.argv[1] if os.path.isfile(iplist): check(iplist) else: print 'IP列表文件路径错误.......'
else:
print '参数不对,请重新输入命令'
print 'uage: python deployIp.py ip_file_path'