I am a sysadmin and have been trying to get more in to coding. I really like using python so far and have been able to do a few cool things. However, one thing I am struggling with is the ability to essentially call a powershell script and read the output (ideally without putting it to a file).
Here are two use cases: 1)
elif choice =="2":
target = raw_input("Enter your target hostname: ")
print "Creating target.ps1 file to establish connection"
pstarget = open("pstarget.ps1", "w")
pstarget.write("$target = New-Pssession " + target + "\n")
pstarget.write("Enter-PSSession $target" + "\n")
pstarget.close()
print "File created. Initiating Connection to remote host..."
os.system("powershell -noexit -ExecutionPolicy Unrestricted secretpath\HealthCheck\pstarget.ps1")
This drops me in a remote powershell session where I can do something like get-host and it will output the hostname of the remote computer.
The main question I have is lets say I was able to run that command as part of the file I created (so it is outputting the response to 'get-host'). How can I bring that back to python? The way things work now is that I am brought in to a powershell session (actually a nested powershell session as it is a powershell session calling a shell on another machine). So yeah, is it possible to have the output of those commands make their way back in to python (maybe I wanted to set that response as a variable?)
The second issue is something like this:
elif choice == "4":
username = raw_input("Unlock AD User (Input username): ")
print "Creating target.ps1 file to unlock AD account"
psunlock = open("unlocktarget.ps1", "w")
psunlock.write("$unlock = Unlock-ADAccount " + username + "\n")
psunlock.close()
print "File created. Unlocking User Account."
os.system("powershell -ExecutionPolicy Unrestricted C:secretpath\Stuff\Code\Python\HealthCheck\unlocktarget.ps1")
print "%s's account has been unlocked. Press enter to continue." % username
raw_input("Press enter to continue...")
os.system("cls")
In this case I'm never explicitly in a powershell session (from the user/UI perspective) but lets say there was an error or output from that command and I wanted to capture it, is it possible to do that?
I'll gladly provide any additional information but I am essentially looking for a way to eventually run things like the Exchange Management Console from a python application which will let me do things like "press (1) to list the top 25 mailboxes by size" Or, eventually, "press (1) to generate a full environment report" which runs a number of powershell commands to get domain/ad/exchange information, as well as parses recent backup files, etc, in order to report on everything from system accessibility, latency, uptime, backup failures, eventlog stuff, recent changes, and output it all as one report.
Thanks!