Advertisement
Guest User

Untitled

a guest
Jul 21st, 2016
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.11 KB | None | 0 0
  1. __author__ = 'victor.grivtsov'
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. from datetime import datetime
  6. import xlrd
  7. import sys
  8. from pytils import translit
  9. import subprocess
  10. import telnetlib
  11. from PyQt4 import QtCore, QtGui, uic
  12. import traceback
  13. import contextlib
  14.  
  15. settings = open("../settings.txt") # OSS, DB login/pass
  16.  
  17. dt = datetime.now().strftime('[%Y%m-%d %H:%M]')
  18.  
  19. #parsing settings file
  20. arr = []
  21. for i in settings:
  22. arr.append(i.rstrip().split())
  23. HOST = arr[0][0].strip()
  24. HOST_LTE_OSS = arr[1][0].strip()
  25. HOST2 = arr[2][0].strip()
  26. HOST2_name = arr[3][0].strip()
  27. HOST_LTE = arr[4][0].strip()
  28. HOST_LTE_NAME = arr[5][0].strip()
  29. user = arr[6][0].strip()
  30. password = arr[7][0].strip()
  31.  
  32. # new work_scripts directory
  33. def new_dir():
  34.  
  35. global path
  36. path = ("../work_scripts/%s" % startname)
  37.  
  38. if os.path.exists(path):
  39. for (p,d,f) in os.walk(path, False):
  40. for file_name in f: # remove all files
  41. os.remove(os.path.join(p, file_name))
  42. for dir_name in d: # remove all dirs
  43. os.rmdir(os.path.join(p,dir_name))
  44. new_path = path
  45. os.mkdir(new_path)
  46.  
  47. else:
  48. new_path = path
  49. os.mkdir(new_path)
  50.  
  51. # ------------------------------Get-Excel-Data--------------------------
  52. # Extract_RNC_RBS_ID
  53. def extdata():
  54.  
  55. global data_dict
  56. data_dict = dict(rnc_id='Отсутсвует', longitude='Отсутсвует',
  57. latitude='Отсутсвует', location='Отсутсвует',
  58. location_rus='Отсутсвует',altitude='Отсутсвует')
  59.  
  60. workbook = xlrd.open_workbook('../DB/New_data_T2_v4.xlsx')
  61. worksheet = workbook.sheet_by_name('Table')
  62. for row in range(worksheet.nrows):
  63. data = (worksheet.cell_value(row,0))
  64. if str(startname) == str(data):
  65. for col in range(worksheet.ncols):
  66. data_dict["rnc_id"] = str(worksheet.cell_value(row, 4))
  67. data_dict["longitude"] = str(round(worksheet.cell_value(row, 5)*3600000)) # Coordinates for OSS
  68. data_dict["latitude"] = str(round(worksheet.cell_value(row, 6)*3600000)) # Coordinates for OSS
  69. try:
  70. data_dict["location"] = str(translit.translify(worksheet.cell_value(row, 17)))
  71. data_dict["location_rus"] = str((worksheet.cell_value(row, 17)))
  72. except:
  73. data_dict["location"] = "Mordor"
  74. log_f(startname + ": rbs_name_error")
  75. pass
  76.  
  77.  
  78. try:
  79. data_dict["altitude"] = str(int(worksheet.cell_value(row, 13)))
  80. except location_rus:
  81. data_dict["altitude"] = "0"
  82. log_f(startname + ": altitude = 0")
  83.  
  84. del workbook
  85. return data_dict
  86. # ----------------------------------------------------------------------
  87. # Extract_IP
  88. def extip():
  89.  
  90. global ip_dict
  91. ip_dict = dict(duw_ip='Отсутсвует', lte_oam='Отсутсвует',
  92. tcu_ip='Отсутсвует')
  93.  
  94. try:
  95. workbook = xlrd.open_workbook('../DB/MOS_IP_PLAN_V5_.xlsx')
  96. worksheet = workbook.sheet_by_name('IP план')
  97. for row in range(worksheet.nrows):
  98. data = (worksheet.cell_value(row,0))
  99. if str(startname) == str(data):
  100. for col in range(worksheet.ncols):
  101. ip_dict["duw_ip"] = (worksheet.cell_value(row, 7))
  102. ip_dict["lte_oam"]= (worksheet.cell_value(row, 12))
  103. ip_dict["tcu_ip"] = (worksheet.cell_value(row, 35))
  104.  
  105. del workbook
  106. except:
  107. log_f(startname + ": error:" + traceback.format_exc())
  108. pass
  109.  
  110. return ip_dict
  111. # ----------OSS-Config--------------------------------------------------
  112.  
  113. # Writer
  114. def replace_tmpl(tmpl, var_list):
  115.  
  116. lines = open(tmpl).readlines()
  117. src = "%s"*len(lines) % tuple(lines)
  118. for key, var in var_list.items():
  119. src = str.replace(src, key, var)
  120. return src
  121.  
  122. def NE_Site_create():
  123.  
  124. NE_Site = './template/NE_Site.txt'
  125. body = replace_tmpl(NE_Site, {'$userLabel': startname,
  126. '$altitude': data_dict["altitude"],
  127. '$location': data_dict["location"],
  128. '$longitude': data_dict["longitude"],
  129. '$latitude': data_dict["latitude"]
  130. })
  131.  
  132. file = open("%s/01_OSS_Site_%s.xml" % (path, startname), "w")
  133. file.write(body)
  134. file.close()
  135.  
  136. def NE_RBS_create():
  137. NE_RBS = './template/NE_RBS_create.txt'
  138. body = replace_tmpl(NE_RBS, {'$RNC': data_dict["rnc_id"],
  139. '$ManagedElementId': startname,
  140. '$associatedSite': startname,
  141. '$ipAddress': ip_dict["duw_ip"]
  142. })
  143. file = open("%s/02_NE_RBS_%s.xml" % (path, startname), "w")
  144. file.write(body)
  145. file.close()
  146.  
  147. def NE_TCU_create():
  148. NE_TCU = './template/NE_TCU_create.txt'
  149. body = replace_tmpl(NE_TCU, {'$ManagedElementId': startname,
  150. '$associatedSite' : startname,
  151. '$ipAddress': ip_dict["tcu_ip"],
  152. '$RNC': data_dict["rnc_id"]
  153. })
  154. file = open("%s/03_NE_TCU_%s.xml"% (path, startname), "w")
  155. file.write(body)
  156. file.close()
  157.  
  158. def NE_ERBS_create():
  159. NE_RBS = './template/NE_ERBS_create.txt'
  160. body = replace_tmpl(NE_RBS, { '$ManagedElementId': startname,
  161. '$associatedSite': startname,
  162. '$ipAddress': ip_dict["lte_oam"]
  163. })
  164. file = open("%s/04_NE_ERBS_%s.xml" % (path, startname), "w")
  165. file.write(body)
  166. file.close()
  167. # ----------------------------------------------------------------------
  168.  
  169. # function for subprocess printout
  170. def unbuffered(p, stream='stdout'):
  171. newlines = ['\n', '\r\n', '\r']
  172. stream = getattr(p, stream)
  173. with contextlib.closing(stream):
  174. while True:
  175. out = []
  176. last = stream.read(1)
  177. # Don't loop forever
  178. if last == '' and p.poll() is not None:
  179. break
  180. while last not in newlines:
  181. # Don't loop forever
  182. if last == '' and p.poll() is not None:
  183. break
  184. out.append(last)
  185. last = stream.read(1)
  186. out = ''.join(out)
  187. yield out
  188.  
  189.  
  190. def ftp_ses():
  191.  
  192. # -------------------------FTP-to-OSS-session---------------------------
  193. # Create script for WinSCP
  194. ftp_line = []
  195. try:
  196. FTP_commands = open("commandsftp.txt", "w")
  197. FTP_commands.write(
  198. """open ftp://%s:%s@%s:21
  199. option batch on
  200. option confirm off
  201. cd scripts
  202. put "../work_scripts\%s"
  203. exit
  204.  
  205. """ % (user, password, HOST, startname))
  206. FTP_commands.close()
  207.  
  208. # Start .com, for open new window use winscp.exe
  209. cmd = 'WinSCP.com /console /script=commandsftp.txt'
  210. p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True,)
  211. p.wait()
  212.  
  213. for line in unbuffered(p):
  214. log_f(startname + ": ftp_load:" + line)
  215. ftp_line.append(line)
  216.  
  217. os.remove("commandsftp.txt")
  218. except:
  219. log_f(startname + ": ftp_error:" + traceback.format_exc())
  220. pass
  221. return ftp_line
  222.  
  223. def teln_ses(): # Telnet session for creating 3G oss elements
  224.  
  225. try:
  226. tn = telnetlib.Telnet(HOST2)
  227.  
  228. tn.read_until(b"login: ")
  229.  
  230. tn.write(user.encode('ascii') + b"\n")
  231.  
  232. if password:
  233. tn.read_until(b"Password: ")
  234. tn.write(password.encode('ascii') + b"\n")
  235. tn.read_until(("@%s>" % HOST2_name).encode('ascii'))
  236.  
  237. tn.write(("/opt/ericsson/arne/bin/import.sh -f /home/%s/scripts/%s/01_OSS_Site_%s.xml -import"
  238. % (user, startname, startname)).encode('ascii') + b"\n")
  239.  
  240. tn.read_until(("@%s>" % HOST2_name).encode('ascii'))
  241. tn.write(("/opt/ericsson/arne/bin/import.sh -f /home/%s/scripts/%s/02_NE_RBS_%s.xml -import"
  242. % (user, startname, startname)).encode('ascii') + b"\n")
  243.  
  244. tn.read_until(("@%s>" % HOST2_name).encode('ascii'))
  245. if tcu:
  246. tn.write(("/opt/ericsson/arne/bin/import.sh -f /home/%s/scripts/%s/03_NE_TCU_%s.xml -import"
  247. % (user, startname, startname)).encode('ascii') + b"\n")
  248.  
  249. else:
  250. tn.write(b"exit\n")
  251. print(tn.read_all().decode('ascii'))
  252. except:
  253. log_f(startname + ": telnet_3G_error:" + traceback.format_exc().encode('utf-8').decode('1251'))
  254. else:
  255. log_f(startname + ": telnet_3G_creation OK")
  256.  
  257.  
  258. def teln_ses_lte(): # Telnet session for creating LTE oss elements
  259.  
  260. try:
  261. tn = telnetlib.Telnet(HOST_LTE)
  262.  
  263. tn.read_until(b"login: ")
  264.  
  265. tn.write(user.encode('ascii') + b"\n")
  266.  
  267. if password:
  268. tn.read_until(b"Password: ")
  269. tn.write(password.encode('ascii') + b"\n")
  270.  
  271. tn.write(("/opt/ericsson/arne/bin/import.sh -f /home/%s/scripts/%s/04_NE_ERBS_%s.xml -import"
  272. % (user, startname, startname)).encode('ascii') + b"\n")
  273.  
  274. tn.read_until(("@%s>" % HOST_LTE_NAME).encode('ascii'))
  275. tn.write(b"exit\n")
  276.  
  277. except:
  278. log_f(startname + ": telnet_4G_error:" + traceback.format_exc().encode('utf-8').decode('1251'))
  279. else:
  280. log_f(startname + ": telnet_4G_OK")
  281.  
  282. # log writer
  283. def log_f(strr):
  284.  
  285. log_file = open("../logfile.txt", "a")
  286. log_file.write(dt + strr + "\n")
  287.  
  288. def main():
  289.  
  290. app = QtGui.QApplication(sys.argv)
  291. window = uic.loadUi("window.ui") # type: <class 'PyQt4.QtGui.QWidget'>
  292.  
  293. def initial():
  294. global startname
  295. startname = (window.lineEdit.text()).upper()
  296. try:
  297. data_dict = extdata()
  298. ip_dict = extip()
  299.  
  300. window.plainTextEdit.appendPlainText(startname)
  301. window.plainTextEdit.appendPlainText("Адрес:%s" % data_dict["location_rus"])
  302. window.plainTextEdit.appendPlainText("Высота:%s" % data_dict["altitude"])
  303. window.plainTextEdit.appendPlainText("Долгота:%s" % data_dict["longitude"])
  304. window.plainTextEdit.appendPlainText("Широта:%s" % data_dict["latitude"] )
  305. window.plainTextEdit.appendPlainText("RNC:%s" % data_dict["rnc_id"])
  306. window.plainTextEdit.appendPlainText("3G IP:%s" % ip_dict["duw_ip"] )
  307. window.plainTextEdit.appendPlainText("TCU IP:%s" % ip_dict["tcu_ip"] )
  308. window.plainTextEdit.appendPlainText("4G IP:%s" % ip_dict["lte_oam"])
  309. except:
  310. log_f(startname + ": error:" + traceback.format_exc())
  311. pass
  312.  
  313. def conf_scripts():
  314. startname = (window.lineEdit.text()).upper()
  315. initial()
  316.  
  317. new_dir()
  318. NE_Site_create()
  319. NE_RBS_create()
  320. NE_ERBS_create()
  321. if window.checkBox.isChecked():
  322. NE_TCU_create()
  323.  
  324. log_f(startname + ": scripts_gen")
  325. ftp_line = ftp_ses()
  326. for line in ftp_line:
  327. print(line)
  328. window.plainTextEdit.appendPlainText(line.encode('utf-8').decode('ascii'))
  329.  
  330. def tln3g():
  331. global tcu
  332. if window.checkBox.isChecked():
  333. tcu = True
  334. else:
  335. tcu = False
  336.  
  337. startname = (window.lineEdit.text()).upper()
  338.  
  339. teln_ses()
  340.  
  341. def tln4g():
  342. startname = (window.lineEdit.text()).upper()
  343. teln_ses_lte()
  344. # ------------------Buttons---------------------------------------------
  345. QtCore.QObject.connect(window.pushButton_4, QtCore.SIGNAL("clicked()"), initial)
  346. QtCore.QObject.connect(window.pushButton_3, QtCore.SIGNAL("clicked()"), conf_scripts)
  347. QtCore.QObject.connect(window.pushButton, QtCore.SIGNAL("clicked()"), tln3g)
  348. QtCore.QObject.connect(window.pushButton_2, QtCore.SIGNAL("clicked()"), tln4g)
  349.  
  350. window.show()
  351. sys.exit(app.exec_())
  352.  
  353. if __name__ == '__main__':
  354. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement