Automatiser la suppression de machines sur OCS Server 1.01.
From Tuxunix
Pre-requis
- Installer le package "python-mysqldb"
Exemple
$ ./ocs_delete_wkst.py file_liste_poste_OCS_for_remove.txt Connection establish [done]. Query execution... Connection close [done]. Log file : /var/log/ocsRemovePoste.log Bye ;-)
$ cat /var/log/ocsRemovePoste.log DELETE 'WIN01' DELETE 'WIN02' Poste NAME : 'test' Not Present in base, so not remove! Finish Thu Jun 26 19:57:58 CEST 2008, all right men! ;-)
Code
1.#!/usr/bin/python 2.# -*- coding: utf-8 -*- 3. 4.# 5.#@Name ocs_delete_wkst.py 6.#@Note delete poste on ocs server 7.#@Author pierre@tuxedo.fr 8.#@Date 19/16/2008 9.#@Depends file list poste name / Only OCS 1.01 10.#@Licence NO COPYRIGHT! GNU/GPL (RIGHT TO INFORMATION FOR ALL) 11.#@Version 0.2 12.# 13. 14.import os, sys, MySQLdb, shutil, gzip, datetime, time 15. 16.# 17.#Global var 18.#################### 19.HOSTNAMEFORDB="127.0.0.1" 20.HOSTNAMEFORUSER="xxxx" 21.HOSTNAMEFORPWD="xxxxx" 22.HOSTNAMEFORNAMEDB="ocsweb" 23.SAVEFILEPLX="/tmp/SavelistePosteOcsForDelete.txt" 24.value="""################################################################# 25.#fichier contenant le nom des poste a effacer dans OCS INVENTORY# 26.#################################################################""" 27.LOGFILE="/var/log/ocsRemovePoste.log" 28.listTableOcs=["accesslog", "accountinfo", "bios", "controllers", "devices","download_history", "drives", "inputs", "memories", "modems","monitors", "networks", "ports", "printers", "registry", "slots","softwares", "sounds", "storages", "videos", "locks" ] 29. 30. 31. 32. 33.# 34.#Object class 35.################### 36.class mysql(object): 37. """Access gestion OCS MySQL base""" 38. def __init__(self): 39. self.conn = None 40. self.cu = None 41. self.resultCom = None 42. self.resultReq = None 43. 44. def connectionStart(self, host, user, pwd, db): 45. try: 46. self.conn = MySQLdb.connect( host, user, pwd, db) 47. self.cu = self.conn.cursor() 48. print "Connection establish [done]." 49. except IOError: 50. print "Error connection base MySQL : %s" %(db) 51. os.sys.exit(1) 52. def requestOcs(self, req): 53. if self.cu != None: 54. self.resultReq = self.cu.execute(req) 55. self.resultReq = self.cu.fetchone() 56. self.resultCom = self.cu.execute("COMMIT") 57. else: 58. print "Request execution problem..." 59. if self.resultReq != None and self.resultCom != None: 60. return self.resultReq 61. 62. def connectionClose(self): 63. self.cu.close() 64. self.conn.close() 65. print "Connection close [done]." 66. 67.class GzipCompressor(object): 68. """Gzip compression""" 69. file_pattern = '%s.%d.gz' 70. 71. def __init__(self): 72. pass 73. 74. def compress(self, filename): 75. if os.path.isfile(filename): 76. dfn = filename + '.1.gz' 77. if os.path.exists(dfn): 78. os.remove(dfn) 79. zf = gzip.GzipFile(dfn, 'wb') 80. zf.write(file(filename, 'rb').read()) 81. zf.close() 82. os.remove(filename) 83. 84.class fileOpe(object): 85. """Operation file""" 86. def __init__(self): 87. pass 88. 89. def readFile(self, file): 90. """Read file temp and return all data in string variable and 91. delete temp file""" 92. f=open(file) 93. data=f.read() 94. f.close() 95. if os.path.exists(file): 96. os.remove(file) 97. #print "Temp File remove : %s"%(file) 98. return data 99. 100. def copyWithNoComment(self, source, destination): 101. """copy file with delete comments""" 102. try: 103. fs = open(source, 'r') 104. fd = open(destination, 'w') 105. while 1: 106. txt = fs.readline() 107. if txt =='': 108. break 109. if txt[0] != "#": 110. fd.write(txt) 111. fs.close() 112. fd.close() 113. except IOError: 114. print "Error Open file %s, or %s"%(source, destination) 115. 116. def removeFile(self, file): 117. """remove file""" 118. if os.path.exists(file) and os.path.isfile(file): 119. os.remove(file) 120. else: 121. print "Error not remove file %s"%(file) 122. 123. def addFile(self, file, valIncrem): 124. """Create file""" 125. try : 126. f=open(file, 'a') 127. f.write(valIncrem+"\n") 128. f.close() 129. except IOError: 130. print "Error Open file %s"%(file) 131. 132. 133.# 134.#Main 135.##################### 136.if len(sys.argv) < 2: 137. print "No arguments!" 138. print "Usage: %s file_liste_poste_OCS_for_remove"%(sys.argv[0]) 139.elif os.path.isfile(sys.argv[1]): 140. ORIGFILENAME=sys.argv[1] 141. #Instance object bdd 142. base = mysql() 143. base.connectionStart(HOSTNAMEFORDB, HOSTNAMEFORUSER, HOSTNAMEFORPWD,HOSTNAMEFORNAMEDB) 144. 145. #Instance object file 146. f = fileOpe() 147. f.copyWithNoComment(sys.argv[1], SAVEFILEPLX) 148. liste=f.readFile(SAVEFILEPLX) 149. print "Query execution..." 150. if liste != "": 151. for i in liste.split(): 152. idWkst = base.requestOcs("select ID from hardware WHERE NAME= '"+i+"'") 153. 154. if idWkst != None and str(idWkst[0]) != "": 155. #Deleting a network device 156. macAddr = base.requestOcs("SELECT macaddr FROM 157. networks WHERE hardware_id='"+str(idWkst[0])+"'") 158. if macAddr[0] != "": 159. base.requestOcs("DELETE FROM netmap WHERE mac='"+str(macAddr[0])+"'") 160. 161. #Delete all record in ocs tables 162. for j in listTableOcs: 163. base.requestOcs("DELETE FROM "+j+" WHERE 164. HARDWARE_ID = '"+str(idWkst[0])+"'") 165. #Delete main table 166. base.requestOcs("DELETE FROM hardware WHERE 167. NAME = '"+i+"'") 168. #Deleted computers tracking 169. traca = base.requestOcs("SELECT IVALUE FROM config 170. WHERE IVALUE>0 AND NAME='TRACE_DELETED'") 171. if traca[0] == 1: 172. base.requestOcs("insert into deleted_equiv(DELETED,EQUIVALENT) values("+str(idWkst[0])+",NULL)") 173. 174. 175. f.addFile(LOGFILE, "DELETE '"+i+"'") 176. else: 177. f.addFile(LOGFILE, "Poste NAME : '"+i+"' Not Present in base, so not remove!") 178. 179. else: 180. f.addFile(LOGFILE, "File: "+str(ORIGFILENAME)+" is empty!") 181. 182. base.connectionClose() 183. #Close log file 184. f.addFile(LOGFILE, "Finish "+str(time.ctime())+", all right men! ;-)") 185. print "Log file : %s"%(LOGFILE) 186. #Compress log file if > 56Ko 187. if os.path.getsize(LOGFILE) >= 56643: 188. #Instance compress 189. comp = GzipCompressor() 190. comp.compress(LOGFILE) 191. 192. #Delete contents liste PLX file 193. f.removeFile(ORIGFILENAME) 194. f.addFile(ORIGFILENAME, value) 195. #print "Generate New file liste PLX : %s"%(sys.argv[1]) 196. print "Bye ;-)" 197.else: 198. print "Error %s is not a valid file"%(sys.argv[1])

