Batch file editing Hosts file - no effect? - batch-file

I made a small batch file to edit the hosts file:
#echo off
title Edit Hosts
color 0A
echo Warning: Please ensure you are running this program as an administrator.
set /p admin=Type Y or N and hit enter to continue.
echo.
IF '%admin%'=='Y' goto :edithosts
IF '%admin%'=='N' exit
:edithosts
cls
set /p block=Enter website to block:
echo 127.0.0.1 %block% > C:\WINDOWS\system32\drivers\etc\hosts
pause
The file does its job and adds whatever the user types in to the hosts file in the format
127.0.0.1 website
I checked to see if the websites were listed, and the hosts file is updating correctly. However, my browser can still connect. Is this somehow due to a cached copy of the site, or is there a flaw in the code?

While changes to the hosts file are immediate on Windows for quite a while, applications may or may not be affected immediately by it. Web browsers in particular will usually cache DNS lookups to save time for further requests. This cache is most easily cleared by simply restarting the browser. After you have done that, and the DNS lookup happens, it should pick up your modified IP instead.

Newer versions of windows have default setting in Windows Defender to protect the hosts file. If you are on W8 or higher, you may also need to open Defender and add the hosts file to your exclusion list.
It's on the settings tab, click Excluded Files and Locations. Disregard red arrow, re-purposed an image from bing.

Related

Enabling RDP by changing registry setting only works if RDP has been enabled several times previously

I'm trying to build an auto config batch file to set up new PC's the way I need them configured. One of the things I need to do is to enable RDP.
I have found this post which gives a solution involving changing a registry key:
reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
Many other posts and blogs give the same advice.
However, when I test this on my system, it only works if remote desktop has been enabled before, several times.
If I use the standard settings interface to enable RDP, I get an "enable remote desktop" popup, asking me to confirm that I want to allow RDP. I select yes, and the registry setting changes. I use the settings interface to turn RDP back off, I get another popup to confirm, I click yes, and the registry setting changes back.
However, it does not work the other way around - changing the registry setting does not affect the slider in the standard settings interface. Setting the registry key to zero does not enable RDP. I have checked that the firewall is configured to allow RDP, and that the relevant RDP services are all started. As soon as I turn the settings RDP slider on, I can RDP into the machine. Once I turn it off, even if I change the registry setting back and make sure all services/firewall settings are OK, I can't RDP in any more.
However, if I mess with the Enable RDP settings slider enough, eventually it stops showing the confirmation popup and just does it. At this point, changing that registry key has the desired effect - changing the registry key changes the position of the settings slider, and allows me to RDP into the machine as expected.
Obviously this makes my batch file ineffective on new PC's, which is it's whole purpose.
How can I overcome this?
Windows 10 Enterprise LTSC Version 1809
(edited to clarify some points)
The following powershell script works for me:
set-itemproperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name "fDenyTSConnections" -Value 0
set-itemproperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-TCP\' -Name "UserAuthentication" -Value 1
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
I see the same process described here with an explanation of what each item does.
So perhaps your problem is not running one of those steps, but its also unclear if you are testing RDP empirically after running your script or just looking at the UI - which may still be displaying a cached RDP status.
I think the batch file equivalent would be:
reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
reg add "HKLM\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-TCP" /v UserAuthentication /t REG_DWORD /d 0x00000001 /f
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
But using powershell is likely to be more future proof.
May i suggest using powershell to do so (u can run powershell from CMD/Batch if neede to work only with batch).
Follow this article.
P.S
Pay attention, they suggest its for remote(if winrm is active), but can be executed locally

My bat file can't run correctly, why?

Create a new file test.bat, the content is as follows:
echo aa;
and execute it in the dos command line,
test.bat
there are no output in the window. But when I tested it in another computer, it outputs
aa
When I double click the bat file, it always disappeared suddenly even I add a "pause" clause line in the test.bat file. Both the systems are Window XP. Can sb tell me where is the problem, please?
I have checked all the things Mofi suggested, but the problem remains.
Now, I divscover when reboot to the system using another Administrator account. All is fine.
So, whether the problem comes from the registry record of the Windows XP?
See my answer on Iterating over files in directory prepends extra character to filename where I have already explained what to check if batch files are not working as expected.
The environment variables ComSpec, PATHEXT and PATH should be verified by you first. And check also the values of registry key Command Processor as explained in referenced answer. Also Autorun value of key Command Processor is very critical.
Further, start Regedit and check standard value of registry key HKEY_CLASSES_ROOT\.bat displayed on right side. It should be batfile. Then go to HKEY_CLASSES_ROOT\batfile, open it and navigate to subkey open - command. The standard value is "%1" %*. It could be that your Windows registry is partly corrupt which makes it not possible to run a batch file by double click.
A check for a problem with registry would be opening a command prompt window by running
C:\Windows\System32\cmd.exe
via Run entry in start menu of Windows. Then run your batch file from within the command prompt window.
You should also run from a command prompt window
C:\Windows\System32\chkdsk.exe C: /F
and confirm running the check disk tool of Windows on next boot of Windows. Then restart Windows to let this tool check the file system for errors resulting in 1 or more corrupt files. If an error was really detected in file system, run after Windows finished starting from a command prompt window
C:\Windows\System32\chkdsk.exe C: /F /R
Confirm running this tool once again on next boot of Windows, but this time with read/write tests on all sectors of your hard disk and repairing sectors if that is possible at all. It can take several hours depending on size of drive C: to finish this task.
Added on 2014-09-28:
Anti-virus application
Do you have checked already the configuration of the anti-virus application?
It could be that it blocks the execution of all *.bat files.
Windows System Restore
Do you have already tried to use Windows System Restore for the account on which batch file execution fails and go back to a restore point of a date on which you are sure that batch file execution worked?
If ntuser.dat or ntuser.dat.log (= registry of current user) is partly corrupt or something is misconfigured in Windows registry for this user account, this would be the easiest method to get back a working environment for the account.
Process Monitor Analysis
As execution of batch files does not work only with one account, the reason must be a corrupt or wrong set key or value in registry of this account.
I suggest to download and run free tool Process Monitor from Sysinternals (Microsoft) using first the account on which batch file execution does not work as expected.
The first displayed on start of this tool is a dialog to configure a filter. Select from first list Process Name, let is selected on second list, enter cmd.exe in edit field, and let Include selected in last list. Click next on button Include and then on OK.
Now in main application window of Process Monitor click on last 3 symbols in toolbar to toggle off those features resulting in monitoring only registry and file system accesses. Clear current list by clicking on fifth symbol in toolbar or by pressing Ctrl+X.
Now double click on your sample batch file in Windows Explorer. Then switch batck to Process Monitor, scroll up to beginning and look line by line what happens on executing of a batch file. Perhaps you can see something which you think is not correct.
The column Result should show only SUCCESS and NAME NOT FOUND and rarely NO MORE ENTRIES for registry entries in log. INVALID in column Result is not good. The log can be saved as CSV file with Ctrl+S or by clicking on disk symbol in toolbar.
Exit Process Monitor, logout from this account, logon on other account, start here also Process Monitor, configure the same filter, execute same batch file and save also this log into a CSV file. Compare the 2 CSV files and look for differences (other than time and line number).
Windows Registry Compare
Another method to find out what is different between the 2 accounts resulting in batch file execution not working is comparing the registry hives of those 2 accounts. In both accounts start Regedit and export entire key HKEY_CURRENT_USER to a *.reg file. Compare the two registry exports with a text comparison tool. The new administrator account has definitely less keys and values. Interesting are those blocks with just similar, but not identical lines.
Most interesting are the keys:
HKEY_CURRENT_USER\Console
HKEY_CURRENT_USER\Environment
HKEY_CURRENT_USER\Software\Classes\.bat
HKEY_CURRENT_USER\Software\Classes\batfile
HKEY_CURRENT_USER\Software\Microsoft\Command Processor
Some keys from this list can be missing completely. That would be okay as in this case the same key under HKEY_LOCAL_MACHINE is taken into account by Windows. But when a key is missing in account on which batch file execution fails, it should be also missing in the other account, or something is wrong here.
What could be a big and hard to find problem is a registry key which is displayed on viewing the registry tree with Regedit, but when clicking on the key it cannot be read.
I have seen such partly corrupt registry keys already several times and it is very hard to fix such a registry error. This happens for example if an application removes a registry key without removing it also from index table of the registry.
Totally unexpected things happen if a registry key is present in index, but does not exist anymore in registry. For example I fixed once an issue where HKLM\Software\Classes\mailto was in index list, but did not exist anymore in registry. When the user clicked on a mailto link, Windows started creating new emails in Outlook in a loop until Windows run out of resources and user restarted Windows.
Please add # before echo, like this:
#echo aa
#pause
Its working in my Windows7 machine.

Task scheduler cannot open batch file when set to run whether user is logged on or not

OS: Windows Server 2008 R2 Enterprise
I am unable to get the Task Scheduler to run .bat files while I am logged off. I have a a production .bat file I want to use, but for my troubleshooting purposes I am using C:\Users\Administrator\Desktop\test.bat
test.bat is very simple. All it contains is:
taskkill /im notepad.exe
It runs successfully on its own. If I have Notepad open and I double-click test.bat then the cmd window flashes and Notepad dies. The .bat file is not the problem.
The task I created in Task Scheduler is "Test taskkill" (without the quotes). I can see its location in Windows Explorer: C:\Windows\System32\Tasks\Test taskkill
If the task is set to run only when the user is logged on then the task works. With this setting, I can right-click on it > run and I get the same behavior as if I double-click the .bat file. That means the task is configured correctly.
If I set it to run whether or not the user is logged on then when I right-click > run nothing obvious happens. The job is reported as having been run successfully in the history, but Notepad survives. I know that I am using the proper credentials for the account that I am configuring to run the task. That account is the local administrator.
This issue appears similar to issues other have had in the past:
Running a .bat file in Scheduled Task
http://social.technet.microsoft.com/Forums/windowsserver/en-US/d47d116e-10b9-44f0-9a30-7406c86c2fbe/scheduled-task-wont-run-bat-file?forum=winservermanager
The thread in the second link seemed to resolve an identical issue for many people with the suggestion that the account used to run the task requires explicit permission to the .bat file and all files that the .bat file modifies. This was very promising (if an annoying requirement). However, I have confirmed or assigned explicit permissions for the local administrator to the following areas, and I am still not successful:
C:\Users\Administrator\Desktop\
C:\Users\Administrator\Desktop\test.bat
C:\Windows\System32\Tasks\
C:\Windows\System32\Tasks\Test taskkill
Additionally, I have confirmed that the local administrator account is in the local administrators group.
Am I missing some other permissions that needs to be set? Is there something else I should be looking at? Thanks!
I have resolved this problem with help from a contractor who was doing some other work for my institution.
In the properties window for the task, on the Action tab, when creating or editing the action that opens the batch file (in my case test.bat), there is the "Program/script:" field and there is also a "Start in (optional):" field. I previously had the "Program/script:" field containing the full path to the file, ending with the file name, and I had the "Start in (optional):" field null. This configuration appears to work without issue when the task is set to "Run only when user is logged on" in the General tab of the task's properties window. However, this configuration does not work when the task is set to "Run whether user is logged on or not".
In order to resolve the problem, I changed the action so that the "Program/script:" field contained only the file name, not the file path. I put the file path in the "Start in (optional):" field. This configuration works when the task is set to "Run only when user is logged on"! I have tested with the task running on a trigger and also with running it manually.
Not sure if this helps. My issue was using a interactive program (in particular Excel) as well.
Creating the 2 empty folders (Desktop) solved it. Create both even if you are running on x64.
C:\Windows\System32\config\systemprofile\Desktop
C:\Windows\SysWOW64\config\systemprofile\Desktop
I debugged my code and realised the code exited at this line
ExcelFile excelFile = new ExcelFile(directory, filename);
I read this solution somewhere and I cannot find the URL now.
Try this as well..
Resolved the "Run whether user is logged on or not" by setting the “Log on as Batch Job” security policy.
Here is details on the setting… https://danblee.com/log-on-as-batch-job-rights-for-task-scheduler/
You may take another approach, but here is the steps…
1) I updated the default domain group policy by adding my admin account (that I fire the task with) to the “Log on as Batch Job” security policy. (Even though ADMIN group is listed, and I am using an admin account)
2) I forced GPUPDATE on the client
3) Rebooted the client
4) Looked at the policy on the client to make sure it made it over from the DC
5) Set the task "Run whether user is logged on or not"
6) Ran the task on demand and it worked creating a PDF file.
7) Logged out and ran the task at scheduled time and it worked creating a PDF file.
I had similar problem, but it was related to the fact that there was a space in the path of my executable batch file. I have removed the space and now it works fine.
What work for me was make sure that the path is available.
i used net use Z: \computername\folder /persistent:yes
then the xxcopy /s /c /d /e /i /y D:*.* z:\BackupBat
I notice all my other .bat work fine only the one with the reference to a map folder was the one no running, so that need to be the problem. with these change the bat file runs good.
Verifying the following has worked for me:
1) 'Run if user is not logged in' option in Task Scheduler does not work for programs that is interactive mode. Example notepad, clock. Tasks will not run interactively. Make sure your program does not requires any interactive actions.
2)Check the “Start in (optional) “ If your program path is not one of the system paths. You have better to add you program path in it. On the "Program/Script" enter only the name of the program, and enter the path of your script in "Start in".
3)The user account you setup for your program must have permission not only to run your program itself and but also to run all other program that related to your program.
Here is a sample program:
On C:\myprogram\folderOne\test.cmd
date /t >> c:\Temp\testAuto.log
date /t >> c:\temp\testAuto.log
echo ----->> c:\temp\testAuto.log
cls
exit
-Create a Tasks, selecting on General>SecurityOptions "Run whether user is logged on or not"
-Enter on Action>Program/script: test.cmd
on "Start in" C:\myprogram\folderOne
-Run, you might see the cmd windows open and closes very quickly. The testAuto.log file should be in c:\tmp folder.
It might be because you don't have permission. I was facing the same problem and i found the solution like this -
Open Task Scheduler right click on your task and than select properties option.
In properties click on General tab and then click on 'User Group or User' and select the appropriate user.

Need a batch file to check the contents of an online text file

My business has been putting out a lot of software, but I'd like to implement a program that checks for updates of our software so our clients are alerted and can then upgrade.
I was thinking of adding a text file on our servers that would display either 0 (no update available) or 1 (update available!) that a batch could read and copy out to a local file.
So I've now uploaded a file (check.txt) that contains just the number '1' and placed on my server. And that's where I've got stuck...
After searching the net, all I could come up with is the following for a batch file:
http://www.mysite/updates/check.txt > update_available.txt
Now, I'm sure I've done something wrong here, as all I'm getting is a blank .txt file.
I'm sure I've missed something crucial here, but despite my searching of the interweb, I simply can't find a solution.
Any ideas?
Below solution cmay be weird, I've had a similar requirement in the task and I used to do the below. I couldn't find any other solution without any 3rd party tools and especially in a proxy environment.
Create a browser shortcut using chrome or just type the below code in a note pad file and save it as myfiledownload.url
[InternetShortcut]
URL=http://www.mysite/updates/check.txt
Make sure that your chrome is your default browser & chrome settings are set to download the files automatically to a path say C:\downloads\
Just use the below lines in your batch. It opens the browser (chrome) and downloads the file to your default download location and you can move it to some other location and do whatever you want. Use the timeout command to give some to open the browser and download the file.
-
#echo off
C:\downloads\myfiledownload.url
timeout /T 10 /nobreak
move c:\downloads\check.txt d:\test\whatever.txt
Cheers.
G
:: Get details. Note - options are case-sensitive!
wget -O %workdir%\update_available.txt http://www.mysite/updates/check.txt >NUL 2>NUL
WGET is a free GNU utility, just Google "wget"

Batch file doesnt run after deploying from SCCM

I have a batch file which uses gpresult /v and saves the output in a text file and copy that text file to a shared folder. This batch when i run on my local machine works perfectly fine but once i deploy it through SCCM it says can not open file with error code 4. I dont know what is wrong in the file.
the code is Like this:
#echo off
gpresult /v >%computername%.txt
xcopy %computername%.txt \some path
Error 4 is "The system cannot open the file.", as if the path is invalid or the open() fails for some other reason.
Do you know what directory the program is running in (CWD)?
That's where the results of gpresult are going (if the output redirection succeeds).
gpresult is not going to produce meaningful user-level data for the SYSTEM user.
Perhaps you should use gpresult /v scope computer.
Why are you using xcopy when you're only copying one file? xcopy really only has added value (over copy) if you are copying directories.
xcopy's behavior changes depending on how you specify the target. If the target ends with the directory separator (backslash), xcopy treats it like it's a directory. If it doesn't and the target doesn't exist, xcopy asks you what to do, which causes automated processes to pause indefinitely waiting for user input.
SCCM Programs Run as 'NT Authority\SYSTEM'
When SCCM (2007) runs a program, the program doesn't run as a regular user. It runs as the highest privilege user (sort of), SYSTEM.
This account is not a regular account, and many settings and environment variables that exist and are predictable for a regular user are different or do not exist for SYSTEM.
One particularly frustrating "feature" of the SYSTEM account's profile is that it is nestled away under %WINDIR%\System32, and so it is subject to filesystem redirection whenever you refer to anything relative to the profile.
Try this: use psexec -s (sysinternals) to get shell access as the SYSTEM account and run the command in that environment to see how it behaves. This is as close as we can get to an environment like the one SCCM programs run under.
When SCCM runs the command, the CWD will probably be somewhere under %WINDIR%\SysWOW64\CCM\ and may be invoked with the 32-bit version of CMD.EXE.
I have a question in regards to something similar to this. So I have an uninstall bat that runs. Due to the vendors uninstall it causes a force close of the windows explorer UI. So in haste to solve that issue I added a call to open explorer.exe. There is a problem with this as someone pointed out to me. Actually as soon as he said I knew exactly what he was saying and where he was going with his statement. Calling explorer.exe would be fine except that the bat is running under the system context not the user so when explorer is restarted it will start under the guise of the system desktop profile not the user's. I know there is way to still run under the guise of system but to restart explorer under the currently logged in user's profile.

Resources