Python Forum

Full Version: unable to pass a input after changing the user from root to non root using python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In my automation using python am triggering a shell script which takes care of prerequisites to my software installations. Prerequisites am running using Root user and after that am changing the user using command SU. till here its working perfectly after changing the user inputs are not getting passed to my shell script from python. can you suggest me any way. thanks alot in advance
say again?
Example code would be nice.
import pexpect,time,re,sys,time,shutil,os,glob,sessionClass,subprocess
import sConstants as const
import Logger
import zipfile
import CommandRunner
import commands


prompt = const.gLNXPrompt
dpkFolder = const.gLocalFolder

def unzipBootStrap():
	import sConstants as const
	import DPKCopy
	os.chdir(dpkFolder)
	bootStrapFile = "HCM-920-C596-R1-LNX_1of11.zip"
	#zipfd = zipfile.ZipFile(bootStrapFile,'r') as z:
	with zipfile.ZipFile(bootStrapFile,'r') as z:
		z.extractall(dpkFolder)
	subprocess.call('chmod -R 755 '+dpkFolder,shell=True)
		
def doCleanup():
	import sConstants as const
	import sys
	"""
	This function cleans up existing installation.
	It first checks for any existing installation and then proceeds for cleanup. Once cleanup is successful, it goes ahead and removes the extracted folders.
	"""
	setupExists = os.path.exists(dpkFolder+"/setup")
	if setupExists == True:
		logger.writeLog("Bootstrap extracted folder exists, proceeding for cleanup")		
		session = sessionClass.sessionManager(logfile=const.gHomeDir+'/ServerCleanup.log')
		child = session.getChild()
		cr = CommandRunner.CommandRunner(child)
		try:
			cr.runCommand('cd '+dpkFolder+"/setup")
			cr.expectString(prompt)
			cr.runCommand('./psft-dpk-setup.sh --cleanup')
			cr.expectString(prompt,timeOut=1800)
			cleanupStatus = checkStringInLog(cr.getBeforeValue(),"The cleanup of PeopleSoft environment is successful.")
			if cleanupStatus == True:
				logger.writeLog("Clean-up is successful")
			else:
				logger.writeLog("Clean-up failed")
				cr.getBeforeValue()
				sys.exit(1)
		finally:
			cr.closeChild()
		
	else:
		logger.writeLog("Setup doesn't exist. No clean-up performed")

def checkIfBootstrapSuccess():
	import sConstants as const
	logger = Logger.Logger()
	logger.writeLog("Checking log for bootstrap status")
	if const.gModeOfOperation == "full-tier":
		if checkStringInLog(const.gHomeDir+'/setup.log',"The initialization of PeopleSoft TOOLS fulltier environment is successful") == True:
			logger.writeLog("Full tier installation successful")
			return True
	elif const.gModeOfOperation == "mid-tier":
		if checkStringInLog(const.gHomeDir+'/setup.log',"The initialization of PeopleSoft TOOLS midtier environment is successful.") == True:
			logger.writeLog("Mid tier installation successful")
			return True
	elif const.gModeOfOperation == "db-tier":
		if checkStringInLog(const.gHomeDir+'/setup.log',"The initialization of PeopleSoft TOOLS dbtier environment is successful.") == True:
			logger.writeLog("DB tier installation successful")
			return True
	logger.writeLog("None of the tools installation success messages matched. Validation failed !")
	return False

def runPsftDpkSetup():
	import sConstants as const
	os.chdir(dpkFolder+"/setup")
	"""if machineType == "VBOX":
		vboxChanges(child)
	
	child.sendline("cd "+dpkFolder)
	child.expect(prompt)
	print "Unzipping bootstrap"
	child.sendline("unzip BOOTSTRAP*.zip")
	child.expect(prompt)
	os.chdir(dpkFolder+"/setup")
	print "Transferring control to setupChild, check setup.log"
	"""
	if const.gModeOfOperation == "full-tier":
		print "Executing full tier"
		session = sessionClass.sessionManager(logfile=const.gHomeDir+'/setup.log')
		child = session.getChild()
		cr = CommandRunner.CommandRunner(child)
		os.system('su avikanch1 -c /opt/oracle/psft/dpk/setup/psft-dpk-setup.sh')
		subprocess.call(['chmod', '-R', '777', '/opt/oracle/psft/dpk/setup'])
		#setupCmd = 'su avikanch1 -c /opt/oracle/psft/dpk/setup/psft-dpk-setup.sh' #"sh psft-dpk-setup.sh --prereq --syscfg"
		cr.expectString(prompt,timeOut=300)
		
		
	elif const.gModeOfOperation == "db-tier":
		print "Executing db tier"
		setupCmd = "sh psft-dpk-setup.sh --env_type dbtier"
	elif const.gModeOfOperation == "mid-tier":
		print "Executing mid tier"
		setupCmd = "sh psft-dpk-setup.sh --env_type midtier"
	else:
		print "Invalid mode of operation, exiting...!!!"
		sys.exit(0)
	#print setupCmd
	setupChild = sessionClass.sessionManager(setupCmd,const.gHomeDir+'/setup.log').getChild()
	print "Started the setup...."
	#i = setupChild.expect([pexpect.TIMEOUT,".*Do you want to proceed with the Puppet Installation? \[Y|n]\:.*"],500)
	#i = setupChild.expect([pexpect.TIMEOUT,".*Do you want to proceed with the Puppet 5.3.5 Installation? \[Y|n]\:.*"],500)
	#print "checkingi value" ,i
	#if i == 0:
		#print "Puppet already installed, skipping timeout"
		#pass
	#elif i == 1:
		#setupChild.sendline("Y")
	#print "executing prereq.sh"
	#os.chdir("/scratch/scripts/")
	#print "/scratch/scripts/"
	#subprocess.call("./Prereq.sh")
	#print "/scratch/scripts Prereq.sh/"
		#dpkFolder = const.gLocalFolder
		#subprocess.call("chmod -R 777 /opt/orcle/psft/dpk/setup")
		#subprocess.call(['chmod', '-R', '777', '/opt/oracle/psft/dpk/setup'])
		#os.system('su ***** -c /opt/oracle/psft/dpk/setup/psft-dpk-setup.sh')
		#os.system("su ***")
		#subprocess.call('ls > /tmp/ls.log')
		#print "user changed"
		#os.chdir("/opt/oracle/psft/dpk/setup")
		#subprocess.call("./psft-dpk-setup.sh")
		
		#try:
			#fo = open("/scratch/scripts/userdetails","r")
			#for line in fo:
				#line=line.strip()
				#user_d=line.split(',', 1)	
				#user=user_d[0]
				#if const.gModeOfOperation == "full-tier":
					#print "Executing full tier"
					#os.system('su "+user+" -c "sh psft-dpk-setup.sh" ') ###till here its working
		#except IOError as error:
			#print (error, "could not read userdetails")
			#sys.exit()
	if const.gMachineType == "LINUX":
                setupChild.expect([pexpect.TIMEOUT,".*Would you like to proceed with the setup as a non-root user? \[y/n]\:.*"],timeout=100)###From here its not working as expected
	        setupChild.sendline("Y")
	        setupChild.expect([pexpect.TIMEOUT,".*Enter the PeopleSoft Base Directory:.*"],timeout=300)
	        setupChild.sendline(const.gNonrootInstallDir)
	        setupChild.expect([pexpect.TIMEOUT,".*Are you happy with your answer? \[Y|n|q]\:*"])
	        setupChild.sendline("y")
	        setupChild.expect([pexpect.TIMEOUT,".*Enter a writable ps_config_home directory for PeopleSoft domains with at least 10.0GB space \[/scratch/home/avikanch1/psft/pt/8.57]\:.*"])
	        setupChild.sendline(const.gCfgHome)
		#i = setupChild.expect([pexpect.TIMEOUT,".*Enter a directory on the Linux VM that is writable \[/home]\:.*"])
		#if i == 0:
			#print "/home directory is writeable, skipping timeout"
			#pass
		#elif i == 1:
			#if not os.path.exists(const.gUsersHomeDir):
				#os.makedirs(const.gUsersHomeDir)
				#setupChild.sendline(const.gUsersHomeDir)
				#setupChild.expect([pexpect.TIMEOUT,".*Are you happy with your answer? \[Y|n|q]\:*"])
				#setupChild.sendline("y")
	print "Waiting for extraction to complete"

	if const.gModeOfOperation == "mid-tier":
		setupChild.expect("Enter the database platform*",timeout=1200)
		setupChild.sendline(const.gMtDbType)
		setupChild.expect("Enter the name of the database:*")
		setupChild.sendline(const.gDbName)
		setupChild.expect("Enter the service name of the database*")
		setupChild.sendline(const.gDbName)
		setupChild.expect("Enter the hostname for the database server:*")
		setupChild.sendline(const.gMtDbHostName)
		setupChild.expect("Enter the port number for the database server*")
		setupChild.sendline(const.gMtDbPortNum)
		setupChild.expect("Enter the Domain Boot user*")
		setupChild.sendline(const.gMtDomainBootUser)
		setupChild.expect("Enter the Domain Boot user password:*")
		setupChild.sendline(const.gMtDomainBootPwd)
		setupChild.expect("Re-Enter the Domain Boot user password:*")
		setupChild.sendline(const.gMtDomainBootPwd)

	if const.gModeOfOperation == "full-tier" or const.gModeOfOperation == "db-tier":
		setupChild.expect("Enter the PeopleSoft installation \[PUM or FRESH]\ type \[PUM]\.*",timeout=1200)
		setupChild.sendline(const.gInstallationType)
		setupChild.expect(".*Enter a new PeopleSoft database name.*",timeout=100)
		setupChild.sendline(const.gDbName)
		setupChild.expect(".*Enter the PeopleSoft database listener port \[1521]\:.*",timeout=100)
		setupChild.sendline(const.gPort)
		setupChild.expect(".*Enter a new PeopleSoft database admin users \[SYS/SYSTEM]\ password.*",timeout=100)
		setupChild.sendline(const.gAdminUser)
		setupChild.expect(".*Re-Enter the database admin users password:.*",timeout=50)
		setupChild.sendline(const.gAdminUser)
		setupChild.expect(".*Enter a new PeopleSoft database Connect ID.*",timeout=120)
		setupChild.sendline(const.gConnectId)
		setupChild.expect(".*Enter a new PeopleSoft database Connect ID \[people]\ password.*",timeout=120)
		setupChild.sendline(const.gConnectPwd)
		setupChild.expect("Re-Enter the PeopleSoft Connect ID password:.*")
		setupChild.sendline(const.gConnectPwd)
	
	if const.gModeOfOperation == 'db-tier':
		setupChild.expect("Enter the port number for the database server*",timeout=1200)
		setupChild.sendline(const.gDBPortNo)
		
	if const.gModeOfOperation == 'full-tier' or const.gModeOfOperation == 'mid-tier':
		setupChild.expect(".*Enter a new PeopleSoft database Access ID \[SYSADM]\ password.*",timeout=120)
		setupChild.sendline(const.gDbAccessPwd)
		setupChild.expect(".*Re-Enter the PeopleSoft Access ID password:.*",timeout=120)
		setupChild.sendline(const.gDbAccessPwd)
		if const.gOperatorIdPwd == 'VP1':
			setupChild.expect(".*Enter a new PeopleSoft database Operator ID \[VP1]\ password.*",timeout=120)
			setupChild.sendline(const.gOperatorIdPwd)
		else:
			setupChild.expect(".*Enter a new PeopleSoft database Operator ID \[PS]\ password.*",timeout=120)
			setupChild.sendline(const.gOperatorIdPwd)
		#setupChild.expect(".*Enter a new PeopleSoft database Operator ID \[PS]\ password.*",timeout=120)
		#setupChild.sendline(const.gOperatorIdPwd)
		setupChild.expect(".*Re-Enter the PeopleSoft Operator ID password:.*",timeout=120)
		setupChild.sendline(const.gOperatorIdPwd)
		setupChild.expect(".*\[Optional]\ Enter a new Application Server Domain connection password.*")
		setupChild.sendline(const.gAppPassword)
		setupChild.expect("Re-Enter the Application Server Domain connection password:.*")
		setupChild.sendline(const.gAppPassword)
		setupChild.expect("Enter a new WebLogic Server Admin user \[system]\ password.*",timeout=120)
		setupChild.sendline(const.gWebPassword)
		setupChild.expect("Re-Enter the WebLogic Server Admin user password:.*")
		setupChild.sendline(const.gWebPassword)
		setupChild.expect("Enter a new PeopleSoft WebProfile user \[PTWEBSERVER]\ password.*",timeout=120)
		setupChild.sendline(const.gWebProfile)
		setupChild.expect("Re-Enter the PeopleSoft WebProfile user password:.*",timeout=120)
		setupChild.sendline(const.gWebProfile)
		setupChild.expect("Enter the PeopleSoft Integration Gateway user \[administrator]\:.*",timeout=120)
		setupChild.sendline(const.gIBUserId)
		setupChild.expect("Enter the PeopleSoft Integration Gateway user \[administrator]\ password.*",timeout=60)
		setupChild.sendline(const.gIntegration)
		setupChild.expect("Re-Enter the PeopleSoft Integration Gateway user password:.*",timeout=120)
		setupChild.sendline(const.gIntegration)
		setupChild.expect("Are you happy with your answers? \[y|n]\:.*",timeout=300)
		setupChild.sendline("y")
		setupChild.expect("Do you want to continue with the default initialization process? \[y|n]\:.*",timeout=300)
		setupChild.sendline("y")
		print "Initialization in progress"
		setupChild.expect(pexpect.EOF,timeout=3600)
		print "installation finished - now check logs!!!"

		checkIfBootstrapSuccess()

	if const.gModeOfOperation == "mid-tier":
		setupChild.expect("Enter the Web Profile user PTWEBSERVER password:*")
		setupChild.sendline(const.gPTWEBSERVERPwd)
		setupChild.expect("Re-Enter the Web Profile user PTWEBSERVER password:*")
		setupChild.sendline(const.gPTWEBSERVERPwd)
		setupChild.expect("Enter the Integration Gateway user Id*")
		setupChild.sendline(const.gIBUserId)
		setupChild.expect("Enter the Integration Gateway user password:*")
		setupChild.sendline(const.gIBPwd)
		setupChild.expect("Re-Enter the Integration Gateway user password:*")
		setupChild.sendline(const.gIBPwd)
	if const.gMachineType != "VBOX" and const.gModeOfOperation != 'db-tier':
		setupChild.expect("Do you wish to configure SES on this VM.*")
		setupChild.sendline("N")
	setupChild.expect("Are you happy with your answers.*")
	setupChild.sendline("y")
	setupChild.expect("Do you want to continue with the default initialization process.*")
	setupChild.sendline("y")
	print "Initialization in progress"
	setupChild.expect(pexpect.EOF,timeout=3600)
	print "installation finished - now check logs!!!"
	
	checkIfBootstrapSuccess()
	        #setupChild.sendline(const.gNonrootCFGDir)
		#setupChild.sendline("y")
		#child.expect(prompt,timeout=2000)
def vboxChanges(child):
	import sConstants as const
	child.sendline('umount /media/sf_X_DRIVE')
	child.expect(prompt)
	child.sendline('cp /media/sf_DPKs/BOOTSTRAP*.zip '+dpkFolder)
	child.expect(prompt,timeout=1200)

		
def removeSetupFolders():
	import sConstants as const
	print "Removing setup folder, readme.txt and zip files"
	if os.path.exists(dpkFolder+"/setup"):
		shutil.rmtree(dpkFolder+"/setup")
	if os.path.exists(dpkFolder+"/migration"):
		shutil.rmtree(dpkFolder+"/migration")
	if os.path.isfile(dpkFolder+"/readme.txt"):
		os.remove(dpkFolder+"/readme.txt")
	if const.gMachineType == "VBOX":
		os.chdir(dpkFolder)
		zipFiles = glob.glob('*.zip')
		for file in zipFiles:
			print "Removing the file: "+file
			os.remove(file)


def splitOutput(output):
	import sConstants as const
	file = open('output.log','a')
	listOutput = output.split('\n')
	file.writelines(listOutput)
	file.writelines("\n")
	file.close()
	
def checkStringInLog(log,checkString):
	logList = []
	available = False
	if os.path.isfile(log):
		print "Log file supplied: "+log
		file = open(log,'rb')
		for lines in file.readlines():
			if checkString in lines:
				available = True
		file.close()
	else:
		print "non file log supplied"
		if checkString in log:
			available = True
	return available
	
def checkIfFolderExists(folderName):
	if os.path.exists(folderName):
		return True
	else:
		return False
		
def runBootStrap():
	import sConstants as const
	unzipBootStrap()
	runPsftDpkSetup()
	if not checkIfBootstrapSuccess():
		print "Bootstrap failed. exiting"
		sys.exit(1)
	testForClients()

def testForClients():
	import sConstants as const
	logger.writeLog("VALIDATION for client folders started")
	clientFolder = const.gInstallDir+"/pt/tools_client"
	
	if const.gModeOfOperation == 'full-tier' or const.gModeOfOperation == 'mid-tier':
		if not checkIfExists(clientFolder+"/client-855"):
			logger.writeLog("VALIDATION FAILED: The client folder : "+clientFolder+"/client-855 doesn't exist in the location")
		else:
			logger.writeLog("VALIDATION SUCCESS: The client folder: "+clientFolder+"/client-855 exists in the location")
	
	if const.gModeOfOperation == 'full-tier':
		if not checkIfExists(clientFolder+"/client-854"):
			logger.writeLog("VALIDATION FAILED: The client folder: "+clientFolder+"/client-854 doesn't exist in the location")
		else:
			logger.writeLog("VALIDATION SUCCESS: The client folder: "+clientFolder+"/client-854 exists in the location")
		
		if not checkIfExists(clientFolder+"/client-853"):
			logger.writeLog("VALIDATION FAILED: The client folder: "+clientFolder+"/client-853 doesn't exist in the location")
		else:
			logger.writeLog("VALIDATION SUCCESS: The client folder: "+clientFolder+"/client-853 exists in the location")
		
		if not checkIfExists(clientFolder+"/readme.txt"):
			logger.writeLog("VALIDATION FAILED: The readme file is not available in the location: "+clientFolder+"/readme.txt")
		else:
			logger.writeLog("VALIDATION SUCCESS: The readme file is available in the location: "+clientFolder+"/readme.txt")
		
		if not checkfIfExists(clientFolder+"/SetupPTClient.bat"):
			logger.writeLog("VALIDATION FAILED: The setup client bat file is not available in the location: "+clientFolder+"/SetupPTClient.bat")
		else:
			logger.writeLog("VALIDATION SUCCESS: The setup client bat file is available in the location: "+clientFolder+"/SetupPTClient.bat")
		
		
def checkIfExists(objName):
	if os.path.exists(objName):
		return True
	else:
		return False