Created
April 27, 2017 12:45
-
-
Save clamytoe/b5c05e5315d079f8e51a6d03e42a871c to your computer and use it in GitHub Desktop.
Script that I use to start/stop processes at work.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.6 | |
from sys import argv, exit | |
def start_stop(process): | |
"""Starts/Stops a process | |
It stops the process that is passed to it by killing it's process ID. If no | |
process ID is found, then the process is started. | |
""" | |
from subprocess import CalledProcessError, check_output, os, signal | |
root = 0 # root always runs with a guid of 0 | |
user = os.getuid() # who is running this script | |
# Ensure that we are running as root | |
if user == root: | |
# Attempt to kill the process | |
try: | |
pid_list = map(int, check_output(["pidof", process]).split()) | |
for pid in pid_list: | |
os.kill(pid, signal.SIGKILL) | |
print(f'TERMINATED: [{pid}] {process}') | |
except CalledProcessError: | |
# If the process is not running, start it | |
print(f'STARTING: {process}:') | |
os.system(process) | |
else: | |
usage() | |
def usage(): | |
# Let the user know that this script needs to run as root | |
print('Use sudo to run this script!\n') | |
if len(argv) > 1: | |
print(f' sudo {argv[0]} {argv[1]}\n') | |
else: | |
print(f' sudo {argv[0]}\n') | |
exit() | |
def main(): | |
"""Run as a script | |
Takes the commandline argument for the process to start/stop. | |
""" | |
if len(argv) == 1: | |
usage() | |
else: | |
start_stop_proc(argv[1]) | |
if __name__ == '__main__': | |
# Start the script if it is being ran from the command line | |
start_stop("motion") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Specifically I use it to start/stop a motion activated web cam when I'm out of my office.