Showing posts with label cron. Show all posts
Showing posts with label cron. Show all posts

Friday, 31 March 2017

Linux Server Admin : Bash Kill Processes By Common Name

On my Linux server I've recently wanted to go through and kill a bunch of application instances in one go, this is a server where students have been connecting and running carious programs under python, therefore I want to remove from my processes anything called "python".

We can see these in our bash shell with the command:

sudo ps -aux | grep python

To remove all these programs I create the following bash shell script:

k = 0
for i in $(ps -aux | grep python)
do
  k=`expr $k + 1`
  kill -9 $i  
done
logger -s "Closed $k Python Instances"

Notice k=`exp... this is NOT a single quote (apostrophe) it is the "smart quote" on a UK English keyboard this is the key to the left of the number 1.  It is used to substitute the command into place, so the value counted in K becomes the result of the expression "$k + 1", i.e. K+1.  More about Command Substitution in Bash here.

The call to logger -s places the message both on screen and in syslog for me to review later.

This simply loops through all the applications resident and kills them off, I've saved this as a "sh" file, added executable rights with "sudo chmod +x ./killpythons.sh" and I created this to run as a cron job everyday at 3am (a pretty safe time, unless I have some students burning the candle at both ends).

That's everything about the bash script, for those of you wondering about the students, they're those folks following my learning examples from my book, which you can buy here.


Tuesday, 1 May 2012

Backing up Subversion (Dump, Tar, BZ2)


One of the daily scripts I am running from my bash shell (as a cron job) is to back up my subversion repository in its entirety.

I have a huge drive, so there's no worries about space here, and I can move the daily back up off of my server when the weekly tape backup has a copy of the compressed files.

But, I thought I'd share with you all the script I'm using, as getting it just right, with the options to tar is with the date included is a bit fiddly... Anyway, without further delay, the script:



mkdir /var/tmp/daily
sudo svnadmin dump /svn > /var/tmp/daily/daily.svn
tar cjPf ~/daily_$(date +%Y%m%d).tar.bz2 /var/tmp/daily
rm -rf /var/tmp/daily


Now I can copy the resulting file wherever I want, its in my home directory as

"daily_20120501.tar.bz2"

Note the use of the c j P f in the tar, that's capitol P there... And the use of Y for year, month and day in the date formatter.


And that "/svn" is the source of my Subversion repository


To restore the file into a clean repository just install your server again, extract the daily you want, so you have a "daily.svn" and run the command:


sudo subversion load /svn < /daily.svn


Again, where /svn is the repository path and /daily.svn can be the full path as you extracted the file.

Hope this is useful.