1. #!/usr/bin/python 2. """ 3. USAGE: 4. ./query.py -u[HOST] -i[SERVER_ID] -n[NAME] 5. 6. """ 7. import optparse, os, re, string, sys, urllib, warnings 8. warnings.simplefilter('ignore', DeprecationWarning) 9. from Cookie import Cookie 10. from urlparse import urljoin 11. import MySQLdb 12. 13. import pylib.configobj as COBJ 14. 15. import logging; log=logging.getLogger('ut3_master') 16. 17. file = os.path.abspath( 18. os.path.join(os.path.dirname(__file__), '../', '../', 'config.ini')) 19. config = COBJ.load(file) 20. HOST = config['DB_SERVER'] 21. USER = config['DB_USER'] 22. PASS = config['DB_PASSWD'] 23. DB = config['DB_DB'] 24. 25. def qstr(s): 26. return "'%s'" % s.replace('\\', '\\\\').replace("'", "\'") 27. 28. def dbconn(*a, **k): 29. def new_conn(): 30. conn = MySQLdb.connect(HOST,USER,PASS,DB) 31. try: 32. cursor = conn.cursor(*a, **k) 33. cursor.execute("SHOW TABLES") 34. cursor.execute("SET AUTOCOMMIT=0;") 35. cursor.close() 36. except (MySQLdb.OperationalError, AttributeError): 37. return new_conn() 38. else: 39. return conn 40. return new_conn() 41. 42. 43. def insert(r, server_id, verbose, debug): 44. conn = dbconn() 45. cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) 46. rec = {'name' : qstr(r[0]), 47. 'ip_address' : qstr(r[1]), 48. 'unique_id' : qstr(r[2]), 49. 'hash' : qstr(r[3]), 50. 'server_id' : server_id 51. } 52. if duplicate(rec, verbose, debug): 53. if verbose: 54. print 'DUPLICATE, returning' 55. return 56. else: 57. if verbose: 58. print 'INSERTING NEW PLAYER %s' % rec['name'] 59. sql = '''INSERT INTO hkey 60. (name, ip_address, unique_id, hash, server_id) 61. VALUES 62. (%(name)s, %(ip_address)s, %(unique_id)s, %(hash)s, %(server_id)s)''' % rec 63. cursor.execute(sql) 64. 65. 66. def duplicate(rec, verbose, debug): 67. conn = dbconn() 68. cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) 69. sql = '''SELECT key_id 70. FROM hkey 71. WHERE 72. name = %(name)s AND 73. ip_address = %(ip_address)s AND 74. unique_id = %(unique_id)s AND 75. hash = %(hash)s''' % rec 76. cursor.execute(sql) 77. recs = cursor.fetchall() 78. if recs: 79. 80. if verbose: 81. print 'PLAYER ALREAD EXISTS: %s' % rec['name'] 82. print 'PLAYER EXIST: ', recs 83. print 'QUERIED FOR: ', rec 84. 85. return True 86. else: 87. return False 88. 89. def urlencode(dict, order): 90. l = [] 91. for k in order: 92. v = dict[k] 93. 94. k = quote_plus(str(k)) 95. v = quote_plus(str(v)) 96. l.append(k + '=' + v) 97. return string.join(l, '&') 98. 99. 100. class WebBot(urllib.FancyURLopener): 101. #---------------------------------------------------------------------- 102. """ """ 103. #---------------------------------------------------------------------- 104. 105. USER_AGENT = 'Mozilla/2.02 (OS/2; I)' 106. SITENAME = 'Hedsteem' 107. despace_patt = re.compile('\s+') 108. verbose = False 109. debug = False 110. def despace(self, str): # Collapse Multiple Whitespace into One Blank 111. return WebBot.despace_patt.sub(' ', str) 112. 113. def __init__(self, baseurl='', debug=0): 114. urllib.FancyURLopener.__init__(self) 115. 116. self.delheader('User-agent') 117. self.addheader('User-agent', self.USER_AGENT) 118. self.addheader('HTTP_ACCEPT', 'text/html') 119. 120. self.baseurl = baseurl 121. self.debug = debug 122. self.cookies = Cookie() 123. 124. 125. def clear(self): 126. self.cookies = Cookie() 127. 128. def delheader(self, hdrtype): 129. keepers = [] 130. for h in self.addheaders: 131. if string.lower(h[0]) != string.lower(hdrtype): 132. keepers.append(h) 133. self.addheaders = keepers 134. 135. def webtransact(self, relurl, optdata=None): 136. url = urljoin(self.baseurl, relurl) 137. 138. if len(self.cookies): 139. self.delheader('Cookie') 140. for name, crumble in self.cookies.items(): 141. if string.lower(name) != 'path': 142. self.addheader('Cookie', crumble.OutputString()) 143. 144. 145. if optdata is None: webpage = self.open(url) 146. else: webpage = self.open(url, optdata) 147. 148. # Look For and Parse Any Relevant Headers 149. # -------------------------------------------------- 150. 151. if webpage.info().has_key('Set-cookie'): 152. items = webpage.info().getallmatchingheaders('Set-cookie') 153. 154. for i in items: 155. self.cookies.load(i) 156. 157. return webpage, url 158. 159. def do(self, debug, verbose): 160. self.verbose = verbose 161. self.debug = debug 162. try: 163. webpage, fullurl = self.webtransact('/current/players') 164. loginstr = webpage.read() 165. headers = webpage.info() 166. except Exception, e: 167. print str(e) 168. return [] 169. return self.getPlayers() 170. 171. 172. def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): 173. return None # do nothing 174. 175. def stripToTable(self, input): 176. ret = [] 177. r = False 178. input = input.split('\n') 179. for line in input: 180. if line.startswith('