I am currently using linux. I have a python script which I want to run as a background service such as the script should start to run when I start my machine.
Currently I am using python 2.7 and the command 'python myscripy.py' to run the script.
Can anyone give an idea about how to do this.
Thank you.
It depends on where in the startup process you want your script to run. If you want your script to start up during the init process, then you can incorporate it into the init scripts in /etc/init.d/ The details will depend on what init system your system is running. You might be on a system V init (https://en.wikipedia.org/wiki/Init) or on systemd (https://wiki.debian.org/systemd), or possibly some other one. If you don't need your script to run at the system level, then you could kick the script off when you log in. To do that, you'd put it in ~/.profile if you log in using a terminal. Or, if you use a desktop environment, then you're going to be doing something in ~/.local/XSession (if I recall correctly). Different desktop environments are going to have different ways to specify what happens when a user logs in.
Hope this helps! Maybe clarify your needs if you want more detail.
You can create init script in /etc/init/ directory
Example:
start on runlevel [2345]
stop on runlevel [!2345]
kill timeout 5
respawn
script
exec /usr/bin/python /path/to/script.py
end script
Save with .conf extension
Related
I need to write a script in python which stops a service running in EC2 instance just before it reboots.
What should be the approach here?
Suppose service name is abc.
to manually stop this service, I execute:
service abc stop
I want to automate this before instance goes for reboot.
Help me with this
The cron scheduler allows you to use #reboot in place of a schedule string. So, write your script and then crontab -e and add the following:
#reboot /path/to/python /path/to/reboot_script.py
For the reboot script, python isn't really your best choice. I would write it using a bash script, looking something like this:
#!/bin/bash
service abc stop
If you must use python, you could use invoke:
from invoke import run
run('service abc stop', hide=True, warn=True)
Edit:
To run this BEFORE reboot, make a shell script called K99kill_service and add it to your /etc/rc6.d directory. These scripts are executed before reboot or shutdown. It's important that it is named as above to make sure it runs at the right time and doesn't interfere with other shutdown scripts.
Courtesy : https://opensource.com/life/16/11/running-commands-shutdown-linux
See the link, it explains in very much detail on, How to shutdown services in linux before shutdown for both SysVinit and Systemd ?
I know this is an exact copy of this question, but I've been trying different solutions for a while and didn't come up with anything.
I have this simple script that uses PRAW to find posts on Reddit. It takes a while, so I need it to stay alive when I log out of the shell as well.
I tried to set it up as a start-up script, to use nohup in order to run it in the background, but none of this worked. I followed the quickstart and I can get the hello word app to run, but all these examples are for web applications and all I want is start a process on my VM and keep it running when I'm not connected, without using .yaml configuration files and such. Can somebody please point me in the right direction?
Well, at the end using nohup was the answer. I'm new to the GNU environment and I just assumed it didn't work when I first tried. My program was exiting with an error, but I didn't check the nohup.out file so I was unaware of it..
Anyway here is a detailed guide for future reference (Using Debian Stretch):
Make your script an executable
chmod +x myscript.py
Run the nohup command to execute the script in the background. The & option ensures that the process stays alive after exiting. I've added the shebang line to my python script so there's no need to call python here
nohup /path/to/script/myscript.py &
Logout from the shell if you want
logout
Done! Now your script is up and running. You can login back and make sure that your process is still alive by checking the output of this command:
ps -e | grep myscript.py
I'm looking to create a script in python that initiates an SSH session with a server. I know it has to be a simple process i'm just not sure where to start. My ultimate plan is to automate this script to run on startup. i am not even sure python is the best way to go i just know it comes preloaded on raspbain for the pi.
A simple bash script would be better suited to the task. It is possible with python, but there's no obvious reason to make it harder than necessary.
From
write a shell script to ssh to a remote machine and execute commands:
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done
From how do i run a script at start up (askubuntu):
You will need root privileges for any the following. To get root, open
a terminal and run the command
sudo su
and the command prompt will change to '#' indicating that the terminal
session has root privileges.
Alternative #1. Add an initscript.
Create a new script in /etc/init.d/myscript.
vi /etc/init.d/myscript
(Obviously it doesn't have to be called "myscript".) In this script,
do whatever you want to do. Perhaps just run the script you mentioned.
#!/bin/sh
/path/to/my/script.sh
Make it executable.
chmod ugo+x /etc/init.d/myscript
Configure the init system to run this script at startup.
update-rc.d myscript defaults
Alternative #2. Add commands to /etc/rc.local
vi /etc/rc.local
with content like the following.
# This script is executed at the end of each multiuser runlevel
/path/to/my/script.sh || exit 1 # Added by me
exit 0
Alternative #3. Add an Upstart job.
Create /etc/init/myjob.conf
vi /etc/init/myjob.conf
with content like the following
description "my job"
start on startup
task
exec /path/to/my/script.sh
Depending on what you do with the ssh connection, if it needs to stay open over the entire up time of the device, you will need to use some more trickery however (ssh connections are autoclosed after a period of inactivity).
I have 3-4 python scripts which I want to run continuously on a remote server(which i am accessing through ssh login).The script might crash due to exceptions(handling all the exceptions is not practical now), and in such cases i want to immediately restart the script.
What i have done till now.
I have written a .conf file in /etc/init
chdir /home/user/Desktop/myFolder
exec python myFile.py
respawn
This seemed to work fine for about 4 hours and then it stopped working and i could not start the .conf file.
Suggest changes to this or i am also open to a new approach
Easiest way to do it - run in infinite bash loop in screen. Also it's the worst way to do it:
screen -S sessionName bash -c 'while true; python myFile.py ; done'
You can also use http://supervisord.org/ or daemon by writing init.d script for it http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
If your script is running on an Ubuntu machine you have the very convenient Upstart, http://upstart.ubuntu.com/
Upstart does a great job running services on boot and respawning a process that died.
I have written a module in Python and want it to run continuously once started and need to stop it when I need to update other modules. I will likely be using monit to restart it, if module has crashed or is otherwise not running.
I was going through different techniques like Daemon, Upstart and many others.
Which is the best way to go so that I use that approach through out my all new modules to keep running them forever?
From your mention of Upstart I will assume that this question is for a service being run on an Ubuntu server.
On an Ubuntu server an upstart job is really the simplest and most convenient option for creating an always on service that starts up at the right time and can be stopped or reloaded with familiar commands.
To create an upstart service you need to add a single file to /etc/init. Called <service-name>.conf. An example script looks like this:
description "My chat server"
author "your#email-address.com"
start on runlevel [2345]
stop on runlevel [!2345]
env AN_ENVIRONMENTAL_VARIABLE=i-want-to-set
respawn
exec /srv/applications/chat.py
This means that everytime the machine is started it will start the chat.py program. If it dies for whatever reason it will restart it. You don't have to worry about double forking or otherwise daemonizing your code. That's handled for you by upstart.
If you want to stop or start your process you can do so with
service chat start
service chat stop
The name chat is automatically found from the name of the .conf file inside /etc/init
I'm only covering the basics of upstart here. There are lots of other features to make it even more useful. All available by running man upstart.
This method is much more convenient, than writing your own daemonization code. A 4-8 line config file for a built in Ubuntu component is much less error prone than making your code safely double fork and then having another process monitor it to make sure it doesn't go away.
Monit is a bit of a red herring. If you want downtime alerts you will need to run a monitoring program on a separate server anyway. Rely on upstart to keep the process always running on a server. Then have a different service that makes sure the server is actually running. Downtime happens for many different reasons. A process running on the same server will tell you precisely nothing if the server itself goes down. You need a separate machine (or a third party provider like pingdom) to alert you about that condition.
You could check out supervisor. What it is capable of is starting a process at system startup, and then keeping it alive until shutdown.
The simplest configuration file would be:
[program:my_script]
command = /home/foo/bar/venv/bin/python /home/foo/bar/scripts/my_script.py
environment = MY_ENV_VAR=FOO, MY_OTHER_ENV_VAR=BAR
autostart = True
autorestart = True
Then you could link it to /etc/supervisord/conf.d, run sudo supervisorctl to enter management console of supervisor, type in reread so that supervisor notices new config entry and update to display new programs on the status list.
To start/restart/stop a program you could execute sudo supervisorctl start/restart/stop my_script.
I used old-style initscript with start-stop-daemon utility.Look at skel in /etc/init.d