Skip to content

Instantly share code, notes, and snippets.

@nilaydshah
Last active July 12, 2019 07:59
Show Gist options
  • Save nilaydshah/1c45eb79915121341aa951c85819bc3a to your computer and use it in GitHub Desktop.
Save nilaydshah/1c45eb79915121341aa951c85819bc3a to your computer and use it in GitHub Desktop.
ASE Pre-Registration Script
import argparse
import sys
import grp
import pwd
import subprocess
import os
import json
class PreRegistration:
def __init__(self, args = None):
self.args = args
self.osGroup = 'msawb'
self.homePath = '/opt/msawb'
self.tmpDirPath = '{0}/tmp'.format(self.homePath)
self.configDirectory = '{0}/etc/config/SAPAse'.format(self.homePath)
self.configFile = '{0}/config.json'.format(self.configDirectory)
self.getDbPasswordFile = '{0}/GetDbPassword.sh'.format(self.configDirectory)
self.sidUser = ''
self.sid = ''
self.dbPort = 4901
self.dbUser = 'sapsa'
self.dbPasswordUtil = ''
def run(self):
self.ShowBanner()
self.GetUserInputs()
print("+ Setting up OS users and groups")
self.CreateOSGroup(self.osGroup)
self.AddUserToGroup(self.sidUser, self.osGroup)
print("+ Setting up directories and permissions")
self.CreateDirectory(self.configDirectory)
self.ChangeOwner(self.homePath, 'root', self.osGroup)
self.CreateDirectory(self.tmpDirPath)
self.ChangeOwner(self.tmpDirPath, 'root', self.osGroup)
self.ChangeMod(self.tmpDirPath, 0o777)
print("+ Creating GetDbPassword script file".format(self.getDbPasswordFile))
self.CreateFile(self.getDbPasswordFile)
print("+ Setting up permissions for GetDbPassword script file")
self.ChangeOwner(self.getDbPasswordFile, 'root', self.osGroup)
self.ChangeMod(self.getDbPasswordFile, 0o650) # Not a type. Its 650 in Octal : 0o650
print("+ Creating config file".format(self.configFile))
self.CreateFile(self.configFile)
print("+ Setting up permissions for config file")
self.ChangeOwner(self.configFile, 'root', self.osGroup)
self.ChangeMod(self.configFile, 0o640) # Not a type. Its 640 in Octal : 0o640
print("+ Setting up initial configurations")
self.SetupInitialConfigurationSettings()
print("\n** The necessary stuffs are configured. Please return to Azure portal/PS/CLI to now select the backup policy and enable protection for these SAP ASE DBs **\n")
"""
Display a banner
"""
def ShowBanner(self):
print (3 * "\n")
print (57 * '-')
print (" A Z U R E - B A C K U P R E G I S T R A T I O N")
print (57 * '-')
print("\n** This script is used to configure necessary permissions for Azure Backup to be able to backup and restore SAP ASE DBs within this SAP system. ** \n")
"""
See if all input params are set through command line. If anything param is missing ask user for input
"""
def GetUserInputs(self):
try: input = raw_input
except NameError: pass
if self.args.sid:
self.sid = self.args.sid
else:
self.sid = input("\n Enter the instance name of the ASE System: ")
if not self.sid:
raise Exception("No value received. Aborting.")
self.sidUser = input("\n Enter OS Username under which ASE System runs (e.g. syb<sid>): ")
if not self.sidUser:
raise Exception("No value received. Aborting.")
self.dbHostName = input("\n Enter the Hostname of the ASE System (e.g. localhost): ")
if not self.dbHostName:
raise Exception("No value received. Aborting.")
self.dbUser = input("\n Enter the ASE Database Username to be used for ODBC Connection (e.g. sapsa): ")
if not self.dbUser:
raise Exception("No value received. Aborting.")
self.dbPort = input("\n Enter the Port Number of the ASE Database System (e.g. 4901): ")
if not self.dbPort:
raise Exception("No value received. Aborting.")
self.dbPasswordUtil = input("\n Enter dpsp utility command to retrieve ASE Database Password: ")
if not self.dbPasswordUtil:
raise Exception("No value received. Aborting.")
print (2 * "\n")
"""
Helper method to create an OS group. Skips creation if group already exists.
"""
def CreateOSGroup(self, groupName):
try:
# Check if group exists
grp.getgrnam(groupName)
except KeyError:
# Group doesn't exists. Creating group
subprocess.check_call(["/usr/sbin/groupadd", groupName])
"""
Helper method to add any OS user to any OS group
"""
def AddUserToGroup(self, userName, groupName):
try:
pwd.getpwnam(userName)
except KeyError:
raise Exception("\n User {0} doesn't exists.".format(userName))
subprocess.check_call(["/usr/sbin/usermod", "-a", "-G", groupName, userName])
"""
Helper method to chown any file/directory
"""
def ChangeOwner(self, path, userName, groupName):
os.chown(path, pwd.getpwnam(userName).pw_uid, grp.getgrnam(groupName).gr_gid)
"""
Helper method to create a directory if not exists
"""
def CreateDirectory(self, directoryPath):
if os.path.exists(directoryPath) and os.path.isdir(directoryPath):
pass
else:
os.makedirs(directoryPath)
"""
Helper method to create a file if not exists
"""
def CreateFile(self, filePath):
if os.path.exists(filePath) and os.path.isfile(filePath):
pass
else:
open(filePath, 'a').close()
"""
Helper method to chmod any file/directory
"""
def ChangeMod(self, path, permMask):
os.chmod(path, permMask)
"""
Helper method to configure config file with config object and initial values.
"""
def SetupInitialConfigurationSettings(self):
config = [{
"LogicalContainerId": self.sid,
"LogicalContainerOSUser": self.sidUser,
"PropertyBag": dict(dbHostName= self.dbHostName, dbPort = self.dbPort, dbUser = self.dbUser, dbPasswordUtil = 'sh ' + self.getDbPasswordFile)
}]
with open(self.configFile, "w") as f:
f.write(json.dumps(config, indent = 4, sort_keys = True))
with open(self.getDbPasswordFile, "w") as f:
f.write('#!/bin/bash\nsource ~/SYBASE.sh && unset LANG && ' + self.dbPasswordUtil)
if __name__ == '__main__':
if os.getuid() != 0:
print("This script requires admin rights. Please execute this script as root or with sudo.")
sys.exit(1)
parser = argparse.ArgumentParser(description='Configure a machine for running Azure Backup')
# parser.add_argument('-u', dest='unattend', help='Run the script in unattend mode', action='store_true', default=False)
parser.add_argument('--sid', help='The instance name of the ASE System')
PreRegistration(parser.parse_args()).run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment