I need to know the status of a service at the end of my batch script which restarts services using "net stop thingie" and "net start thingie".
In my most favorite ideal world, I would like to e-mail the state to myself, to read on cold winter nights, to reassure myself with the warmth and comfort of a server that I know is running right.
Just for you to know, I'm using a Windows server 2003 platform, and a batch file seemed the best choice. I don't mind using something else, and would be very open to suggestions, but just for the sake of knowledge (as a zombie craves brains, I thought, why not inflate my own), is there a command that allows me to check on the status of a service, in command line?
Should I just redirect the output of the command to a file?
Where the hell are my pants? (Gosh, I really do hope the humor inserted in this will not insult anyone. It's Wednesday morning, and humor I do need too :P)
[Edit:] The solution I used is (no longer) available for download from --link redacted--
It is used as a task set to be executed during the night, and checking my e-mail in the morning, I see whether or not the service has correctly restarted.
Have you tried sc.exe?
C:\> for /f "tokens=2*" %a in ('sc query audiosrv ^| findstr STATE') do echo %b
4 RUNNING
C:\> for /f "tokens=2*" %a in ('sc query sharedaccess ^| findstr STATE') do echo %b
1 STOPPED
Note that inside a batch file you'd double each percent sign.
You can call net start "service name" on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.
Using pstools - in particular psservice and "query" - for example:
psservice query "serviceName"
look also hier:
NET START | FIND "Service name" > nul
IF errorlevel 1 ECHO The service is not running
just copied from:
http://ss64.com/nt/sc.html
If PowerShell is available to you...
Get-Service -DisplayName *Network* | ForEach-Object{Write-Host $_.Status : $_.Name}
Will give you...
Stopped : napagent
Stopped : NetDDE
Stopped : NetDDEdsdm
Running : Netman
Running : Nla
Stopped : WMPNetworkSvc
Stopped : xmlprov
You can replace the ****Network**** with a specific service name if you just need to check one service.
Using Windows Script:
Set ComputerObj = GetObject("WinNT://MYCOMPUTER")
ComputerObj.Filter = Array("Service")
For Each Service in ComputerObj
WScript.Echo "Service display name = " & Service.DisplayName
WScript.Echo "Service account name = " & Service.ServiceAccountName
WScript.Echo "Service executable = " & Service.Path
WScript.Echo "Current status = " & Service.Status
Next
You can easily filter the above for the specific service you want.
Well i see "Nick Kavadias" telling this:
"according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST ..."
If you type in Windows XP this:
NET START /LIST
you will get an error, just type instead
NET START
The /LIST is only for Windows 2000... If you fully read such web you would see the /LIST is only on Windows 2000 section.
Hope this helps!!!
my intention was to create a script which switches services ON and OFF (in 1 script)
net start NameOfSercive 2>nul
if errorlevel 2 goto AlreadyRunning
if errorlevel 1 goto Error
...
Helped a lot!! TYVM z666
but when e.g. service is disabled(also errorlevel =2?)it goes to "AlreadyRuning"and never comes to
if errorlevel 1 goto Error ?!!
i wanted an output for that case ...
:AlreadyRunning
net stop NameOfSercive
if errorlevel 1 goto Error
:Error
Echo ERROR!!1!
Pause
my 2 Cents, hope this helps
Maybe this could be the best way to start a service and check the result
Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:
#ECHO OFF
REM Put whatever your Batch may do before trying to start the service
net start NameOfSercive 2>nul
if errorlevel 2 goto AlreadyRunning
if errorlevel 1 goto Error
REM Put Whatever you want in case Service was not running and start correctly
GOTO ContinueWithBatch
:AlreadyRunning
REM Put Whatever you want in case Service was already running
GOTO ContinueWithBatch
:Error
REM Put Whatever you want in case Service fail to start
GOTO ContinueWithBatch
:ContinueWithBatch
REM Put whatever else your Batch may do
Another thing is to check for its state without changing it, for that there is a much more simple way to do it, just run:
net start
As that, without parameters it will show a list with all services that are started...
So a simple grep or find after it on a pipe would fit...
Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:
#ECHO OFF
REM Put here any code to be run before check for Service
SET TemporalFile=TemporalFile.TXT
NET START | FIND /N "NameOfSercive" > %TemporalFile%
SET CountLines=0
FOR /F %%X IN (%TemporalFile%) DO SET /A CountLines=1+CountLines
IF 0==%CountLines% GOTO ServiceIsNotRunning
REM Put here any code to be run if Service Is Running
GOTO ContinueWithBatch
:ServiceIsNotRunning
REM Put here any code to be run if Service Is Not Running
GOTO ContinueWithBatch
:ContinueWithBatch
DEL -P %TemporalFile% 2>nul
SET TemporalFile=
REM Put here any code to be run after check for Service
Hope this can help!! It is what i normally use.
Well I'm not sure about whether you can email the results of that from a batch file. If I may make an alternate suggestion that would solve your problem vbscript. I am far from great with vbscript but you can use it to query the services running on the local machine. The script below will email you the status of all of the services running on the machine the script gets run on. You'll obviously want to replace the smtp server and the email address. If you're part of a domain and you run this script as a privileged user (they have to be an administrator on the remote machine) you can query remote machines as well by replacing localhost with the fqdn.
Dim objComputer, objMessage
Dim strEmail
' If there is an error getting the status of a service it will attempt to move on to the next one
On Error Resume Next
' Email Setup
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Service Status Report"
objMessage.From = "service_report#noreply.net"
objMessage.To = "youraddress#example.net"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.example.net"
'Server port (typically 25)
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
Set objComputer = GetObject("WinNT://localhost")
objComputer.Filter = Array("Service")
For Each aService In objComputer
strEmail = strEmail &chr(10) & aService.Name & "=" & aService.Status
Next
objMessage.TextBody = strEmail
objMessage.Configuration.Fields.Update
objMessage.Send
Hope this helps you! Enjoy!
Edit: Ahh one more thing a service status of 4 means the service is running, a service status of 1 means it's not. I'm not sure what 2 or 3 means but I'm willing to bet they are stopping/starting.
according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST but i can't get it to work on by XP box. I'm sure there's some WMI that will give you the list.
Ros the code i post also is for knowing how many services are running...
Imagine you want to know how many services are like Oracle* then you put Oracle instead of NameOfSercive... and you get the number of services like Oracle* running on the variable %CountLines% and if you want to do something if there are only 4 you can do something like this:
IF 4==%CountLines% GOTO FourServicesAreRunning
That is much more powerfull... and your code does not let you to know if desired service is running ... if there is another srecive starting with same name... imagine:
-ServiceOne
-ServiceOnePersonal
If you search for ServiceOne, but it is only running ServiceOnePersonal your code will tell ServiceOne is running...
My code can be easly changed, since it reads all lines of the file and read line by line it can also do whatever you want to each service... see this:
#ECHO OFF
REM Put here any code to be run before check for Services
SET TemporalFile=TemporalFile.TXT
NET START > %TemporalFile%
SET CountLines=0
FOR /F "delims=" %%X IN (%TemporalFile%) DO SET /A CountLines=1+CountLines
SETLOCAL EnableDelayedExpansion
SET CountLine=0
FOR /F "delims=" %%X IN (%TemporalFile%) DO #(
SET /A CountLine=1+CountLine
REM Do whatever you want to each line here, remember first and last are special not service names
IF 1==!CountLine! (
REM Do whatever you want with special first line, not a service.
) ELSE IF %CountLines%==!CountLine! (
REM Do whatever you want with special last line, not a service.
) ELSE (
REM Do whatever you want with rest lines, for each service.
REM For example echo its position number and name:
echo !CountLine! - %%X
REM Or filter by exact name (do not forget to not remove the three spaces at begining):
IF " NameOfService"=="%%X" (
REM Do whatever you want with Service filtered.
)
)
REM Do whatever more you want to all lines here, remember two first are special as last one
)
DEL -P %TemporalFile% 2>nul
SET TemporalFile=
REM Put here any code to be run after check for Services
Of course it only list running services, i do not know any way net can list not running services...
Hope this helps!!!
Related
I have a custom package I want to install automatically in my docker using expect.
The first thing the package asks me to do is press Enter to continue, then it prints another 2 empty lines then it waits for an input.
My expect script :
#!/usr/bin/expect -f
set timeout -1
spawn ./install
expect "\n"
send -- "\n"
But as you can see in the image, it just runs the installer and exits.
I tried removing the expect "\n" so only send -- "\n" will execute but now even the install message doesn't appear (tried with set timeout 1000 before send and it also didn't work)
Any ideas?
P.S : This is a link to the package if anyone wants to have a go at it:
https://www.bayometric.com/downloads/digital-persona/DP_UareU_Linux223_20140429.2.zip
(the installer is inside DP-UareU-RTE-2.2.3-1.20140429_1533.tar.gz)
expect "\n" match a linefeed exactly, I think this is not what your program is sending.
To wait for a Shell prompt you can use expect "%" or expect "*" to match anything.
If you need to make sure you're dealing with the right prompt you may be able to use something like expect "*Linux Installation*".
Also don't send \n but \r for the enter key :
#!/usr/bin/expect
spawn ./install
expect "*Linux Installation*"
send "\r"
expect eof
Note that the default flag is -gl for glob pattern matching but you can also use the -re flag for regular expression matching.
Hiya made a simple Youtube autoviewer using notepad*BATCH FILE but i want to have user input--> so the user can change the link before pressing start
And i wont it to stop script after its LOOPS 250 times.
:top
start /min iexplore.exe http://www.youtube.com/watch?v=u5DzRTyhs_0
#echo "waiting"
ping -n 5 127.0.0.1>nul
#echo "done waiting"
TASKKILL /F /IM "iexplore.exe"
ipconfig /release /renew
GOTO top
So USER CAN CHANGE URL LINK THEN PRESS START.
Many thks
Add after "start /min iexplore.exe http://www.youtube.com/watch?v=u5DzRTyhs_0":
set /a number=%number% + 1
if "%number%"=="250" (goto whereever)
if not "%number%"=="250" (goto whereever)
http://www.mpgh.net/forum/showthread.php?t=754730 <-- Working EXE version, finlayy finish coding it!
for /L %a in (1,1,10) do #(echo run %a&batch.exe)
http://www.pcreview.co.uk/forums/loop-example-cmd-window-t1468124.html
I'm not too familiar with cmd or anything, but I have done some research and put together a bit of what I want. This .bat I'm trying to make would take the output of ipconfig/all and select the mac address and ip address of the ethernet adapter and insert them in key locations in a pre-prescribed url for those instances when a computer doesn't automatically redirect to the front page of my hotel's internet billing setup. this is not official work; I am only trying to "ease my burden" a bit and save time typing.
the full address I need to create in a .txt is 000.000.000.00/defaulta.php?mac=xxxxxxxxxxxx&ip=xxx.xxx.xx.xxx
everything but the mac and ip address (both listed as x's) are exactly as they need to be in every case. the ip address shown censored with 0's is intentionally changed for security reasons, and no work needs to be done for that. I have been able to create a simple .bat to create an output of the ipconfig data onto any user's desktop for easy access:
#echo off
ipconfig/all > %userprofile%\Desktop\url_address.txt
I have tried using other parsing solutions to get the data that I need, but the one easiest for me to adapt (linked here) would only output the last instance, not the first or any in between when I make the simplest substitution. I could try to use one of the solutions for only selecting certain lines, but I've seen some computers listing their ethernet first and wireless second, while others list wireless first and ethernet second. I need to parse based specifically on the ethernet lines, as wireless internet is not available in the rooms.
here's an example of the output from my personal pc:
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . : xxxx.net
Description . . . . . . . . . . . : Atheros AR8121/AR8113/AR8114 PCI-E Ethernet Controller
Physical Address. . . . . . . . . : xx-xx-xx-xx-xx-xx
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : xxxx::xxxx:xxxx:xxxx:xxxx%12(Preferred)
IPv4 Address. . . . . . . . . . . : xxx.xxx.xx.xxx(Preferred)
anyone who looks up their own and compares will see it's not all the same length, so parsing based on length of characters won't work as different guests will have different cards, etc. this means I need to parse two specific points, the physical address for the mac in the url and the ipv4 address for the ip address in the url. would this mean I have to make two texts, one for each parsing? and how will these two variables be able to be inserted into the final url?
so my main questions are:
1) is it possible to take the two parts I need from the ethernet data and insert them into the appropriate places in the required link and put it in a .txt, and if so, what exactly needs to be done?
2) does the full function I intend need to be done through several .txt files being written as the function progresses to the final solution, or can this all be output to one text file on the guest's desktop for less clutter and easier deletion?
Question was tl;dr. Does this do what you're looking for? Modify xxxx.net and 000.000.000.00 as appropriate.
#echo off
setlocal enabledelayedexpansion
set found=0
for /f "tokens=1,2 delims=:(" %%I in ('ipconfig /all') do (
if !found!==1 (
for /f %%x in ('echo "%%I" ^| find "Physical Address"') do set mac=%%J
for /f %%x in ('echo "%%I" ^| findstr "IP[v4]*.Address"') do (
set ip=%%J
goto next
)
)
for /f %%x in ('echo "%%J" ^| find /i "xxxx.net"') do set found=1
)
echo Couldn't scrape info. Press any key to exit.
pause >NUL
goto :EOF
:next
set mac=%mac: =%
start http://000.000.000.00/defaulta.php?mac=%mac:-=%^&ip=%ip: =%
It performs an ipconfig /all and loops through the output, ignoring everything until it encounters xxxx.net (your connection-specific DNS suffix). Then it looks for Physical Address and IPv4 address from there. Spaces have to be removed from both captures, and dashes removed from the MAC address, all through variable string substitution. Then it launches the user's default web browser to visit the URL you built.
If you actually do need this URL written to a text file instead of launched, then change
start http://000.000.000.00/defaulta.php?mac=%mac:-=%^&ip=%ip: =%
to
echo http://000.000.000.00/defaulta.php?mac=%mac:-=%^&ip=%ip: =% >outfile.txt
Be sure to put a space before the > to make sure Windows redirects stdout to the text file rather than whatever number the IP address happens to end with.
UPDATE 2013.02.27:
The above stuff should work regardless of user access level (administrator or normal user). If you want to simulate running as a non-privileged user, run the following command:
runas /trustlevel:0x20000 cmd
... to open a cmd prompt with restricted privileges. Then you can see for yourself that ipconfig /all still works.
For what it's worth, ipconfig /all is not the only place to scrape the IP and MAC address. If you'd like an alternative to the above script, try this one:
#echo off
setlocal
for /f "tokens=1,2 delims=={}," %%I in (
'wmic nicconfig where ^(ipenabled^='TRUE' and dnsdomain is not null^) get ipaddress^, macaddress /format:list'
) do (
if %%I==IPAddress set ip=%%~J
if %%I==MACAddress set mac=%%J
)
start "" "http://000.000.000.00/defaulta.php?mac=%mac::=%&ip=%ip%"
As before, don't forget to change the IP address in the URL as appropriate.
Update 2013.03.29:
Well, since nothing else has worked for every client computer (as wmic will not work on WinXP Home), and just to see whether I could more than anything, here's another one to try -- a batch / JScript hybrid script. Save this with a .bat extension and I think it should work on every version of Windows after 98 and ME (Mistake Edition, if I recall correctly).
As before, don't forget to replace 000.000.000.00 in the url.
#if (#a==#b) #end /* <-- ignore this, please
:: batch portion
#echo off
setlocal
for /f "tokens=1,2" %%I in ('cscript /nologo /e:jscript "%~f0"') do (
set mac=%%I
set ip=%%J
)
start "" "http://000.000.000.00/defaulta.php?mac=%mac::=%&ip=%ip%"
goto :EOF
:: JScript portion (leave this weird bit here, please) --> */
var wmi = GetObject("winmgmts:\\\\.\\root\\cimv2");
var adapters = wmi.InstancesOf("Win32_NetworkAdapterConfiguration");
for (var res=new Enumerator(adapters); !res.atEnd(); res.moveNext()) {
var adapter = res.item();
/* -------------------------------------------------------------
Note to supergaijin: If this script fails like all the others,
try removing "|| !adapter.DNSDomain" from the following line so
it reads as follows: if (!adapter.IPEnabled) continue;
------------------------------------------------------------- */
if (!adapter.IPEnabled || !adapter.DNSDomain) continue;
WSH.Echo(adapter.MACAddress + ' ' + adapter.IPAddress.toArray()[0]);
}
Credits: I stumbled upon the Win32_NetworkAdapterConfiguration class using WMI Explorer. I figured out how to query its child instances with the help of Scriptomatic (which was much more useful than the TechNet documentation).
First of all, I am not good at scripting and I need to delete a
windows service in a batch file.
The service name is randomly generated, I only know the display name
of the script. What can I do?
I tried basically as a trial
#echo off
set sname = sc getkeyname "Display Name"
sc delete %sname%
Not Working..
This is a general format, you must fix some details:
#echo off
for /F %%s in ('sc getkeyname "Display Name"') do set sname=%%s
sc delete %sname%
For example, if the service name is not displayed in the first line:
for /F "skip=#" %%s in ('sc getkeyname "Display Name"') do set sname=%%s
If the service name does not appear at beginning of the line:
for /F "tokens=2" %%s in ('sc getkeyname "Display Name"') do set sname=%%s
We may help you whit more detail if you show us the info displayed by sc getkeyname ... and what the info you want is. I hope it helps.
This may bit a bit of a basic question, but I can't seem to find an answer on the web. I'm trying to automatically set up tomcat as a service through a batch file.
My batch file currently looks like this:
set memSize=512
set jvmOptions="-XX:MaxPermSize=512M"
ECHO Setting up tomcat as a service.
call service.bat install
ECHO Setting the memory allocation to a maximum of %memSize%
ECHO Using JVM options %jvmOptions%
Tomcat6 //US// --JvmMx=%memSize% --Startup="auto" --JvmOptions=%jvmOptions%
The issue I'm facing is that running the --JvmOptions switch overwrites all the current java options that are set in the tomcat6w.exe.
So my question is, does anyone know how to have the --JvmOptions switch concatenate the passed value to the end of the current value?
Thanks in advance
Could it be as simple as this (if I understand your question correctly)
set memSize=512
REM I removed the quotes and reused the variable in its own definition
set jvmOptions=%jvmOptions%-XX:MaxPermSize=512M
ECHO Setting up tomcat as a service.
call service.bat install
ECHO Setting the memory allocation to a maximum of %memSize%
ECHO Using JVM options %jvmOptions%
REM Added the quotes back here
Tomcat6 //US// --JvmMx=%memSize% --Startup="auto" --JvmOptions="%jvmOptions%"
After a long hard search I did manage to find the answer in a code example. But then to make me feel very foolish I noticed that the answer was also here right under my nose on the Tomcat6 Windows Service How To page. By replacing the -- with ++ the option is concatenated rather than replacing the original.
So the batch file became.
set memSize=512
set jvmOptions="-XX:MaxPermSize=512M"
ECHO Setting up tomcat as a service.
call service.bat install
ECHO Setting the memory allocation to a maximum of %memSize%
ECHO Using JVM options %jvmOptions%
Tomcat6 //US// --JvmMx=%memSize% --Startup="auto" ++JvmOptions=%jvmOptions%
Thanks.
A bit of an old post, but I have to do a bunch of Tomcat uninstalls/installs due another application being upgraded (a term I use loosely) and was trying to figure out how to do something similar to avoid using the UI and ensure consistency.
Some scripting tips (based on my experience so far):
REM -- Use variables for the Tomcat install directory & executable:
set TomcatDir=%ProgramFiles%\Tomcat
set TomcatExe=%TomcatDir%\bin\Tomcat7.exe
REM -- If using multiple instances, turn these in to array
set TomcatInstance[1]=Tomcat7
set TomcatInstance[2]=MyAppInstance1
set TomcatInstance[3]=MyAppInstance2
set TomcatInstance[4]=MyAppInstance3
set TomcatInstance[5]=MyAppInstance4
REM -- When updating/adding Java options and you need to use a ";" between
REM -- values, single-quote the semi-colon, ';' so it isn't intepretted as a CrLf
REM -- For example,
call "%TomcatExe%" //US/%TomcatInstance% ++JvmOptions "-Djava.library.path=%TomcatDir%\bin';'%TomcatDir%\endorsed"
REM -- So to ensure all instances have the same settings...
for /L %I in (1,1,5) do (
call "%TomcatExe%" //US/!TomcatInstance[%I]! ++JvmOptions "-Djava.library.path=%TomcatDir%\bin';'%TomcatDir%\endorsed"
)
REM -- Block scripts sections with setlocal/endlocal
REM -- "EnableDelayedExpansion" allows the above delayed variable expansion to occur
::--==--==--==--==--==--==--==--==--==--==
:Routine_Name
::--==--==--==--==--==--==--==--==--==--==
setlocal EnableDelayedExpansion
echo script commands go here
endlocal
goto :EOF
Note: This would be much easier in an actual scripting language (vbs, js or ps), but I need to leave the script "easy" to modify for whomever takes over for me when I leave my current gig.
FWIW, the how to doc for Tomcat7 is http://tomcat.apache.org/tomcat-7.0-doc/windows-service-howto.html.