Python Code to Check If Service Is Running or Not.

Python code to check if service is running or not.?

Simply by using os.system(). You then get the return code of the execution; 0 means running, 768 stopped

>>> import os
>>> stat = os.system('service sshd status')
Redirecting to /bin/systemctl status sshd.service
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2017-10-05 09:35:14 IDT; 29s ago
Docs: man:sshd(8)
man:sshd_config(5)
Process: 620 ExecStart=/usr/sbin/sshd $OPTIONS (code=exited, status=0/SUCCESS)
Main PID: 634 (sshd)
CGroup: /system.slice/sshd.service
└─634 /usr/sbin/sshd
>>> stat
0 <-- means service is running

>>> os.system('service sshd stop')
Redirecting to /bin/systemctl stop sshd.service
0 <-- command succeeded

>>> os.system('service sshd status')
Redirecting to /bin/systemctl status sshd.service
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Thu 2017-10-05 09:41:58 IDT; 10s ago
Docs: man:sshd(8)
...
768 <-- service not running

The return code is the one returned from the execution. From the service manpage:

EXIT CODES
service calls the init script and returns the status returned by it.

So it's up to the init script executed. You can safely say any return code other than 0 means the service is not running.

You can either check if the process is running instead using:

>>> os.system('ps aux | grep sshd | grep -v grep | wc -l')
2
>>> os.system('ps aux | grep sshd123 | grep -v grep | wc -l')
0

How to check if a service is running using WMI in Python?

This can easily be done using WQL in win32com.client module.

For example,

from win32com.client import GetObject
WMI = GetObject('winmgmts:')

if len(WMI.ExecQuery('select * from Win32_Process where Name like "%s%s"' % ("process_name",'%'))) > 0:
pass

To do so in your way, do something like this using WQL to check if that service is indeed running or not.

You can see the tutorial if it helps.

Check if a Windows Service exists with Python

It seems like a Try-Except block would be the easiest solution:

try: 
win32serviceutil.QueryServiceStatus('myservice')
except:
print "Windows service NOT installed"
else:
print "Windows service installed"

how to check service running on other server with python

You can use the following code for your service. i think these codes will help you
in your problem.

            ip = your_ip
server_user = your_serviceuser
server_pass = your_pass
command = f"net use \\\\{ip} {server_pass} /USER:{server_user}"
os.system(command)
command = f"SC \\\\{ip} query SQLSERVERAGENT"
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output, err = process.communicate()

output = str(str(str(str(output)[2:-1].replace(' ', '')).replace('\\t', '')).replace('\\r', '')).split('\\n')
if output[3] != 'STATE:4RUNNING':
print("service is running...")

Check if a process is running or not on Windows?

You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. psutil is an excellent cross-platform python module cable of enumerating all the running programs on a system.

import psutil    
"someProgram" in (p.name() for p in psutil.process_iter())

Need a hand with this script to check service status

Using os.system() only give you back the error code of the command, not the result of the command. As stated in the documentation for os.system(), you should look into using the subprocess module for running OS commands and retrieving the results of them.

import subprocess
check = subprocess.run(["systemctl", "is-active", "webmin"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if check.stdout == b"active": # Your result may end in a newline: b"active\n"
print("Webmin is active!")

FastAPI as a Windows service is running but can't get in 127.0.0.1:5000

Ok I got the solution.

Steps:

  1. Install service with nssm from cmd as admin
  2. Insert python.exe path, then main.py(api filename) path and at last put file name main.py in the argument.
  3. After install, start the service and check in the browser.

Check my gitlab link for details.

how can you know if the python file is run directly and not from the command line?

The second answer provided in Detect if python program is executed via Windows GUI (double-click) vs command prompt functions correctly for the program to check if the program was run thru a GUI works. Thanks for the help guys!



Related Topics



Leave a reply



Submit