Open a HTTPS URL under unattended batch control - batch-file

My problem is that I need to send a shutdown command to my NAS when the UPS tells my home server that there's a power cut. I want to do this by using the (Windows 10 Home) PC server's closedown notification, which can trigger a batch file as part of the closedown event, rather than by using extra hardware. I have determined that opening a particular URL will cause the NAS to close down gracefully.
https://192.168.1.10/get_handler?PAGE=System&OUTER_TAB=tab_shutdown&INNER_TAB=NONE&shutdown_option1=1&command=poweroff&OPERATION=set
The problems seem to be related to trying to bypass dialogues that result in the browser. First it asks for credentials. I can bypass this one by including them in the URL call, like this:
start "" "C:\Program Files\Mozilla Firefox\firefox.exe"
"https://username:password#192.168.1.10/get_handler?PAGE=System&OUTER_TAB=tab_shutdown&INNER_TAB=NONE&shutdown_option1=1&command=poweroff&OPERATION=set"
Now it pops up a dialogue asking me to confirm that I want to log on as "username", again defeating my attempt to make this run unattended (I might be anywhere when a power cut strikes). Is there a way around this? Just FYI, I gave up trying to work with Microsoft Edge as it kept cutting the URL paramaeters into pieces by inserting spaces everywhere. It also kept manually complaining about the security certificate each and every time I tried it. I think I'll have the same confirmation request problems with that browser too. So I need a way to surpress all these dialogues and just make the URL call. Any thoughts please?

The lack of any answers after this question had been posted over 24 hours told me that this was a tricky one & kept me trying. After I tried everything I could think of to solve it with Window's own tool set and finding nothing worked I realised I'd need something additional to solve the problem. Finally I gave up and installed the free Autohotkey and wrote a script to do the entire job, including handling the dialogue boxes. Once it was all working I made an executable from the script for convenience so I can easily call it from the close down batch (.bat) file. This solution works. Here is the script for anyone who needs to solve a similar problem:
> runWait, C:\Program Files\Mozilla Firefox\firefox.exe
> https://admin:password#192.168.1.10/get_handler?PAGE=System&OUTER_TAB=tab_shutdown&INNER_TAB=NONE&shutdown_option1=1&command=poweroff&OPERATION=set
>
> #Persistent SetTimer, MsgBoxCheck, 3000 return
>
> MsgBoxCheck: If WinExist("ahk_class MozillaDialogClass") {
> SetControlDelay -1 ControlClick, , Confirm, SetTimer,
> MsgBoxCheck, off exitApp } else { SetTimer, MsgBoxCheck, off
> MsgBox, 4, , Debug - No Confirm Window Found. exitApp } return
Please note, to make this work with non-Mozilla programs you will need to change the ahk_class parameter. I suggest you use Windows Spy to determine the class of window you want to close. You will also need to change 'Confirm' to whatever your window's title might be.

Related

Autohotkey function 'reload' starts an infinite loop that only Taskkill will stop

I'm a relative newbie with Autohotkey but I'm fairly certain this is not supposed to happen. When I use the 'reload' command, an infinite loop begins. As far as I can tell, it is a loop of whatever script invoked it. But it won't stop unless I use Taskkill. Actually, Task Manager might work but I haven't tried it. I'm running Windows 10 21H2. AHK is ver 1.1.34.03. I have tried a diagnostic boot of windows (almost no running apps) and I have also uninstalled and reinstalled AHK. Result remains the same.
I have a script that is only
Reload
msgbox, 4096, , Pausing
(There isn't really a blank line in there. Without it, the editor made it into a single line.)
My assumption was that msgbox would stop any loop. What actually happens is that the program begins to loop, flashing the msgbox momentarily. This goes on and on. I'm unable to stop it with the ahk icon because it also appears and disappears (in the hidden icons tray), so fast that I cannot click it. Only thing I have killed it with is taskkill.
Any suggestions?
-----Paul-----
#SingleInstance is probably not really what you need for this. Normally Reload is used with a hotkey, or a timer that checks if the file has changed, then reloads it. Where I use this I have a script running in the background with many little scripts attached to hotkeys. When I save the script it reloads. Something like:
~^s:: ; pass through hotkey when saving
If winActive(A_Scriptname) {
Reload
}
Return
Make sense?
(Above code is just an idea, which might work depending on what editor you are using)

How to skip and return a message if subscript prompts for user input in batch file

I'm testing new account creations by calling a script with the newly created account id/password. If everything is set up correctly the script reports back some text and continues on without pause. However if there's an issue the script will go to interactive mode asking for a userid/password.
I'd like some kind of error catch (or in this case interactive input catch) and report back that there's an issue with the account. Is there a way of doing this?
If your script returns different exit codes depending on the success/failure, you can react on the errorlevel, using if, goto and labels. See this answer for the syntax.

How can i export my event logs to a folder (csv or txt) on every start up automatically?

I was looking for either a batch file, powerscript (not really good with yet)or any way to have my event logs exported to txt or csv on every start up?
Im using windows 7 pro if that helps
This will output last 20 system event logs in eventlog.txt.Not sure what exactly you need from eventlog - it's a big place...
WEVTUtil query-events System /count:20 /rd:true /format:text > eventlog.txt
You can change System to Application,Security or Setup - not sure what exactly you need.
more info:
http://ss64.com/nt/wevtutil.html
check also this:
http://ss64.com/nt/psloglist.html
You can save this (or similar) command to bat file and schedule it on start-up
WEVTUtil query-events System /count:20 /rd:true /format:text > exported_file_name.csv /q:"Event[System[(EventID=1074)]]"
Then gpedit.msc - windows settings - scripts and add to start up.
Thanks #npockmaka for getting this started

Restart batch file on crash/error

I have a batch file that encounters several errors. These errors require the command prompt to be forcefully closed. Which causes me to have to open the file again to fix the issue.
Due to the nature of this application it is required to run all the time.
I'm looking for a way to automate the file to restart when it encounters an error. Is there a command I can do this with?
Could you please describe in detail and why the command accomplishes such a resolution?
Update:
What I would recommend to accomplish your goal, would be to turn your batch into a Service. (Documentation here) By converting your batch into a Service it no longer becomes subject to users being logged in, permission issues, it will run as a SYSTEM ACCOUNT. This in itself can alleviate a lot of anger for the process.
After you've completed that, you can write a batch file that ensures that your Service is indeed running. Your current issue, is it doesn't automatically restart. Well, a Service always runs- Even if it has an error it will still attempt to run.
Which means unless it has a Fatal Exception your Service should always work- But for certainty you can create a batch that will ensure your Service is running.
An example:
:START
timeout 3600
for /F "tokens=3 delims: " %%H in ('sc query "MyServiceName" ^| findstr "
if /I "%%H" NEQ "RUNNING" (
NET START "MyServiceName"
REM Service has Started...
)
)
GOTO START
So in theory every 3,600 seconds it will test if your Service is running, if it isn't it will start the Service for you.
Important:
This is more the proper way to resolve your issue, rather then circumvent it. However, as I noted your batch should still implore Exception Handling to ensure your application doesn't fall into an unusable state. This still isn't the best way, as it should implore Exception Handling and Verification to test against it's state.
As I mentioned before, you have a lot of methods to solve your issue. However, your thinking in a Linear Mindset. Which means:
Execute Command, Goal Guaranteed.
If I do this, this happens.
Essentially based on the minimal example I saw, it looks like you've created an infinite loop to continually execute your command. My question to you: When your loop has an error, how can it continue to run?
You've already stated that it happens in random areas- Nothing is random, those are more then likely areas that require some verification / testing to ensure it remains in a proper state. The faster your identify the potential problems, the more effective your program can run with no errors.
Hopefully that helps-
What exactly does your batch application do?
The reason I ask is because you can circumvent the issue with Windows Task Scheduler which allows you to configure some parameters to auto start and auto open particular applications based on your specified criteria. Will it be ideal? Will it truly automate to your needs- More then likely not.
As mentioned above by GolezTrol, the cause of your error will be the more important aspect to resolve your issue. Based on your remark
The errors are different each time, to be honest.
That could be an indicator that the batch script doesn't adhere to testing but rather assuming it successfully completed. Without any underlining information such as:
Function
Code Example
Where an error occurred, and during what task.
It makes it relatively difficult to point you in the proper direction. One thing that I would consider is IF. This is a fundamentally basic task but is quite important-
if(Directory.Exists(dirName))
{
// Do This
}
else
{
// Do This
}
I find the C# outline an easier method to understand the purpose of the IF. You can actually implement something similar in your batch. You would accomplish it like this:
if exist { insert file name } (
rem file exists
) else (
rem file doesn't exists
)
or you can accomplish it like this:
if exists c:\myFile.bat notepad c:\myFile.bat
If C:\myFile.bat exists, then open notepad. The reason this is an important is because if the variable doesn't exists, then it can not be affected. This allows your application to essentially make decisions in a very primitive manner.
You have quite a bit of flexibility- There are a lot of examples on this topic because batch programming has been around for a very, very long time. Another alternative would be to eventually move to Powershell. It will have access to the Windows Management Interface (WMI).
Hopefully this points you in the right direction, without more information our answers may not be much help.
I believe, that easiest way is to create one more .bat file with GOTO statement:
#echo off
:startover
echo (%time%) App started.
call "c:\app.bat"
echo (%time%) WARNING: App closed or crashed, restarting.
goto startover
Possibly this will fix your problem:
http://nssm.cc/usage
Basically what it does is you adding some bat file to nssm and making it a service.
In "Action on exit" part it says:
To configure the action which nssm should take when the application exits, edit the default value of the key HKLM\System\CurrentControlSet\Services\servicename\Parameters\AppExit. If the key does not exist in the registry when nssm runs it will create it and set the value to Restart.

Help getting Conky to work with LXDE & PCManFM

As some of you might be aware, there's a bug with either Conky or PCManFM (the desktop manager aspect of it) that makes the Conky window disappear in one of these situations:
Setting "own_window_type override" in .conkyrc (the usual configuration for Nautilus) flat out doesn't show the Conky window at all.
Setting "own_window_type desktop" in .conkyrc shows the Conky window, but it disappears if you click on the desktop.
Setting "own_window_type normal" in .conkyrc shows the Conky window, it doesn't disappear when clicking on the desktop, BUT... it disappears if you use LXPanel's "Minimize all windows" plugin ("Show desktop" equivalent). This happens if using the keyboard shortcut as well.
There are some workarounds to this, such as deactivating PCManFM's desktop management (and using feh for setting the wallpaper and, presumably, iDesk for the icons) or using another file manager altogether, but I've come to notice these are all subpar solutions. I really like PCManFM and I really like Conky. What's a guy to do? :-/
So I dug in LXPanel's source and found a relevant piece of code that might house my fix. The file is src/plugins/wincmd.c .
The idea I have is that when the "Minimize all windows" button is clicked, all windows (class) names would be compared to a static string "Conky" and if it matches, it simply wouldn't minimize that window. Simple, and it should work. But the problem is it has been a few years since I've touched any C code and I haven't really played with Xlib that much.
So far, I have done the following changes:
19a20
> #include <string.h>
77a79,82
>
> /* Getting window's class name */
> XClassHint class;
> XGetClassHint(GDK_DISPLAY(), client_list[i], &class);
81c88
< if (((task_desktop == -1) || (task_desktop == current_desktop))
---
> if (((task_desktop == -1) || (task_desktop == current_desktop) || strcmp(class.res_name, "Conky") != 0)
This compiles correctly, but when I run the new lxpanel and click on "Minimize all windows", Conky still disappears as before.
If someone can look into this file and see if my changes make sense, I'd be very grateful.
Thanks SO! :)
This is still impossible afaik. I made this quirky workaround. Just use the own_window_type normal mode where you cannot use the Win+D desktop shortcut, and fix conky on show desktop.
First I thought, just remapping the conky window will do the trick. But I found out that as long as the desktop is focussed, nothing will get drawn over it. Then I thought, just kill and restart conky. But while in show desktop mode, it will get created in the background.
So in order to get conky back:
The desktop must be unfocussed
restart conky or remap the window
Install xdotool; apt-get install xdotool
Create a script, e.g. /usr/local/bin/conky-remap.sh:
#!/usr/bin/env bash
zenity --info --text "Remapping Conky..." &
pid=$!
sleep 0.3
kill $pid
xdotool windowmap `xdotool search --classname 'conky'`
Edit ~/.config/openbox/lxde-rc.xml (or wherever shortcuts are in your distro).
Find:
<keybind key="W-d">
<action name="ToggleShowDesktop"/>
</keybind>
Change to:
<keybind key="W-d">
<action name="ToggleShowDesktop"/>
<action name="Execute">
<execute>conky-remap.sh</execute>
</action>
</keybind>
Activate the new keyboard shortcut configuration:
openbox --reconfigure
Press Win+D. You'll see a flash and conky is back!
This quirky solution is the only solution in the universe according to a week of google, so improving on it is encouraged.
Explanation:
zenity --info --text "Remapping Conky..." &
We need to create a random window to unfocus the desktop. Conky itself doesn't work. :(
We also need the script to continue, so use &
pid=$!
Get the pid of that last process
sleep 0.3
Sleep any less (slow HTPC) and the window is killed before it is created.
kill $pid
Kill the window as soon as it has performed its function.
xdotool windowmap xdotool search --classname 'conky'
Now finally, we can raise (remap) conky.
Quirks:
Desktop is not focussed, so you cannot use the arrows to navigate desktop icons
Can we refocus the desktop? As long as the windows are not programatically minimized, conky will stay put.
300 ms delay, and a flash of the dialog box.
Pressing Win+D for a second time to go back ('unshow desktop')
We would need a way to detect if the desktop is already in show-desktop-mode, in which case the script should exit 0
The simplest solution working perfectly with Openbox (and should work with other WMs too):
In your .conkyrc file:
own_window yes
own_window_type desktop
own_window_class Conky
The "desktop" window type prevents conky from being minimized when show desktop is executed. Moreover your windows will be restored by executing "show desktop" again
Install xdotool package (it's very lightweight, don't worry), in terminal emulator run the following:
xdotool search --class "Pcmanfm" behave %# focus windowraise $(xdotool search --class "Conky")
and make sure your conky doesn't hide when you focus a desktop
If everything is okay, interrupt xdotool by pressing Ctrl+C in your terminal and place the code above in autostart. It probably won't start right away, so you have to create a simple script (e.g. "show_conky.sh") containing
#!/bin/sh
sleep 5
xdotool search --class "Pcmanfm" behave %# focus windowraise $(xdotool search --class "Conky")
The minimal required sleep time should be defined accordingly to your system. To be sure, conky won't hide at the first launch before "show_conky.sh" is executed, you can also create another script with xdotool focus windowraise $(xdotool search --class "Conky") command and proper sleep time in it (or try to add it between "sleep" and "xdotool behave" commands it "show_conky.sh").
Restart your Xorg server. Enjoy! :)
I personally advice you using SpaceFM for managing desktop icons. It allows you to set margins for the desktop area, so conky never covers icons. Pcmanfm looks more friendly as an explorer, but you can use both of them: spacefm can open directories located on the desktop with other application. Its desktop behavior is identical to pcmanfm, so you should simply replace "Pcmanfm" in the code above with the "Spacefm"
This is an old "question", but it came up fairly high in Google hits when I searched for "Conky LXDE", because I couldn't get Conky to work in Lubuntu. But there is no need to hack LXPanel!
After MUCH searching and false trials and trails, I found a .conkyrc file in the "PCLinuxOS-Forums" that Just Worked™. It has proved to be an excellent base to tweak from on Lubuntu 11.10.
I now use the same set up on Linux Mint 13 LTS "Maya" Xfce (based on Ubuntu 12.04), and it continues to meet my (very simple) Conky requirements. The current form of my .conkyrc file is saved in a Gist if anyone is thinks it might help them. (The original source link for the forum is commented into the rc file.)
The solution is:
NetWMState nws;
guint task_desktop = get_net_wm_desktop(client_list[i]);
get_net_wm_state(client_list[i], &nws);
if (((task_desktop == -1) || (task_desktop == current_desktop))
&& ( ( ! nwwt.dock) && ( ! nwwt.desktop) && ( ! nwwt.splash)
&& ( ! nws.skip_pager) )
To build on Redsandro's solution:
Follow Redsandro's advice and sudo apt-get install xdotool and create some conky-remap.sh (or whatever) script in your /usr/local/bin (or wherever) directory. Also, install wmctrl if you do not already have it. We will be using this to make Conky active (I know this is different than mapping, but it behaves as I expect it to, so I'm not worried.)
run wmctrl -l to list all windows while Conky is running and take note of Conky's title (mine was something like Conky (<my-machine-name>).
While you're at it create another file in which we will save the current state of the desktop (0=not show-desktop-mode, 1=show-desktop-mode... almost) called something like .conky_desktop_state. I have put this into /usr/local/bin as well. Now back to conky-remap.sh:
#!/usr/bin/env bash
state=$(cat /usr/local/bin/.conky_desktop_state)
dt=$(xdotool get_desktop)
if (( $state == 1 )) ; then
echo 0 > /usr/local/bin/.conky_desktop_state
wmctrl -a "Conky (<my-machine-name>)"
else
echo 1 > /usr/local/bin/.conky_desktop_state
wmctrl -a "Conky (<my-machine-name>)"
xdotool search --desktop $dt . windowmap %#
fi
wmctrl's command to activate a window doesn't care about the desktop being in focus or not, so we don't need to sleep or flash a dialog window to the screen. $state and $dt are the variables which hold the current state of the desktop (again, kind of) and the current desktop id number.
xdotool search --desktop $dt . windowmap %# maps all of the windows from the current desktop back to the screen and leaves other desktops alone.
Edit ~/.config/openbox/lubuntu-rc.xml or wherever to execute the script when Win+D is pressed.
<keybind key="W-d">
<action name="ToggleShowDesktop"/>
<action name="Execute">
<command>conky-remap.sh</command>
</action>
</keybind>
openbox --reconfigure to refresh keybindings and you should be good to go.
With Win-D to show desktop, the desktop is focused, so you may use arrow keys to navigate desktop icons.
This solution does have its own set of quirks:
A second pressing of Win+D brings up all windows of the current desktop, not just the ones which were active before showing the desktop.
A toggle is stored in .conky_desktop_state, but it doesn't really match up with show-desktop-mode since it only toggles when the script is executed. This means it is possible to have one desktop shown and the other not. In this case, the desktop will be shown briefly and then all windows will be brought active. One more pressing Win+D will show the desktop.
Sometimes the whole thing fails and Conky disappears with all of the other windows, albeit rarely. Just cat /usr/.../.conky_desktop_state and toggle the opposite value in (ie- echo 1 > /usr/.../.conky_desktop_state)
Although most of the time the last active window before Win+D is on top after a second Win+D, it is not necessarily active, meaning you may have to click in the window or Alt+Tab to it to start typing in it. This generally is the case with terminal windows.
Ideally, we would be able to look at all active (mapped) windows on each desktop individually and execute one or the other command based on if Conky is the only active window, but I wasn't smart (dedicated) enough to do that, so here is my contribution. Please build on it and reply.
Simplifying #imiric's answer:
Openbox RC.xml (e.g. ~/.config/openbox/lxde-rc.xml):
<keybind key="W-d">
<action name="ToggleShowDesktop"/>
<action name="Execute">
<command>wmctrl -a "Conky (hostname)"</command>
</action>
</keybind>
~/.conkyrc:
own_window yes
own_window_type normal
own_window_class conky-semi
own_window_transparent yes
own_window_hints undecorated,sticky,skip_taskbar,skip_pager
own_window_argb_visual yes
got success with conky transparency in LXDE on debian squeezy, with pcmanfm running.
In the conky config file (i.e. .conkyrc) I removed all 'own_window' lines, except the following:
own_window yes
own_window_class conky
own_window_transparent yes
own_window_hints undecorated,below,skip_taskbar,sticky,skip_pager
Adding again some often used lines caused transparency to fail, or conky wouldn't start at all. Very strange...

Resources