Advertisement
Guest User

Untitled

a guest
Jan 8th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 49.99 KB | None | 0 0
  1. #!/usr/bin/python
  2. import os
  3. import platform
  4. import xml.etree.ElementTree as ET
  5. import uuid
  6. import sys,time,subprocess,socket,logging,stat
  7. import threading,subprocess
  8. import asyncore
  9. import pprint, socket, ssl
  10. from datetime import datetime,timedelta
  11.  
  12. def supported_os_msg():
  13. print "This script can be run on a machine with below operation systems."
  14. print "Ubuntu 12.04 and above"
  15. print "CentOS 6.5 and above"
  16. print "RHEL 6.7 and above"
  17. print "Debian 7 and above"
  18. print "Oracle Linux 6.4 and above"
  19. print "SLES 12 and above"
  20. print "OpenSUSE 42.2 and above"
  21.  
  22. def exitonconfirmation():
  23. while True:
  24. ans=raw_input("\nPlease enter 'q/Q' to exit...")
  25. if 'q' in ans or 'Q' in ans:
  26. sys.exit()
  27.  
  28. def log(message):
  29. logtime = time.strftime("%Y%m%d-%H%M%S")
  30. logfile.write(("[" + logtime + "] : " + message))
  31. logfile.write("\n")
  32.  
  33. def is_supported(OsVersion, LowestVersion):
  34. return ((OsVersion - LowestVersion >= 0) or (abs(OsVersion - LowestVersion) <= 0.01 ))
  35.  
  36. def is_package_installated(package):
  37. proc = subprocess.Popen(["which " + package], stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
  38. output = proc.stdout.read()
  39. return True if output else False
  40.  
  41. def run_shell_cmd(cmd):
  42. proc = subprocess.Popen([cmd], stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
  43. output_line = proc.stdout.read()
  44. log("Running cmd: " + cmd)
  45. log(output_line)
  46. err = proc.stderr.read()
  47. if err:
  48. log("Got error")
  49. log(err)
  50.  
  51. def get_pkg_installer_cmd_from_os(OsName):
  52. if OsName in ["Debian", "Ubuntu"]:
  53. installcmd='apt-get --assume-yes install'
  54. elif OsName in ["CentOS", "Oracle", "RHEL"]:
  55. installcmd='yum -y install'
  56. elif OsName in ["SLES", "OpenSUSE"]:
  57. installcmd='zypper install'
  58. else:
  59. installcmd='apt-get --assume-yes install'
  60. return installcmd
  61.  
  62. def install_packages(OsName, packages):
  63. pkg_installer_cmd = get_pkg_installer_cmd_from_os(OsName)
  64. for package in packages:
  65. if package == "iscsiadm":
  66. if OsName in ["CentOS", "Oracle", "RHEL"]:
  67. installcmd = pkg_installer_cmd + " iscsi-initiator-utils"
  68. else:
  69. installcmd = pkg_installer_cmd + " open-iscsi"
  70. else:
  71. installcmd = pkg_installer_cmd + " " + ("acl" if package == "setfacl" else package)
  72. p = subprocess.Popen([installcmd],shell=True)
  73. p.wait()
  74. p = subprocess.Popen(["which " + package],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  75. output = p.stdout.read()
  76. err = p.stderr.read()
  77. log(package +" installation output:"+output+".")
  78. log(package +" installation Error:"+err)
  79. if err and not err.isspace():
  80. log("Failed to install " + package)
  81. print "Failed to install " + package
  82. print "Error Details : .%s." % (err)
  83. exitonconfirmation()
  84.  
  85. def install_prereq_packages(OsName):
  86. packages = ["setfacl", "iscsiadm", "lshw"]
  87. package_map = {}
  88. for package in packages:
  89. package_map[package] = is_package_installated(package)
  90. packages_not_installed = list(filter(lambda package: package_map[package] == False, package_map.keys()))
  91. if len(packages_not_installed) > 0:
  92. pkg_msg = ",".join(map(lambda package: "'" + package + "'" ,packages_not_installed))
  93. if OsName in ["CentOS", "Oracle", "RHEL"]:
  94. pkg_msg = pkg_msg.replace("iscsiadm", "iscsi-initiator-utils")
  95. else:
  96. pkg_msg = pkg_msg.replace("iscsiadm", "open-iscsi")
  97. print "The script requires " + pkg_msg + " to run"
  98. print "Do you want us to install " + pkg_msg + " on this machine?"
  99. ans=raw_input("Please press 'Y' to continue with installation, 'N' to abort the operation. : ")
  100. if ans in ['y','Y']:
  101. install_packages(OsName, packages_not_installed)
  102. elif ans in ['n','N']:
  103. log("Aborting Installation...")
  104. print "Aborting Installation..."
  105. print "Please install " + pkg_msg + " and then run this script again."
  106. exitonconfirmation()
  107. else:
  108. log("You have entered invalid input.:"+ans)
  109. print "You have entered invalid input. Please try re-running the script."
  110. exitonconfirmation()
  111.  
  112. def check_for_open_SSL_TLS_v12():
  113. p=subprocess.Popen("openssl ciphers -v | awk '{print $2}' | sort | uniq",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  114. output = p.stdout.read()
  115. err = p.stderr.read()
  116. log("openssl output:"+output+".")
  117. if err:
  118. log("openssl Error:"+err)
  119. if err and not err.isspace() and output.isspace():
  120. log("error in getting cipher lists or no output")
  121. elif "TLSv1.2" in output:
  122. log("TLSv1.2 is supported")
  123. else:
  124. log("TLSv1.2 is not supported")
  125. print "Microsoft Azure File Folder Recovery script needs OpenSSL with TLSv1.2 cipher to securely connect to the recovery point in Azure."
  126. print "To know whether TLSv1.2 is supported in a OS, run this command."
  127. print "openssl ciphers -v | awk '{print $2}' | sort | uniq"
  128. print "The output should show TLSv1.2"
  129. exitonconfirmation()
  130.  
  131. ## Coremethods of ILR
  132.  
  133. def CheckForRAIDDisks(LogFolder):
  134. lshwpath=LogFolder+'/Scripts/lshw2.xml'
  135. lshwoutput = open(lshwpath,'w')
  136. proc=subprocess.Popen(['lshw -xml -class disk -class volume'],shell=True,stdout=lshwoutput)
  137. log('process started')
  138. proc.wait()
  139. log('process completed')
  140. log('process write completed')
  141. lshwoutput.flush()
  142. lshwoutput.close()
  143. tree = ET.parse(lshwpath)
  144. root = tree.getroot()
  145. VolumeIndex=1
  146. raidvolumeslist=list()
  147.  
  148. global isStorageSpaceExists
  149. isStorageSpaceExists = False
  150. for nodes in root:
  151. disk= nodes.attrib.get('class')
  152. if disk == 'disk':
  153. isMABILRDisk = False
  154. vendorname="linux"
  155. disklogicalname=""
  156. hasvolumes=False
  157. for child in nodes:
  158. #print child.tag
  159. if child.tag == 'vendor':
  160. #print child.tag + " " + child.text
  161. vendorname = child.text
  162. if vendorname == 'MABILR I' :
  163. isMABILRDisk = True
  164. log('Found MAB ILR Disk')
  165. log('Vendor : ' + vendorname)
  166. elif child.tag == 'logicalname' :
  167. disklogicalname=child.text
  168. log('Disk Logical Name :' + disklogicalname)
  169. else :
  170. childclass= child.attrib.get('class')
  171. #print isMABILRDisk
  172. if childclass == 'volume' :
  173. hasvolumes=True
  174. description=child.find('description')
  175. log("description:"+description.text)
  176. logname=child.find('logicalname')
  177. if logname != None:
  178. log('Logical Volume Name : ' + logname.text)
  179. if description.text == "Linux raid autodetect partition" or description.text == "Linux LVM Physical Volume partition":
  180. raidvolumeslist.append((disklogicalname+" | "+logname.text+" | "+description.text))
  181.  
  182. log("Has Volumes"+str(hasvolumes))
  183. if hasvolumes == False :
  184. log("found disk without volumes")
  185. diskxmlstring=ET.tostring(nodes)
  186. if "lvm" in diskxmlstring or "LVM" in diskxmlstring :
  187. raidvolumeslist.append((disklogicalname+" | ------- | LVM "))
  188. log("Found LVM")
  189.  
  190. if len(raidvolumeslist) > 0 :
  191. isStorageSpaceExists = True
  192. print "\nPlease find below the logical volume/RAID Array entities present in this machine."
  193. print "\n************ Volumes from RAID Arrays/LVM partitions ************"
  194. print "\nSr.No. | Disk | Volume | Partition Type "
  195. i=1
  196. for voldetail in raidvolumeslist:
  197. print "\n"+str(i)+") | "+voldetail
  198. i=i+1
  199.  
  200. def UnMountILRVolumes(LogFolder):
  201.  
  202. proc = subprocess.Popen(["mount | grep '"+LogFolder+"'"],
  203. stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,
  204. )
  205. err = proc.stderr.read()
  206. log("Mount List error:"+err)
  207. processoutput=proc.stdout.readlines()
  208. log("Mount List Output Len :%d" % (len(processoutput)))
  209. log("Mount List Output :%s." % (processoutput))
  210. if len(processoutput) > 0:
  211. records = processoutput[0].split('\n')
  212.  
  213. for record in records:
  214. log("UnMount Record :"+record)
  215. values = record.split(' ')
  216. log("UnMount Record :"+values[0])
  217. proc = subprocess.Popen(["umount '"+values[0]+"'"],
  218. stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,
  219. )
  220. output = proc.stdout.read()
  221. log("UnMount ouput:"+err)
  222. output = proc.stderr.read()
  223. log("UnMount error:"+err)
  224.  
  225. def MountILRVolumes(LogFolder):
  226. time.sleep(5)
  227. lshwpath = LogFolder+'/Scripts/lshw1.xml'
  228. lshwoutput = open(lshwpath,'w')
  229. proc=subprocess.Popen(['lshw -xml -class disk -class volume'],shell=True,stdout=lshwoutput)
  230. log('process started')
  231. proc.wait()
  232. log('process completed')
  233. log('process write completed')
  234. lshwoutput.flush()
  235. lshwoutput.close()
  236. tree = ET.parse(lshwpath)
  237. root = tree.getroot()
  238. VolumeIndex = 1
  239. volumeslist = list()
  240. raidvolumeslist = list()
  241. failedvolumeslist = list()
  242. for nodes in root:
  243. disk= nodes.attrib.get('class')
  244. if disk == 'disk':
  245. isMABILRDisk = False
  246. vendorname = "linux"
  247. disklogicalname = ""
  248. hasvolumes = False
  249. for child in nodes:
  250. #print child.tag
  251. if child.tag == 'vendor':
  252. #print child.tag + " " + child.text
  253. vendorname = child.text
  254. if vendorname == 'MABILR I':
  255. isMABILRDisk = True
  256. log('Found MAB ILR Disk')
  257. log('Vendor : ' + vendorname)
  258. elif child.tag == 'logicalname' and isMABILRDisk :
  259. disklogicalname=child.text
  260. log('Disk Logical Name :' + disklogicalname)
  261. else :
  262. childclass = child.attrib.get('class')
  263. #print isMABILRDisk
  264. if childclass == 'volume' and isMABILRDisk :
  265. hasvolumes=True
  266. description=child.find('description')
  267. log("description:"+description.text)
  268. logname=child.find('logicalname')
  269. if logname != None:
  270. log('Logical Volume Name : ' + logname.text)
  271. if description.text == "Linux raid autodetect partition" or description.text == "Linux LVM Physical Volume partition":
  272. raidvolumeslist.append((disklogicalname+" | "+logname.text+" | "+description.text))
  273. else:
  274. MountPath = LogFolder+'/Volume'+str(VolumeIndex)
  275. VolumeIndex = VolumeIndex+1
  276. log(MountPath)
  277. os.mkdir(MountPath)
  278. log("Mounting volume"+(logname.text)+" to path "+(MountPath))
  279. proc = subprocess.Popen(["mount",logname.text,MountPath],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  280. output = proc.stdout.read()
  281. err = proc.stderr.read()
  282. log("Mount Output:"+output+".")
  283. log("Mount Error:"+err)
  284. if err and not err.isspace():
  285. log("Mount failed for volume"+(logname.text)+" to path "+(MountPath))
  286. log("Retry: Mounting with nouuid option for volume"+(logname.text)+" to path "+(MountPath))
  287. proc = subprocess.Popen(["mount","-o","nouuid",logname.text,MountPath],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  288. output = proc.stdout.read()
  289. err = proc.stderr.read()
  290. log("Mount Output:"+output+".")
  291. log("Mount Error:"+err)
  292. if err and not err.isspace():
  293. log("Retry mount failed for volume"+(logname.text)+" to path "+(MountPath))
  294. failedvolumeslist.append((disklogicalname+" | "+logname.text+" | "+description.text))
  295. else:
  296. volumeslist.append((disklogicalname+" | "+logname.text+" | "+MountPath))
  297. else:
  298. volumeslist.append((disklogicalname+" | "+logname.text+" | "+MountPath))
  299. log("Has Volumes"+str(hasvolumes))
  300. if hasvolumes == False and isMABILRDisk :
  301. log("found MAB ILR disk without volumes")
  302. diskxmlstring=ET.tostring(nodes)
  303. if "lvm" in diskxmlstring or "LVM" in diskxmlstring :
  304. raidvolumeslist.append((disklogicalname+" | ------- | LVM "))
  305. log("Found LVM")
  306.  
  307. if len(volumeslist) > 0:
  308. print "\n************ Volumes of the recovery point and their mount paths on this machine ************"
  309. print "\nSr.No. | Disk | Volume | MountPath "
  310. i = 1
  311. for voldetail in volumeslist:
  312. print "\n"+str(i)+") | "+voldetail
  313. i = i+1
  314. else:
  315. print "\n0 volumes mounted as volumes are either RAID Arrays/LVM partitions or failed to mount."
  316.  
  317. if len(raidvolumeslist) > 0:
  318. print "\n************ Volumes from RAID Arrays/LVM partitions ************"
  319. print "\nSr.No. | Disk | Volume | Partition Type "
  320. i = 1
  321. for voldetail in raidvolumeslist:
  322. print "\n"+str(i)+") | "+voldetail
  323. i=i+1
  324. print "\nRun the following commands to mount and bring the partitions online."
  325. print "\nFor LVM partitions:"
  326. print "\n $ pvs <volume name as shown above> - To list the volume group names under this physical volume"
  327. print "\n $ lvdisplay <volume-group-name from the above command's result> - To list all logical volumes, names and their paths in this volume group"
  328. print "\n $ mount <LV path> </mountpath> - To mount the logical volumes to the path of your choice"
  329. print "\nFor RAID Arrays:"
  330. print "\n $ mdadm --detail --scan (To display details about all raid disks)"
  331. print " The relevant RAID disk will be named as '/dev/mdm/<RAID array name in the backed up VM>'"
  332. print "\n Use the mount command if the RAID disk has physical volumes"
  333. print " $ mount <RAID Disk Path> </mountpath>"
  334. print "\n If this RAID disk has another LVM configured in it then follow the same prcedure as outlined above for LVM partitions with the volume name being the RAID Disk name"
  335. if len(failedvolumeslist) > 0:
  336. print "\nThe following partitions failed to mount since the OS couldn't identify the filesystem."
  337. print "\n************ Volumes from unknown filesystem ************"
  338. print "\nSr.No. | Disk | Volume | Partition Type "
  339. i = 1
  340. for voldetail in failedvolumeslist:
  341. print "\n"+str(i)+") | "+voldetail
  342. i = i+1
  343. print "\nPlease refer to '"+LogFolder+ "/Scripts/MicrosoftAzureBackupILRLogFile.log' for more details."
  344. print "\n************ Open File Explorer to browse for files. ************"
  345.  
  346. def UpdateISCSIConfig(logfolder,TargetUserName,TargetPassword):
  347. iscsi_config_file='/etc/iscsi/iscsid.conf'
  348. iscsi_config_temp_file1=logfolder+"/Scripts/iscsidtemp1.conf"
  349. iscsi_config_temp_file2=logfolder+"/Scripts/iscsidtemp2.conf"
  350. iscsiconfig=open(iscsi_config_temp_file1,'w+')
  351. iscsiconfig.write("discovery.sendtargets.auth.authmethod =\n")
  352. iscsiconfig.write("discovery.sendtargets.auth.authmethod=\n")
  353. iscsiconfig.write("discovery.sendtargets.auth.authmethod \n")
  354. iscsiconfig.write("discovery.sendtargets.auth.username =\n")
  355. iscsiconfig.write("discovery.sendtargets.auth.username=\n")
  356. iscsiconfig.write("discovery.sendtargets.auth.username \n")
  357. iscsiconfig.write("discovery.sendtargets.auth.password =\n")
  358. iscsiconfig.write("discovery.sendtargets.auth.password=\n")
  359. iscsiconfig.write("discovery.sendtargets.auth.password \n")
  360. iscsiconfig.write("discovery.sendtargets.auth.username_in =\n")
  361. iscsiconfig.write("discovery.sendtargets.auth.username_in=\n")
  362. iscsiconfig.write("discovery.sendtargets.auth.username_in \n")
  363. iscsiconfig.write("discovery.sendtargets.auth.password_in =\n")
  364. iscsiconfig.write("discovery.sendtargets.auth.password_in=\n")
  365. iscsiconfig.write("discovery.sendtargets.auth.password_in \n")
  366. iscsiconfig.write("node.session.auth.authmethod =\n")
  367. iscsiconfig.write("node.session.auth.authmethod=\n")
  368. iscsiconfig.write("node.session.auth.authmethod \n")
  369. iscsiconfig.write("node.session.auth.username =\n")
  370. iscsiconfig.write("node.session.auth.username=\n")
  371. iscsiconfig.write("node.session.auth.username \n")
  372. iscsiconfig.write("node.session.auth.password =\n")
  373. iscsiconfig.write("node.session.auth.password=\n")
  374. iscsiconfig.write("node.session.auth.password \n")
  375. iscsiconfig.write("node.session.auth.username_in =\n")
  376. iscsiconfig.write("node.session.auth.username_in=\n")
  377. iscsiconfig.write("node.session.auth.username_in \n")
  378. iscsiconfig.write("node.session.auth.password_in =\n")
  379. iscsiconfig.write("node.session.auth.password_in=\n")
  380. iscsiconfig.write("node.session.auth.password_in \n")
  381. iscsiconfig.close()
  382. log("Removing old iscsi config entries.")
  383. updatediscsiconfig=open(iscsi_config_temp_file2,'w+')
  384. p=subprocess.Popen(["grep -v -f "+iscsi_config_temp_file1+" "+iscsi_config_file],
  385. stdout=updatediscsiconfig,shell=True,
  386. )
  387. p.wait()
  388.  
  389. log("Removed old iscsi config entries.")
  390. updatediscsiconfig.write("\ndiscovery.sendtargets.auth.authmethod = CHAP")
  391. updatediscsiconfig.write("\ndiscovery.sendtargets.auth.username = "+OSName+TargetUserName)
  392. updatediscsiconfig.write("\ndiscovery.sendtargets.auth.password = "+TargetPassword)
  393. updatediscsiconfig.write("\n#discovery.sendtargets.auth.username_in = username_in")
  394. updatediscsiconfig.write("\n#discovery.sendtargets.auth.password_in = password_in")
  395. updatediscsiconfig.write("\nnode.session.auth.authmethod = CHAP")
  396. updatediscsiconfig.write("\nnode.session.auth.username = "+OSName+TargetUserName)
  397. updatediscsiconfig.write("\nnode.session.auth.password = "+TargetPassword)
  398. updatediscsiconfig.write("\n#node.session.auth.username_in = username_in")
  399. updatediscsiconfig.write("\n#node.session.auth.password_in = password_in\n")
  400. log("successfully added new iscsi config entries.")
  401. updatediscsiconfig.flush()
  402. updatediscsiconfig.close()
  403. p=subprocess.Popen(["cp "+iscsi_config_temp_file2+" "+iscsi_config_file],
  404. stdout=subprocess.PIPE,shell=True,
  405. )
  406. output = p.stdout.read()
  407. log("CP output:"+output)
  408.  
  409. log("/etc/iscsi/iscsid.conf file is replaced successfully.")
  410.  
  411.  
  412.  
  413. def ILRMain(ilr_params):
  414. LogFolder = ilr_params['LogFolder']
  415. ScriptId = ilr_params['ScriptId']
  416. MinPort = ilr_params['MinPort']
  417. MaxPort = ilr_params['MaxPort']
  418. TargetPortalAddress = ilr_params['TargetPortalAddress']
  419. TargetPortalPortNumber = ilr_params['TargetPortalPortNumber']
  420. TargetNodeAddress = ilr_params['TargetNodeAddress']
  421. TargetUserName = ilr_params['TargetUserName']
  422. TargetPassword = ilr_params['TargetPassword']
  423. VMName = ilr_params['VMName']
  424. MachineName = ilr_params['MachineName']
  425. docleanup = ilr_params['DoCleanUp']
  426. global OSName
  427. OSName = ilr_params['OsNameVersion']
  428. LogFileName = LogFolder + "/Scripts/MicrosoftAzureBackupILRLogFile.log"
  429.  
  430. log("Log Folder Path: " + LogFolder)
  431. log("Log File Path: " + LogFileName)
  432. log("Script Id: " + ScriptId)
  433. log("MinPort: " + str(MinPort))
  434. log("MaxPort: " + str(MaxPort))
  435. log("TargetPortalAddress: " + TargetPortalAddress)
  436. log("TargetPortalPortNumber: " + str(TargetPortalPortNumber))
  437. log("TargetNodeAddress: " + TargetNodeAddress)
  438.  
  439.  
  440. if docleanup:
  441. log("Only Cleanup called")
  442. print "\nRemoving the local mount paths of the currently connected recovery point..."
  443.  
  444. if TargetPassword == "UserInput012345" and not docleanup :
  445. TargetPassword=raw_input("Please enter the password as shown on the portal to securely connect to the recovery point. : ")
  446. log("Input Password Length: "+str(len(TargetPassword)))
  447. if len(TargetPassword) != 15 :
  448. log("Password length is not 15 char. ")
  449. print "\nYou need to enter the complete 15 character password as shown on the portal screen. Please use the copy button beside the generated password and past here."
  450. exitonconfirmation()
  451.  
  452. scriptran=False
  453. isProcessRunning=False
  454. proc = subprocess.Popen(["tail","-n","1","/etc/MicrosoftAzureBackupILR/mabilr.conf"],
  455. stdout=subprocess.PIPE,stderr=subprocess.PIPE,
  456. )
  457. processoutput=proc.stdout.readlines()
  458. log("Output Len :%d" % (len(processoutput)))
  459. log("Output :%s." % (processoutput))
  460. if len(processoutput) > 0:
  461. lastrecord = processoutput[0].split('\n')
  462. log("Last Record in MABILR Config :%s." % (lastrecord))
  463. values = lastrecord[0].split(',')
  464. portnumber=values[4]
  465. processid=values[5]
  466. targetnodeaddress=values[3]
  467. lastvmname=values[6]
  468. lastlogfolder=values[7]
  469. scriptran=True
  470. proc=subprocess.Popen(["iscsiadm -m session"],
  471. stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,
  472. )
  473. output = proc.stdout.read()
  474. err = proc.stderr.read()
  475. log("Session Target Output:"+output+".")
  476. log("Session Target Error:"+err)
  477. if targetnodeaddress.lower() in output:
  478. if docleanup :
  479. ans='Y'
  480. else:
  481. print "\nWe detected a session already connected to a recovery point of the VM '"+lastvmname+"'."
  482. print "We need to unmount the volumes before connecting to the new recovery point of '"+VMName+"'"
  483. ans=raw_input("\nPlease enter 'Y' to proceed or 'N' to abort...")
  484.  
  485. if 'y' in ans or 'Y' in ans:
  486. log("Un mounting existing mount points.")
  487. UnMountILRVolumes(lastlogfolder)
  488. proc=subprocess.Popen(["iscsiadm -m node -T "+targetnodeaddress+" --logout"],
  489. stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,
  490. )
  491. output = proc.stdout.read()
  492. err = proc.stderr.read()
  493. log("Logout Target Output:"+output+".")
  494. log("Logout Target Error:"+err)
  495. if "successful." in output:
  496. log("Logout Succeeded.")
  497. if not docleanup:
  498. print "\nOlder session disconnected. Establishing a new session for the new recovery point...."
  499. else:
  500. print "It is recommended to close the earlier session before starting new connection to another RP."
  501. exitonconfirmation()
  502. else:
  503. UnMountILRVolumes(lastlogfolder)
  504.  
  505. if not docleanup:
  506. hostname=socket.gethostname()
  507. log("Host Name :"+hostname)
  508. vmname = VMName.split(';')
  509. if (hostname.lower() == vmname[2].lower() or hostname.lower() == MachineName.lower()):
  510. CheckForRAIDDisks(LogFolder)
  511. log("isStorageSpaceExists"+str(isStorageSpaceExists))
  512. if isStorageSpaceExists == True :
  513. print "\nMount the recovery point only if you are SURE THAT THESE ARE NOT BACKED UP/ PRESENT IN THE RECOVERY POINT."
  514. print "If they are already present, it might corrupt the data irrevocably on this machine."
  515. print "It is recommended to run this script on any other machine with similar OS to recovery files."
  516. ans=raw_input("\nShould the recovery point be mounted on this machine? ('Y'/'N') ")
  517. if 'y' in ans or 'Y' in ans:
  518. log("user selected to continue")
  519. else:
  520. print "\nPlease run this script on any other machine with similar OS to recover files."
  521. exitonconfirmation()
  522. UpdateISCSIConfig(LogFolder,TargetUserName,TargetPassword)
  523.  
  524. if scriptran == True:
  525. log("Script already ran earlier on this machine.")
  526. log("PortNumber:%s, PID:%s" % (portnumber,processid))
  527.  
  528. proc = subprocess.Popen(["ps","-p",processid,"-o","comm="],
  529. stdout=subprocess.PIPE,
  530. )
  531. processoutput=proc.stdout.readlines()
  532. #print "Output Len :%d" % (len(processoutput))
  533. #print "Output :%s." % (processoutput)
  534. if len(processoutput) > 0:
  535. processname = processoutput[0].split('\n')
  536. log("Process Name :%s." % (processname[0]))
  537. if processname[0] == "SecureTCPTunnel":
  538. log("SecureTCPTunnel process is already running")
  539. isProcessRunning=False
  540. log("Killing the existing SecureTCPTunnelProcess to free 3260 port in OSName:"+OSName)
  541. proc = subprocess.Popen(["kill","-9",processid],
  542. stdout=subprocess.PIPE,stderr=subprocess.PIPE
  543. )
  544. output = proc.stdout.read()
  545. err = proc.stderr.read()
  546. log("Kill output:"+output)
  547. log("Kill error:"+err)
  548. else:
  549. log("SecureTCPTunnel process is not running")
  550. else:
  551. log("Script didnt' ran earlier on this machine.")
  552.  
  553. if docleanup:
  554. log("Cleanup Completed")
  555. print "\nThe local mount paths have been removed."
  556. print "\nPlease make sure to click the 'Unmount disks' from the portal to remove the connection to the recovery point."
  557. exitonconfirmation()
  558.  
  559. if isProcessRunning == False:
  560. try:
  561. if "CentOS" in OSName or "Oracle" in OSName or "RHEL" in OSName:
  562. MinPort=3260
  563. MaxPort=3260
  564. log("Starting SecureTCPTunnel process...")
  565. log("with args:")
  566. log(LogFolder + "/Scripts/SecureTCPTunnel.py " + OSName + " " + LogFolder + " " + ScriptId + " " + str(MinPort) + " " + str(MaxPort) + " " + TargetPortalAddress + " " + str(TargetPortalPortNumber) + " " + TargetNodeAddress + " " + VMName)
  567. proc = subprocess.Popen([LogFolder + "/Scripts/SecureTCPTunnel.py",OSName,LogFolder,ScriptId,str(MinPort),str(MaxPort),TargetPortalAddress,str(TargetPortalPortNumber),TargetNodeAddress,VMName],
  568. stdout=subprocess.PIPE,stderr=subprocess.PIPE
  569. )
  570. pid=proc.pid
  571. log("pid : " + str(pid))
  572. except Exception as e:
  573. log("Exception raised while starting SecureTCPTunnel process")
  574. log(repr(e))
  575. if proc.stdout:
  576. output = proc.stdout.read()
  577. log("SecureTCPTunnel output:"+output)
  578. if proc.stderr:
  579. err = proc.stderr.read()
  580. log("SecureTCPTunnel error:"+err)
  581. found=True
  582. maxretrycount=2
  583. retrycount=0
  584. while found and retrycount < maxretrycount:
  585. try:
  586. time.sleep(1)
  587.  
  588. with open('/etc/MicrosoftAzureBackupILR/mabilr.conf','r') as f:
  589. lines = f.readlines()
  590. for line in lines:
  591. log(line)
  592. values = line.split(',')
  593. if values[0] == ScriptId and values[5] == str(pid):
  594. log("Secure TCP process added record to config file")
  595. found=False
  596. portnumber=values[4]
  597. except Exception as e:
  598. log("Exception raised while reading mabilr.conf file")
  599. #log("Exception: "+e.message)
  600. retrycount=retrycount+1
  601. if retrycount == maxretrycount:
  602. log("Secure TCP Process is not started after max retry count")
  603. if "CentOS" in OSName or "Oracle" in OSName or "RHEL" in OSName:
  604. print "We are unable to communicate via the port 3260 on this machine since it is being used by ISCSI target server or any other application. Please unblock the port or use another machine where the port is open for communicatoin."
  605. else:
  606. print "We are unable to use local port range "+str(MinPort)+"-"+str(MaxPort)+" for our communication on this machine. Please check if these ports are already being used by another application."
  607. print "Please refer to the logs at '"+ LogFolder +"/Scripts'"
  608. exitonconfirmation()
  609. else:
  610. log("SecureTCPTunnel started on Port %s" % (portnumber))
  611.  
  612. print "\nConnecting to recovery point using ISCSI service..."
  613. log(("Discovering Targets from Portal: "+TargetPortalAddress+","+str(TargetPortalPortNumber)))
  614. p=subprocess.Popen(["iscsiadm -m discovery -t sendtargets -p 127.0.0.1:"+portnumber],
  615. stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,
  616. )
  617.  
  618. output = p.stdout.read()
  619. err = p.stderr.read()
  620. log("Discovery Output:"+output+".")
  621. log("Discovery Error:"+err)
  622.  
  623. if ("127.0.0.1:"+str(portnumber)+",-1 "+TargetNodeAddress) in output:
  624. log("Discovery Succeeded.")
  625. log("Target Found: "+TargetNodeAddress)
  626. log("Connecting to target "+TargetNodeAddress+" ...")
  627. p=subprocess.Popen(["iscsiadm -m node -T "+TargetNodeAddress+" -p 127.0.0.1:"+portnumber+" --login"],
  628. stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,
  629. )
  630. output = p.stdout.read()
  631. err = p.stderr.read()
  632. log("Connect Target Output:"+output+".")
  633. log("Connect Target Error:"+err)
  634. if "successful." in output:
  635. log("Connection Succeeded.")
  636. print "\nConnection succeeded!"
  637. print "\nPlease wait while we attach volumes of the recovery point to this machine..."
  638. log("Mounting Volumes to the Mount Paths.")
  639. MountILRVolumes(LogFolder)
  640. log("Mounting of volumes completed successfully.")
  641. print "\nAfter recovery, remove the disks and close the connection to the recovery point by clicking the 'Unmount Disks' button from the portal or by using the relevant unmount command in case of powershell or CLI."
  642. print "\nAfter unmounting disks, run the script with the parameter 'clean' to remove the mount paths of the recovery point from this machine."
  643. elif "iscsiadm: default: 1 session requested, but 1 already present." in err or (not (output and not output.isspace())):
  644. log("Already connected to target.")
  645. print "\nThe target has already been logged in via an iSCSI session."
  646. log("Mounting Volumes to the Mount Paths.")
  647. MountILRVolumes(LogFolder)
  648. log("Mounting of volumes completed successfully.")
  649. print "\nAfter recovery, remove the disks and close the connection to the recovery point by clicking the 'Unmount Disks' button from the portal or by using the relevant unmount command in case of powershell or CLI."
  650. print "\nAfter unmounting disks, run the script with the parameter 'clean' to remove the mount paths of the recovery point from this machine."
  651. else:
  652. log("Connection to target failed.")
  653. print "\nException caught while connecting to the recovery point."
  654. print "\nPlease refer to the logs at '"+ LogFolder +"/Scripts'. You can also retry running the script from another machine. If problem persists, raise a support request with details about OS of machines where script was run and the entire log folder"
  655. elif "initiator failed authorization" in err:
  656. log("Discovery Failed.")
  657. print "\nThis script cannot connect to the recovery point. Either the password entered is invalid or the disks have been unmounted."
  658. print "Please enter the correct password or download a new script from the portal."
  659. elif "iscsid is not running" in err:
  660. log("Discovery Failed.")
  661. log("Failure Reason: iscsid is not running")
  662. print "\nException caught while connecting to the recovery point."
  663. print "\nFailure Reason: iscsid is not running. can not connect to iSCSI daemon (111)."
  664. print "\nPlease refer to the logs at '"+ LogFolder +"/Scripts'. You can also retry running the script from another machine. If problem persists, raise a support request with details about OS of machines where script was run and the entire log folder"
  665. else:
  666. log("Discovery Failed.")
  667. log("Target Not Found :"+TargetNodeAddress)
  668. log("Unable to acces the target URL : "+TargetPortalAddress+":"+str(TargetPortalPortNumber))
  669. log("Use below curl command to check the access to any URL and Port")
  670. log("curl "+TargetPortalAddress+":"+str(TargetPortalPortNumber)+" --connect-timeout 2")
  671. log("It will display this message if you have access. 'curl: (56) Failure when receiving data from the peer'")
  672. log("Else it will get timed out with message 'curl: (28) connect() timed out!'")
  673. print "\nUnable to access Recovery vault, check your proxy/firewall setting to ensure access to <"+TargetPortalAddress+":"+str(TargetPortalPortNumber)+">."
  674. print "\nIn general, make sure you meet the network connectivity requirements to Azure Recovery vault as specified here: https://docs.microsoft.com/en-us/azure/backup/backup-azure-vms-prepare#network-connectivity"
  675. print "\nIf problem persists despite meeting all the network connectivity requirements as specified above, please refer to the logs at '"+ LogFolder +"/Scripts'"
  676. exitonconfirmation()
  677.  
  678. def generate_securetcptunnel_code(script_folder):
  679. SecureTCPTunnelCode ="""#!/usr/bin/python
  680. import threading,subprocess
  681. import time
  682. import asyncore
  683. import pprint, socket, ssl
  684. import logging,sys,os
  685. from datetime import datetime,timedelta
  686. class SecureTCPTunnelServer(asyncore.dispatcher):
  687.  
  688. def __init__(self, port_range, ILRTargetInfo, ilr_config_file):
  689.  
  690. self.logger = logging.getLogger('SecureTCPTunnelServer')
  691.  
  692. asyncore.dispatcher.__init__(self)
  693. ilrconfig = open(ilr_config_file,"a+")
  694. minport, maxport = port_range
  695. port = minport
  696. self.ILRTargetInfo = ILRTargetInfo
  697. TargetPortalAddress, TargetPortalPortNumber,TargetNodeAddress,ScriptId,VMName,LogFolder = ILRTargetInfo
  698. gcthread = GCThread("GCThread",TargetNodeAddress)
  699. gcthread.start()
  700. while port <= maxport:
  701. try:
  702. SocketAddress = ('localhost', port)
  703. self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  704. self.bind(SocketAddress)
  705. self.address = self.socket.getsockname()
  706. self.listen(1)
  707. self.logger.info('Listening on %s', self.address)
  708. ilrconfig.write("\\n%s,%s,%d,%s,%d,%d,%s,%s" % (ScriptId,TargetPortalAddress,TargetPortalPortNumber,TargetNodeAddress,port,os.getpid(),VMName,LogFolder))
  709. ilrconfig.close()
  710. break
  711. except socket.error, (value,message):
  712. self.logger.error("socket.error - %d, Port: %d - %s" % (value,port,message))
  713. if value == 98:
  714. self.close()
  715. port=port+1
  716. else:
  717. break
  718. return
  719.  
  720. def handle_accept(self):
  721.  
  722. client_info = self.accept()
  723.  
  724. self.logger.info('Accepted client connection from %s', client_info[1])
  725.  
  726. try:
  727. cthread=ClientThread("ClientThread",clientsock=client_info[0],ILRTargetInfo=self.ILRTargetInfo)
  728. cthread.start()
  729. except Exception as e:
  730. self.logger.warning("Exception raised while creating client thread")
  731. #self.logger.warning("Exception: "+e.message)
  732. return
  733.  
  734.  
  735. def handle_close(self):
  736.  
  737. self.logger.info('Closing the Server.')
  738.  
  739. self.close()
  740.  
  741. return
  742.  
  743. class GCThread (threading.Thread):
  744.  
  745. def __init__(self, name, targetNodeAddress):
  746. self.logger = logging.getLogger('GCThread')
  747. threading.Thread.__init__(self)
  748. self.name = name
  749. self.TargetNodeAddress = targetNodeAddress
  750.  
  751. def run(self):
  752. self.logger.info("Starting " + self.name)
  753. self.endtime = datetime.now()+timedelta(minutes=720)
  754. self.logger.info("GC end Time " + str(self.endtime.strftime("%Y%m%d%H%M%S")))
  755. while True:
  756. time.sleep(60)
  757. self.logger.info("GC Started")
  758. self.logger.info("GC current Time " + str(datetime.now().strftime("%Y%m%d%H%M%S")))
  759. if self.endtime < datetime.now():
  760. self.logger.info("SecureTCPTunnel reached 12 hours active window. Killing the process.")
  761. try:
  762. p = subprocess.Popen(["iscsiadm -m node -T "+TargetNodeAddress+" --logout"],
  763. stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,
  764. )
  765. output = p.stdout.read()
  766. err = p.stderr.read()
  767. self.logger.info("Logout Target Output:"+output+".")
  768. self.logger.info("Logout Target Error:"+err)
  769. if "successful." in output:
  770. self.logger.info("Logout Succeeded.")
  771. except Exception as e:
  772. self.logger.warning("Exception raised while creating client thread")
  773. #self.logger.warning("Exception: "+e.message)
  774. self.logger.info("GC Completed")
  775. os._exit(0)
  776.  
  777.  
  778. class ServerThread (threading.Thread):
  779.  
  780. def __init__(self, name, clientsock, serversock):
  781. self.logger = logging.getLogger('ServerThread')
  782. threading.Thread.__init__(self)
  783. self.name = name
  784. self.chunk_size = 131072
  785. self.clientsocket = clientsock
  786. self.serversocket = serversock
  787.  
  788. def run(self):
  789.  
  790. self.logger.info("Starting " + self.name)
  791. try:
  792. while True:
  793. self.logger.info("reading from server")
  794. data = self.serversocket.recv(self.chunk_size)
  795. if data != '':
  796. self.logger.info("sending to client")
  797. sent=self.clientsocket.send(data[:len(data)])
  798. self.logger.info("sent to client (%d)" % (sent) )
  799. elif data == '':
  800. break
  801.  
  802. except socket.error, (value,message):
  803. self.logger.error('socket.error - ' + message)
  804.  
  805. self.logger.info("Disconnected from Server")
  806. self.clientsocket.close()
  807. self.serversocket.close()
  808.  
  809. class ClientThread (threading.Thread):
  810.  
  811. def __init__(self, name, clientsock, ILRTargetInfo):
  812. self.logger = logging.getLogger('ClientThread')
  813. threading.Thread.__init__(self)
  814. self.logger.info("Creating Client Thread for new connection")
  815. self.name = name
  816. self.chunk_size=131072
  817. self.clientsocket=clientsock
  818. TargetPortalAddress, TargetPortalPortNumber,TargetNodeAddress,ScriptId,VMName,LogFolder = ILRTargetInfo
  819. self.logger.info("LogFolder:"+LogFolder)
  820. #self.logger.info("System Version: %s" % (sys.version_info))
  821. if sys.version_info < (2,7,9):
  822. ssocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  823. self.serversocket = ssl.wrap_socket(ssocket)
  824.  
  825. self.serversocket.connect((TargetPortalAddress, TargetPortalPortNumber))
  826. #print "connection succeeded %s %s" % (TargetPortalAddress, TargetPortalPortNumber)
  827.  
  828. #cert = self.serversocket.getpeercert()
  829. #print repr(self.serversocket.getpeername())
  830. #print pprint.pformat(self.serversocket.getpeercert())
  831. #print self.serversocket.cipher()
  832. else:
  833. context = ssl.create_default_context()
  834. context = ssl.SSLContext(ssl. PROTOCOL_TLSv1_2)
  835. context.verify_mode = ssl.CERT_OPTIONAL
  836. context.check_hostname = True
  837. context.load_default_certs()
  838. self.serversocket = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=TargetPortalAddress)
  839.  
  840. self.serversocket.connect((TargetPortalAddress, TargetPortalPortNumber))
  841. self.logger.info("connection succeeded %s %s" % (TargetPortalAddress, TargetPortalPortNumber))
  842. try:
  843. self.logger.info("Handshare in progress")
  844. self.serversocket.do_handshake()
  845. self.logger.info("Handshare done")
  846. except ssl.SSLError, err:
  847. if err.args[0] == ssl.SSL_ERROR_WANT_READ:
  848. select.select([self.serversocket], [], [])
  849. elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
  850. select.select([], [self.serversocket], [])
  851. else:
  852. raise
  853. cert = self.serversocket.getpeercert()
  854.  
  855. self.logger.info("SSL Done %s %s" % (TargetPortalAddress, TargetPortalPortNumber))
  856. self.sthread=ServerThread("ServerThread",self.clientsocket,self.serversocket)
  857. self.sthread.start()
  858.  
  859. def run(self):
  860. self.logger.info("Starting " + self.name)
  861. try:
  862.  
  863. while True:
  864. self.logger.info("Reading from client")
  865. data = self.clientsocket.recv(self.chunk_size)
  866. if data != '':
  867. self.logger.info("sending to server")
  868. sent=self.serversocket.send(data[:len(data)])
  869. self.logger.info("sent to server (%d)" % (sent))
  870. elif data == '':
  871. break
  872.  
  873. except socket.error, (value,message):
  874. self.logger.error('socket.error - ' + message)
  875.  
  876. self.logger.info("Disconnected from client")
  877.  
  878. self.clientsocket.close()
  879. self.serversocket.close()
  880.  
  881. def SecureTCPTunnelMain(args):
  882. OSVersion=sys.argv[1]
  883. LOG_FOLDER=sys.argv[2]
  884. ScriptId=sys.argv[3]
  885. MinPort=int(sys.argv[4])
  886. MaxPort=int(sys.argv[5])
  887. TargetPortalAddress=sys.argv[6]
  888. TargetPortalPortNumber=int(sys.argv[7])
  889. TargetNodeAddress=sys.argv[8]
  890. VMName=sys.argv[9]
  891. LOG_FILENAME = LOG_FOLDER + "/Scripts/SecureTCPTunnelLog.log"
  892. logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s: %(message)s',)
  893. ILRTargetInfo=(TargetPortalAddress, TargetPortalPortNumber,TargetNodeAddress,ScriptId,VMName,LOG_FOLDER)
  894. ilr_config_file = '/etc/MicrosoftAzureBackupILR/mabilr.conf'
  895. port_range = (MinPort, MaxPort) # let the kernel give us a port
  896. server = SecureTCPTunnelServer(port_range, ILRTargetInfo, ilr_config_file)
  897. asyncore.loop()
  898. if __name__ == "__main__":
  899. SecureTCPTunnelMain(sys.argv)
  900. """
  901. script_file_path = os.path.join(script_folder, "SecureTCPTunnel.py")
  902. f = open(script_file_path, "w+")
  903. f.write(SecureTCPTunnelCode)
  904. f.close()
  905. os.chmod(script_file_path, stat.S_IXGRP)
  906.  
  907. def get_osname_for_script(OsName):
  908. lowercase_osname = OsName.lower()
  909. if "ubuntu" in lowercase_osname:
  910. OsName = "Ubuntu"
  911. elif "debian" in lowercase_osname:
  912. OsName = "Debian"
  913. elif "centos" in lowercase_osname:
  914. OsName = "CentOS"
  915. elif "red hat" in lowercase_osname or "rhel" in lowercase_osname:
  916. OsName = "RHEL"
  917. elif "opensuse" in lowercase_osname:
  918. OsName = "OpenSUSE"
  919. elif ("suse" in lowercase_osname and "enterprise" in lowercase_osname) or "sles" in lowercase_osname:
  920. OsName = "SLES"
  921. elif "oracle" in lowercase_osname:
  922. OsName = "Oracle"
  923. return OsName
  924.  
  925. def main(argv):
  926. print "Microsoft Azure VM Backup - File Recovery"
  927. print "______________________________________________"
  928. try:
  929. (Os, Version, VersionName) = platform.linux_distribution()
  930. if Version.count(".") > 1:
  931. Versions = Version.split(".")
  932. Version = Versions[0] + "." + Versions[1]
  933. OsVersion = float(Version)
  934. OsName = get_osname_for_script(Os)
  935. SupportedOSes = ["Ubuntu", "Debian", "CentOS", "RHEL", "SLES", "OpenSUSE", "Oracle"]
  936. OsVersionDict = {"Ubuntu" : 12.04,
  937. "Debian" : 7,
  938. "CentOS" : 6.5,
  939. "RHEL" : 6.7,
  940. "SLES" : 12,
  941. "OpenSUSE" : 42.2,
  942. "Oracle" : 6.4}
  943. if OsName in SupportedOSes:
  944. LowerVersion = OsVersionDict[OsName]
  945. if not is_supported(OsVersion, LowerVersion):
  946. supported_os_msg()
  947. exit()
  948. else:
  949. supported_os_msg()
  950. exit()
  951. except:
  952. print "OsName not recognized if your os is in the list 'Ubuntu', 'Debian', 'CentOS', 'RHEL', 'SLES', 'OpenSUSE', 'Oracle'.\n Please enter OsName as they appear in the list (without changing the case if you os is Ubuntu enter 'Ubuntu') "
  953. response = raw_input("Enter you os name: ")
  954. OsName = response.strip()
  955. if OsName not in ["Ubuntu", "Debian", "CentOS", "RHEL", "SLES", "OpenSUSE", "Oracle"]:
  956. print "Your Os " + OsName + " is not yet supported"
  957. supported_os_msg()
  958. exit()
  959.  
  960. # initialize the parameters required for ILR script to run
  961. MinPort=5365
  962. MaxPort=5396
  963. # set up script directory and set up the logs directory
  964. # volume will be mounted in this directory only
  965. script_directory = os.getcwd()
  966. new_guid = str(time.strftime("%Y%m%d%H%M%S"))
  967. log_folder = script_directory + "/" + MachineName + "-" + new_guid
  968. script_folder = log_folder + "/Scripts"
  969. os.mkdir(log_folder)
  970. os.mkdir(script_folder)
  971. logfilename = script_folder + "/MicrosoftAzureBackupILRLogFile.log"
  972. global logfile
  973. logfile = open(logfilename,'a+')
  974. MABILRConfigFolder="/etc/MicrosoftAzureBackupILR"
  975. install_prereq_packages(OsName)
  976. if not os.path.exists(MABILRConfigFolder):
  977. os.mkdir(MABILRConfigFolder)
  978.  
  979. log("Generating SecureTCPTunnel code")
  980. generate_securetcptunnel_code(script_folder)
  981.  
  982.  
  983. log("Setting ACL to Log and script Folder")
  984. isSetfaclInstalled = is_package_installated("setfacl")
  985. if isSetfaclInstalled:
  986. shell_cmd = 'setfacl --set="user::rwx,group::rwx,other::---" ' + log_folder
  987. run_shell_cmd(shell_cmd)
  988. shell_cmd = 'setfacl --default --set="user::rwx,group::rwx,other::---" ' + log_folder
  989. run_shell_cmd(shell_cmd)
  990. shell_cmd = 'setfacl --set="user::rwx,group::rwx,other::---" ' + script_folder
  991. run_shell_cmd(shell_cmd)
  992. shell_cmd = 'setfacl --default --set="user::rwx,group::rwx,other::---" ' + script_folder
  993. run_shell_cmd(shell_cmd)
  994. else:
  995. shell_cmd = 'chmod -R "ug+rwx" ' + log_folder
  996. run_shell_cmd(shell_cmd)
  997. shell_cmd = 'chmod -R "ug+rwx" ' + script_folder
  998. run_shell_cmd(shell_cmd)
  999. log("Setting ACL succeeded")
  1000. check_for_open_SSL_TLS_v12()
  1001. DoCleanUp = len(argv) > 0 and "clean" in argv
  1002. ilr_params = {
  1003. "MinPort": MinPort,
  1004. "MaxPort": MaxPort,
  1005. "VMName" : VMName,
  1006. "OsNameVersion" : OsName + ";" + Version + ";",
  1007. "MachineName" : MachineName,
  1008. "TargetPortalAddress": TargetPortalAddress,
  1009. "TargetPortalPortNumber": int(TargetPortalPortNumber),
  1010. "TargetNodeAddress": TargetNodeAddress,
  1011. "TargetUserName": TargetUserName,
  1012. "TargetPassword": TargetPassword,
  1013. "InitiatorChapPassword": InitiatorChapPassword,
  1014. "ScriptId": ScriptId,
  1015. "LogFolder": log_folder,
  1016. "SciptFolder": script_folder,
  1017. "DoCleanUp" : DoCleanUp
  1018. }
  1019. ILRMain(ilr_params)
  1020.  
  1021. if __name__ == "__main__":
  1022. if os.getuid() != 0:
  1023. print "Launching the ilrscript as admin"
  1024. python_script_with_args = " ".join(sys.argv)
  1025. os.system("sudo python " + python_script_with_args)
  1026. exit(0)
  1027. else:
  1028. global VMName,MachineName,TargetPortalAddress,TargetPortalPortNumber,TargetNodeAddress,InitiatorChapPassword,ScriptId,TargetUserName,TargetPassword
  1029. VMName="iaasvmcontainerv2;AlfrescoProd-RG;hazrlapalfo01"
  1030. MachineName="hazrlapalfo01"
  1031. TargetPortalAddress="pod01-rec2.eus.backup.windowsazure.com"
  1032. TargetPortalPortNumber="3260"
  1033. TargetNodeAddress="iqn.2016-01.microsoft.azure.backup:9201227995819502386-540730-158331142885912-167402196783478.636825702503883264"
  1034. InitiatorChapPassword="f6c5a81ad91046"
  1035. ScriptId="f86b4bfc-e295-4901-85af-e974799c5b29"
  1036. TargetUserName="9201227995819502386-fee76d1a-6831-4e72-a905-f603362d68bb"
  1037. TargetPassword="UserInput012345"
  1038. main(sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement