How to run a powershell script on startup in safe mode as an administrator - powershell

At the company I work for, we use Bit9 as part of our security stack. We are in the process of upgrade the version to 8.0 (and eventually 8.2) on all of our devices. Between the automatic upgrades and a different script I wrote, I was able to upgrade about 1000. But there are still about 700 left where the CLI password from Bit9 is not working, and the devices are not checking in to allow auto upgrade.
Bit9 has come back and suggested the following:
Boot the endpoint into Safe Mode w/ Networking
Run a script that executes the following Administrative commands from a CMD prompt (please note the proper spacing between start= disabled):
sc config parity start= disabled
sc config paritydriver start= disabled
Boot into Normal Mode
I've written a script that is supposed to do all of this, except I cannot for the life of me get the script to run once the device starts in safe mode. I've tried everything that I can think of:
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
Placing a batch file in the Startup folder
Scheduled task
Nothing I do is working.
And one other caveat, the user that is logging in (safe mode & normal mode) is not an administrator. It is a regular user. I am kicking off the initial script with BigFix, which does run as an administrator.
Thanks in advance.

I was finally able to get it to work. The service idea was the starting point, though instead of creating a "fake" service, I actually wrote a service in C# that calls the PS script. I was then able to edit the registry, where I made that service able to start in safe mode. That seemed to do the trick. Now the only issue is that I can't seem to disable safe mode programmatically, but I will ask that as a separate question.

Related

Running Flask at startup as a Service in Windows won't work in background

Before explaining what my problem is, please know that I have looked up for solutions on similar topics but none of them seems to work nor even to corresponds to my problem.
What I am trying to do:
I have this python code on multiple files that I run with flask with the following command:
python -m flask run --host=0.0.0.0
So far, everything works, but I would like this code to automatically run everytime the computer boots. In the future this will be used on mini PCs without any graphical interface nor human intervention.
Since I need to do some configuration checks before running the web server, I've created a powershell script that ends with Flask running (using the previous command).
So far, everything works too. Now we're coming to the problem:
I'd like this script to run when I boot the machine. Specificity: Every things needs to work with Administrator privileges, on the local system without any interaction.
I've tried scheduled tasks but Flask won't run even if the rest of the script works (like creating folders or other things)
Ok, it's not a big deal I have other ways to do it, so I've created a Windows Service in C# to run the Script at startup on the local system.
The script works, I've checked the privileges too, everything's fine but arriving at the flask command line that is supposed to make it run, nothing works.
It's the same thing if I run flask using "pythonw" which is supposed to run python as a background process.
What the problem seems to be:
Well, as long as I run flask and I have either a command prompt or a powershell terminal, everything works greats. But if in a way or another I run the script as a background process, it won't work.
Normally it would take around 30 seconds for Flask to start-up. Here if I try to create a folder right after flask ended starting up (as a test) I can see the folder is created almost instantly, which means the process is immediately killed.
The problem doesn't seem to come from the service itself but really Windows that kills the process I don't know why
I'm running out of idea so if you guys have anything that I could try it would really help me.

How to run a powershell script on Amazon EC2 instance at Startup?

I have to think this is a solved issue but I am just not getting it to work. So I have come to you StackOverflow with this issue:
I have a windows server 2016 machine running in amazon ec2. I have a machine.ps1 script in a config directory.
I create an image of the box. (I have tried with checking noreboot and unchecking it)
When I create a new instance of the image I want it to run machine.ps1 at launch to set the computer name and then set routes and some config settings for the box. The goal is to do this without logging into the box.
I have read and tried:
Running Powershell scripts at Start up
and used this to ensure user data was getting passed in:
EC2 Powershell Launch Tools
I have tried setting up a scheduled task that runs the machine.ps1 on start up (It just hangs)
I see the initializeInstance.ps1 on start up task and have tried to even coop that replacing the line to run userdata with the line to run my script. Nothing.
If I log into the box and run machine.ps1, it will restart the computer and set the computer name and then I need to run it once more to set routes. This works manually. I just need to find a way to do it automagically.
I want to launch these instances from powershell not with launch configurations and auto scale.
You can use User data
Whenever you deploy a new server, workstation or virtual machine there is nearly always a requirement to make final changes to the system before it’s ready for use. Typically this is normally done with a post-deployment script that might be triggered manually on start-up or it might be a final step in a Configuration Manager task sequence or if you using Azure you may use the Custom Script Extension. So how do you achieve similar functionality using EC2 instances in Amazon Web Services (AWS)? If you’ve created your own Amazon Machine Image (AMI) you can set the script to run from the Runonce registry key, but then can be a cumbersome approach particularly if you want to make changes to the script and it’s been embedded into the image. AWS offers a much more dynamic method of injecting a script to run upon start-up through a feature called user data.
Please refer following link for ther same:
Poershell User data
Windows typically won't let a powershell script call another powershell script unless it is being run as Administrator. It is a weird 'safety' feature. But it is perfectly okay to load the ps1 files and use any functions inside them.
The UserData script is typically run as "system". You would THINK that would pass muster. But it fails...
The SOLUTION: Make ALL of your scripts into powershell functions instead.
In your machine.ps1 - wrap the contents with function syntax
function MyDescriptiveName { <original script contents> }
Then in UserData - use the functions like this
# To use a relative path
Set-Location -Path <my location>
# Load script file into process memory
. <full-or-relpath>/machine.ps1
# Call function
MyDescriptiveName <params-if-applicable>
If the function needs to call other functions (aka scripts), you'll need to make those scripts into functions and load the script file into process memory in UserData also.

Microsoft Deployment Toolkit setting SystemAutoLogon registry key when deploying upgraded OS

I'm trying to deploy images via MDT that have been upgraded via the MDT "Standard Client Upgrade" task sequence. My images started as Win10 v1607 images and are updated to v1703 and then captured.
When I go to deploy the captured images, I'll get a popup on first login that c:\LTIBootstrap.vbs can't be found. Digging, I discovered that after the OS is installed and the PC restarts, the MDT task sequence continues running as the SYSTEM account . This is bizarre as it typically runs as the built-in Administrator account.
For some reason, even though the unattend.xml file contains the usual AutoAdminLogon entries, a registry key at
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\SystemAutoLogon
is being created and set to 1 during the deployment. (I discovered this by comparing the registries at the end of deployment.) This key is not present in the captured image. This key does not get created if I deploy an image that is manually updated to v1703 (via Windows Update instead of MDT).
Any ideas on why the unattend.xml could be ignored or what would cause SystemAutoLogon to get created and set?
I figured out what was going on.
The MDT Upgrade task sequence invokes the upgrade with the command line /postoobe option pointing to setupcomplete.cmd. This causes the file to be copied to c:\windows\setup\scripts\setupcomplete.cmd. When windows install is complete, if a file is present at that location, it is run under the SYSTEM account.
The problem is that this file remains even after the upgrade task sequence is totally complete. So if you then capture the image and deploy it to a real machine, it will see setupcomplete.cmd and run it after the deploy, instead of using the usual default Administrator account.
I imagine the presence of this file at c:\windows... is what causes the registry changes mentioned above. setupcomplete.cmd is only built to bootstrap an upgrade back into the MDT task sequence, and needs to be removed from c:\windows... when the task sequence is done running.
Knowing that the post-upgrade portion of the upgrade task-sequence runs as SYSTEM instead of Administrator via a very different mechanism than standard deployment is important, as there are then limits to what you can do. By default the sequence lets you install applications.. they need to be apps that are ok being installed by SYSTEM.
For now I've updated my local SetupComplete.cmd in my scripts directory to delete itself when it is done by changing the last for loop to this (there was also a typo in the for loop before preventing the exit echo):
for %%d in (c d e f g h i j k l m n o p q r s t u v w x y z) do if exist %%d:\Windows\Setup\Scripts\setupcomplete.cmd (
del /q /f %%d:\Windows\Setup\Scripts\setupcomplete.cmd
echo %DATE%-%TIME% Exiting SetupComplete.cmd >> %WINDIR%\Temp\setupcomplete.log)
After thinking about this more and hitting issues due to running as the SYSTEM account, I started playing with avoiding running as the SYSTEM account. (One big problem is that if you want to shutdown at the end of the task sequence right after a reboot occurs, SYSTEM starts running too fast, and the call to shutdown in MDT fails.)
The idea is to instead use SetupComplete.cmd running as SYSTEM to simply bootstrap back into running the task sequence as the default Administrator.
There are a few wrinkles to implementing this. Namely, the synchronous commands that run from unattend.xml during a normal install do not run, so things like enabling admin, disabling uac for admin, disable user account page, disable async run once all have to be invoked manually. Beyond that, it is just a matter of setting the right registry entries by calls to PopulateAutoAdminLogon and SetStartMDT via a step in the task sequence after the OS upgrade is complete, and then performing a restart. This seems to work pretty well. The ideal way to do this would be to have the same script that calls PopulateAutoAdminLogon/SetStartMDT also parse unattend.xml and run those commands.
For some reason shell hiding does not work even though everything is set for it. My best guess is that the task sequence runner is doing this because IsOSUpgrade is set, but am not sure.
With this approach, SetupComplete.cmd is just responsible for a single bootstrap back into the task sequence, and the task sequence can delete it at the same time that it calls a script to do PopulateAutoAdminLogon/SetStartMDT
There is enough work to be done to fully polish this approach that I'll just workaround the one autologin issue for now, but it really does feel like a better way for MDT to work when doing upgrades. Hopefully they'll flesh it out in the future.

Unable to start service in window 10 by using NSSM

I have create a small script file to test.
This my script.bat file.
sc create myService binpath= C:\Users\Admin\Desktop\test.bat start= auto
This is my test.bat file.
echo "Welcome to Wizard"
Problem Statement
I am unable to start the service from control panel Service section.
I get following error.
[SC] StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.
That is why I am using nssm.
NOW what happening is that when I run following command on powershell
.\nssm install myService, I dialogue box appears. I give it the path of my script file and click on install service.
After successfull installation of service. I go to control panel -> Service -> click on start against myService but it get paused and following dialog box appears
How can I fix this?
Is there anyother way to do it without doing manual steps and not using third party tool.
I am doing all this on window 10. Do I need any server to perform this task?
NOTE: I cannot use Always up or window scheduler in my case.
The NSSM behaviour is caused by the script terminating almost instantly. Try the following script:
echo Hello World
pause
This should allow the service to start, but you will not necessarily see a console window. Even if you tick 'allow service to interact with desktop', it will not be your desktop that it interacts with!
Windows implements 'session zero isolation' as a security feature, and this essentially prevents services interacting with end user desktops.
In terms of a solution, it's possible to write Windows 'service' applications fairly simply using Visual Studio. It's outside my area of expertise, but based on the Windows applications I'm familiar with, you would generally have a user-mode application running to provide desktop interaction. The user-mode application can interact with services hosted by the service application.
Probably this is resolved by now, but in case it helps anyone, what saved the day for me was checking again my input in the arguments field in nssm. I had an extra "-" which created the error. To edit my service, I went via nssm edit <servicename>
I would also add on the fix that worked for me. I added "" (quotes) in the argument path and that solved the issue for me.

iot-core custom oem image/ffu: crashing only in custom oem/ffu image. Bottom line: looking for a unique board ID

We have an iot-core UWP, headless app that runs fine (for months, hundreds of devices) when deployed directly from Visual Studio 2015 or as an App onto the retail iot-core distribution. In order to avoid over-air-update problems caused by recent automatic iot-core updates, we are trying to get a custom oem image/ffu built and deployed to the microsoft store. However, even after walking through the documentation/examples in detail, our app is still crashing when we deploy our oem image/ffu.
UPDATE
OK, no debugger still, but I found where it crashes, now is the question why the oem-ffu behaves differently from the side-deployed code (our code is identical) Since iot-core/UWP provices no way to get the board-UUID, I use the MAC of the primary network interface. To get this, I use this http://embedded101.com/BruceEitman/entryid/676/Windows-10-IoT-Core-Getting-the-MAC-Address-from-Raspberry-Pi which requires that a webserver be running, which it normally is, otherwise the console webapp would not work. However, on the OEM-Custom-Build-Version I get a crash in this routine. I don't know where since I can't debug, but it crashes, and I get a null back, which causes my azure storage connect to crash. I do not block processing since I have a retry loop... Anyway, what is the difference or what must we do to enable this code to also work in the OEM build?
The grass roots issue is: all I really need is a unique ID for the RPi board from somewhere... which does not seem possible via C#!? See How to get the processor serial number of Raspberry PI 2 with Windows IOT
So it looks like my MAC-Address solution above was the best we can expect at the moment, but doesn't work on the oem build. Why?
If your purpose is to avoid problem with auto update, you can use powershell script or putty to disable auto-update. Will that work for you?
Below is the command line you can use to disable auto-update,
Use powershell or putty to connect to pi using administrator
sc.exe config wuauserv start=disabled
sc.exe query wuauserv
sc.exe stop wuauserv
sc.exe query wuauserv
REG.exe QUERY HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\wuauserv /v Start