Hey guys im im trying to get a cumulative uptime data of my network machines easily.
Essentially we need the total of the uptime saved to a file so at say the end of the quarter we can report on this.
I can easily get uptime at the time i run a script, but unsure how to go about one that saves the uptime of the machine each day so i can then report back on it.
Any help is appreciated.
If you want to do this with the uptime that the machine itself monitors you need to (more or less) continuously update your log, because the counter is reset after a system crash or reboot you'll lose the uptime information between the last log write and the crash/reboot. A better approach would be to implement a system monitoring solution (Nagios, Zabbix, WhatsUp, SCOM, ...). These tools continuously track the system uptime and already provide reports that you can use.
If you still want to go the "local script" route, running something like the following every 5 minutes as a scheduled task might work:
Set fso = CreateObject("Scripting.FileSystemObject")
Set wmi = GetObject("winmgmts://./root/cimv2")
Set re = New RegExp
logfile = "C:\path\to\uptime.log"
uptimes = fso.OpenTextFile(logfile, 1, True).ReadAll
'extract last uptime from log
re.Pattern = "(\d+)\s*$"
For m In re.Execute(uptimes)
lastUptime = CLng(m.SubMatches(0))
Next
'get current uptime
qry = "SELECT * FROM Win32_PerfFormattedData_PerfOS_System"
For Each v In wmi.ExecQuery(qry)
currentUptime = CLng(v.SystemUpTime)
Next
Set f = fso.OpenTextFile(logfile, 2)
If IsEmpty(lastUptime) Or lastUptime >= currentUptime Then
'append current uptime if the last uptime was greater or equal to than the
'current uptime (=> a crash or reboot occurred) or no uptime was logged before
f.WriteLine uptimes & currentUptime
Else
'update last uptime otherwise
f.WriteLine re.Replace(uptimes, currentUptime)
End If
f.Close
Related
I am running a Matlab script on Linux (RedHat Enterprise Linux RHEL 7.6, 64-bit) as a cron job. I am not admin on that machine, therefore, I use crontab -e to schedule the job. The installed version of Matlab is 2018b. The email which I recieve upon execution includes a couple of >> at the beginning and end which I find a bit irritating.
Here, an example of the email:
MATLAB is selecting SOFTWARE OPENGL rendering.
< M A T L A B (R) >
Copyright 1984-2018 The MathWorks, Inc.
R2018b (9.5.0.944444) 64-bit (glnxa64)
August 28, 2018
To get started, type doc.
For product information, visit www.mathworks.com.
>> >> >> >>
Matlab started: 2020-07-31 21:50:26.
>> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >>
Going to update from 2015-01-01 00:00:00 UTC to 2015-12-31 23:00:00 UTC.
[...]
>> Matlab closes: 2020-07-31 23:26:41.
>>
The corresponding lines at the beginning of the Matlab script look exactly like this:
close all
clearvars
% profile on % to check performance
fprintf('\nMatlab started: %s.\n', char(datetime()))
%% Database user parameters
% connects always to the soecified database on "localhost"
DB_conn_name = 'abc';
DB_username = 'def';
DB_password = 'ghi';
% Add path and subfolders
if isunix
addpath(genpath('/project/abc'));
elseif ispc
addpath(genpath('C:\Branches\abc'));
end
% Change working folder
if isunix
cd /project/abc
elseif ispc
cd C:\Branches\abc
end
% Add database driver to path
javaaddpath JDBC_driver/mysql-connector-java.jar % Forward slashes within Matlab work even on Windows
% Set default datetime format
datetime.setDefaultFormats('default','yyyy-MM-dd HH:mm:ss')
%% Begin and end of update period
% now_UTC = datetime('now','TimeZone','UTC');
% time_2 = datetime(now_UTC.Year, now_UTC.Month, now_UTC.Day-1, 22, 0, 0); % Set the end time not too late, otherwise, some data might not yet be available for some areas leading to ugly "dips" in Power BI.
% During each update, we update e.g. the past 30 days
% datetime_month_delay = time_1 - days(30);
% Override automatic dates obtained below, for testing purposes
% time_1 = datetime(2020,1,1,0,0,0);
% time_2 = datetime(2020,2,1,23,0,0);
% Updating several years, one at a time
for iYear = 2015:2019
time_1 = datetime(iYear,1,1,0,0,0);
time_2 = datetime(iYear,12,31,23,0,0);
fprintf(['\nGoing to update from ',char(time_1),' UTC to ',char(time_2),' UTC. \n'])
[...]
Looks as though each row that is outside the for loop produces an empty line and therefore such a >> prompt in the output. Also visible at the end (not included here).
The crontab -e looks like the following:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=<my email address>
HOME=/project/abc
HTTP_PROXY=<proxy address>:8086
HTTPS_PROXY=<proxy address>:8086
# Run script regularly: minute hour day month dayofweek command
# No linebreaks allowed
15 2 * * * ~/script.sh
The shell script script.sh looks like this:
#!/bin/bash
/prog/matlab2018b/bin/matlab -nodesktop < ~/git-repos/abc/matlabscript.m
Does anyone have an idea what I need to change to get rid of these >>? That would be great! Thanks in advance!
The -nodesktop flag is still giving you an interactive shell, which is why crontab is capturing the prompts at all. You need to tell the matlab command what statement to execute.
I know you are using R2018b; but, I am going to give you BOTH answers for before and after R2019a, in case you ever upgrade.
For both answers: Because you called this in your crontab, make sure to use full path for your MATLAB executable for security reasons; and, it would be good to make sure you use the -sd flag as well so that your statement to execute is first in the path. The statement to execute is to be typed the same way you would type it on the MATLABcommand line.
Before R2019a: Per the doc page for the R2018b matlab (Linux) command, you need to run your command with the -r and -sd flags together. The -sd flag specifies your startup directory. Also, your code needs to have an exit statement at the end so that the matlab executable knows its done.
/path/before_R2019a/matlab -sd /path/startup_directory -b statement
Starting in R2019a, the -batch flag in your invocation of MATLAB is the recommended way to run automated jobs like this, per the matlab (Linux) command doc page
Note that starting in R2019a, the -r flag is NOT recommended; and, it should NOT be used with the -batch flag.
The -batch flag is simpler to use, and was added to make automation tasks easier. For starters, you no longer need to have an exit statement in your code with this approach.
Also remember that if you need quotes, starting in R2016b, MATLAB handles both double and single quoted strings. Choose appropriately in your script or cron call to handle your linux shell replacements - or avoid them.
/path/R2019a+/matlab -sd /path/startup_directory -b statement
As an added bonus, if you use the -batch flag, you can tell from inside your script whether it is running from a -batch call or interactively using the MATLAB variable batchStartupOptionUsed.
I would like to run a macro just before Windows shutsdown to log the time.
I wrote below program to run the macro just right after windows starts up. I will put the shortcut in Windows startup folder so that when windows starts, it will log the current day time and date.
But how to run a macro just before shutting down the PC.
The same below code will work for Start up and shut down with little change.
But how to run the macro or code before windows turns off
Private Sub Workbook_Open()
'
' Macro1 Macro
'
Dim Day As Date
Dim Tim As Date
Dim Row As Integer
Dim Col As Integer
Row = 1
Col = 1
Day = DateValue(Now)
Tim = TimeValue(Now)
While (Cells(Row, Col) <> "")
Row = Row + 1
Wend
Cells(Row, Col) = Day
Cells(Row, Col + 1) = Tim
ThisWorkbook.Save
'
End Sub
If you put something in the startup folder, it will not really run at startup, but at user logon.
To run something at startup or shutdown, you need to implement startup or shutdown scripts through Group Policy. Type "gpedit.msc" in the run box to explore Group Policy.
Another solution is the system eventlog, events from source "eventlog" are logging all startup and shutdown activity.
This popup kills many of my tests. Even simple DOM interactions like .exists? timeout. Is there any way of detecting that it appeared and dismissing it?
Warning: Unresponsive script.
A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete.
dom.max_script_run_time=999
dom.max_chrome_script_run_time=19
These websites aren't designed nor influenced by me. I am merely scraping and sending them instructions as customer.
I run a small autoit3 application that kills popups. If I recall correctly, it waits a little bit to see if the popup is handled before it kills it. This removed many frustrations for me. I also had a version of this that would match certain keywords in the title or body that was read from a file - that allowed me to avoid killing something that needed to stay.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; AutoIt Version: 3.1.0 ;
; Author: Dave McNulla ;
; Script Function: Close unwanted popups during test automation. ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Opt("GUIOnEventMode", 1) ; Change to OnEvent mode
Opt("WinTextMatchMode", 1) ;0=best, 1=quick
Opt("WinTitleMatchMode", 2) ;1=start, 2=subStr, 3=exact, 4=advanced
Opt("TrayIconHide", 0) ;0=show, 1=hide
Opt("TrayMenuMode", 0) ;0=default
TraySetIcon("Shell32.dll", 98)
dim $SleepTime = 2000
dim $Max = 100
$Message = "{ENTER}"
$ButtonClick = "[CLASS:Button; TEXT:OK]"
$Title = "[CLASS:#32770;TITLE:Internet Explorer]"
While 1
If WinExists($Title) Then
WinActivate($Title)
Sleep($SleepTime)
ControlClick($Title, "", $ButtonClick)
EndIf
Sleep($SleepTime)
If $Max < 1 Then Exit(1)
WEnd
I have the eventual goal of determining that a particular database on a particular server with particular credentials is running, but I would settle, at this point, for the ability to check and see if a server is actually up on the network. Does anyone have a way of doing this? I seem to be drawing a blank.
Michael
try this
Dim target
Dim result
target= "172.19.130.96"
Set shell = WScript.CreateObject("WScript.Shell")
Set shellexec = shell.Exec("ping " & target)
result = LCase(shellexec.StdOut.ReadAll)
If InStr(result , "reply from") Then
WScript.Echo "Server alive"
Else
WScript.Echo "Not Alive"
End If
There maybe better ways especialy given you end goal but this should work and at least point you in the correct direction.
Here's an alternative solution that uses the Win32_PingStatus WMI class (note: this class is only available on Windows XP and later):
strServer = "stackoverflow.com"
Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
Set oPing = oWMI.Get("Win32_PingStatus.Address='"& strServer & "'")
If oPing.StatusCode = 0 Then
WScript.Echo "Server is available."
Else
WScript.Echo "Server is not available."
End If
More ping script samples here: Why Doesn't My Ping Script Run on Windows 2000 Computers?
If you update the ping command so it only sends one echo request the script executes faster, if you've got an unreliable network this might not be best but for local LAN it's useful.
Dim target
Dim result
target= "172.19.130.96"
Set shell = WScript.CreateObject("WScript.Shell")
Set shellexec = shell.Exec("ping -n 1 " & target)
result = LCase(shellexec.StdOut.ReadAll)
If InStr(result , "reply from") Then
WScript.Echo "Server alive"
Else
WScript.Echo "Not Alive"
End If
For checking whether your database server is up, you can use tools like nmap. Then you can call it in your vbscript using exec() as per normal.
How can my program know if windows rebooted since the last time it ran? All versions of windows XP and on.
This can be accomplished trivially using the global atom table. Just make sure your atom name is unlikely to conflict with another atom.
if (GlobalFindAtom ("MySecretName") == 0)
{
// First time run since reboot
GlobalAddAtom ("MySecretName");
}
There's a Windows API call you can make called GetTickCount...
http://msdn.microsoft.com/en-us/library/ms724408%28VS.85%29.aspx
Edit: The idea is that when your program starts, you make a call to GetTickCount (which returns how many milliseconds Windows has been running), and then calculate an exact start date (right now minus the number of milliseconds). Store that date, and then the next time your program starts, calculate the date again and compare it to the previously stored date. If the dates are different, Windows has rebooted. Use GetTickCount64 if possible (but don't code your solution solely using this function.
You can use WMI:
strComputer = "."
Set objWMIService = GetObject _
("winmgmts:\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("Select * from Win32_OperatingSystem")
For Each objOS in colOperatingSystems
dtmBootup = objOS.LastBootUpTime
dtmLastBootupTime = WMIDateStringToDate(dtmBootup)
dtmSystemUptime = DateDiff("h", dtmLastBootUpTime, Now)
Wscript.Echo dtmSystemUptime
Next
Function WMIDateStringToDate(dtmBootup)
WMIDateStringToDate = CDate(Mid(dtmBootup, 5, 2) & "/" & _
Mid(dtmBootup, 7, 2) & "/" & Left(dtmBootup, 4) _
& " " & Mid (dtmBootup, 9, 2) & ":" & _
Mid(dtmBootup, 11, 2) & ":" & Mid(dtmBootup, _
13, 2))
End Function
net statistics workstation|find "Statistics since"
The Microsoft utility uptime.exe "processes the machine's event log to determine system availability and current uptime".
Simple, but ugly solution : just launch a never-ending dummy process :-)
If it's still here, you didn't reboot. If it's not, chances are that you have just rebooted.
In the vein of ugly hacks ... stick something in one of the RunOnce registry keys
How about adding a file to %TMP% and check if it's still there (%TMP% should be cleared at each reboot by Windows)
or
more robust way, create a file somewhere and mark it for deletion on next reboot (see MoveFileEx API) and check that file