Crontab not really running as root when it should be? - bash

I have Ubuntu and am running under the user "alex". I've got the following bash script running as root with crontab however it sends me an email and it looks like it hasn't run correctly as the result is not present:
/dev/sda - Reallocated_Sector_Ct is
However if I run the crontab job manually from webmin, it works without issues. But when it's scheduled to run, that's when it fails. Maybe it's not really running as root?
Here's my code:
#!/bin/bash
SMARTCHECK=`smartctl -a /dev/sda | grep "Reallocated_Sector_Ct" | awk 'NR==1 {print $10}'`
echo "/dev/sda - Reallocated_Sector_Ct is $SMARTCHECK"
if [ "$SMARTCHECK" != "0" ]; then
mail -s "Failing: /dev/sda" alex <<< "/dev/sda - Reallocated_Sector_Ct is $SMARTCHECK"
fi
Thanks!

There are two possibilities to run scripts using cron:
You use system crontab /etc/crontab. In this case they run as root.
You use users' crontabs, which are accessible using crontab -e. In this case they run with privileges of the user, that has added the command to his crontab.

more possible issues in cronjob scripting.
change all commands in script with full path, especially the command smartctl
check your system has /bin/bash, not /usr/bin/bash, or set the cronjob as:
0 * * * * ~/.profile;/usr/bin/bash YOUR_SCRIPT
check the mail in alex account, if there are any error messages can be found.

Related

Kill process via sh script called by crontab

i wrote a sh file which kills a tomcat process, suppose my shell scrip is in /usr/temp, script looks likethat:
#!/bin/bash
ps -Af | grep "tomcat_something" | grep -v grep | awk '{print$2}' | xargs sudo kill -9
then i created a cron via crontab -e My cron looks likethat (dont pay attention to the time):
10 10 * * * /usr/temp/myshellscript.sh
If i run the sh without cron it works fine, but via cron is not working at all.
I even tryied to run the same shell script with a touch file command and in this case cron works fine, so my doubt is that the problem is the kill command. Can someone help ?
Problem:
sudo in cron job does not work as it expects a password to be entered.
Possible Solutions
Not Recommended as require to give password in plaintext.
Use expect (Quick google or SO search will help you) in your script
and provide sudo's password there.
Run your script as sudo instead of running sudo inside script
In your own crontab, write your command like so:
10 10 * * * echo "your password" | sudo -S /usr/temp/myshellscript.sh
Again, it is not recommended
Best Possible Way: Use roots crontab (only if you have access)
Run the following command:
sudo crontab -e
This opens up root's crontab. sudo is not necessary to run your command in this context since it'll be invoked as root anyway.

What is the result of running 'crontab *'?

I've accidentally ran 'crontab *'. Afterwards, crontab -l and, possibly, crontab -e stopped working properly.
Can someone more knowledgeable in cron help me explain what would happen if 'crontab *' command is ran?
I ran crontab -l | grep * and very few cronjobs showed up. I also ran crontab -e in order to edit the crontab file and it gives me the "Error detected while procedssing 'pathway'" message and "E518: Unknown option: foldmehod=marker" error. It brings me to /tmp/crontab* where * denotes an attempt to create a cron file at tmp folder.
I expect the output of crontab -l | grep "name" to output something but the output doesn't show anything. I suspect it's me running crontab *.
In short, the result would be crontab attempting to install every file that * would have expanded to. Since you did not specify a user with -u first, it would have defaulted to whatever user you were executing the command as. The good news is this only messed up your private crontab.
Cron uses two different crontabs; a system-wide crontab at /etc/crontab and the private, user-specific crontabs at /var/spool/cron. When you use crontab, for example as root, to install a new file, those changes are actually made to /var/spool/cron/root, not the global crontab found at /etc/crontab.
Thus the damage is mitigated to the private crontab of whichever user ran that command, which you can most likely safely remove and rebuild if necessary; but whatever is inside of that private crontab is going to be junk.

script working manually but not via crontab?

Wondered if anyone had any idea why the following problem is occurring, or had any tips where to look…I can run the shell script manually in ssh, but if I set it up to run in crontab i get the problems below.
Server is: FreeBSD 8, and I have access to all root permissions
I have a shell script (Bourne) that runs under the “root” permissions using crontab with the following command:
* * * * * /data/backups/scripts/server_log_check.sh > /data/backups/logs/cron_logs/server_log_check.sh_cron.log
The “server_log_check.sh” script checks to see if “the report server” is running with this command:
if ps -xauww | grep -v grep | grep java | grep www > /dev/null
then
#“reports are running, no need to try to restart it”
Else
/usr/local/etc/rc.d/tomcat55 start #start report server because it is not running
Fi
The problem is occurring on this line: “/usr/local/etc/rc.d/tomcat55 start”, when the script is run using crontab, but if I run the script manually via ssh this line of code runs without a problem, but all the rest of the code in the script executes fine, just not this line. Allternatively, if I paste this line /usr/local/etc/rc.d/tomcat55 start into the ssh command prompt, it runs just fine too.
I changed the “server_log_check.sh” ownership to be “root”, but that didn’t make a difference, and the script "tomcat55" ownership is "www". The crontab entry is being made under the "Root" profile, so, I assumed there is no problem running a file that is owned by a lessor permission such as "www" has
Do you have any ideas why cron is doing this?
Thanks in advance
Try adding the following which will add the error to the log file as well:
* * * * * /data/backups/scripts/server_log_check.sh > /data/backups/logs/cron_logs/server_log_check.sh_cron.log 2>&1
Also change this:
/usr/local/etc/rc.d/tomcat55 start
to:
cd /home/root
nohup /usr/local/etc/rc.d/tomcat55 start &
This should create a nohup.out in /home/root.

How do you run a crontab in Cygwin on Windows?

Some cygwin commands are .exe files, so you can run them with the standard Windows Scheduler, but others don't have an .exe extension so can't be run from DOS (it seems like).
For example I want updatedb to run nightly.
How do I make cron work?
You need to also install cygrunsrv so you can set cron up as a windows service, then run cron-config.
If you want the cron jobs to send email of any output you'll also need to install either exim or ssmtp (before running cron-config.)
See /usr/share/doc/Cygwin/cron-*.README for more details.
Regarding programs without a .exe extension, they are probably shell scripts of some type. If you look at the first line of the file you could see what program you need to use to run them (e.g., "#!/bin/sh"), so you could perhaps execute them from the windows scheduler by calling the shell program (e.g., "C:\cygwin\bin\sh.exe -l /my/cygwin/path/to/prog".)
You have two options:
Install cron as a windows service, using cygrunsrv:
cygrunsrv -I cron -p /usr/sbin/cron -a -n
net start cron
Note, in (very) old versions of cron you need to use -D instead of -n
The 'non .exe' files are probably bash scripts, so you can run them via the windows scheduler by invoking bash to run the script, e.g.:
C:\cygwin\bin\bash.exe -l -c "./full-path/to/script.sh"
hat tip http://linux.subogero.com/894/cron-on-cygwin/
Start the cygwin-setup and add the “cron” package from the “Admin” category.
We’ll run cron as a service by user SYSTEM. Poor SYSTEM therefore needs a home directory and a shell. The “/etc/passwd” file will define them.
$ mkdir /root
$ chown SYSTEM:root /root
$ mcedit /etc/passwd
SYSTEM:*:......:/root:/bin/bash
The start the service:
$ cron-config
Do you want to remove or reinstall it (yes/no) yes
Do you want to install the cron daemon as a service? (yes/no) yes
Enter the value of CYGWIN for the daemon: [ ] ntsec
Do you want the cron daemon to run as yourself? (yes/no) no
Do you want to start the cron daemon as a service now? (yes/no) yes
Local users can now define their scheduled tasks like this (crontab will start your favourite editor):
$ crontab -e # edit your user specific cron-table HOME=/home/foo
PATH=/usr/local/bin:/usr/bin:/bin:$PATH
# testing - one per line
* * * * * touch ~/cron
#reboot ~/foo.sh
45 11 * * * ~/lunch_message_to_mates.sh
Domain users: it does not work. Poor cron is unable to run scheduled tasks on behalf of domain users on the machine. But there is another way: cron also runs stuff found in the system level cron table in “/etc/crontab”. So insert your suff there, so that SYSTEM does it on its own behalf:
$ touch /etc/crontab
$ chown SYSTEM /etc/crontab
$ mcedit /etc/crontab
HOME=/root
PATH=/usr/local/bin:/usr/bin:/bin:$PATH
* * * * * SYSTEM touch ~/cron
#reboot SYSTEM rm -f /tmp/.ssh*
Finally a few words about crontab entries. They are either environment settings or scheduled commands. As seen above, on Cygwin it’s best to create a usable PATH. Home dir and shell are normally taken from “/etc/passwd”.
As to the columns of scheduled commands see the manual page.
If certain crontab entries do not run, the best diagnostic tool is this:
$ cronevents
Just wanted to add that the options to cron seem to have changed. Need to pass -n rather than -D.
cygrunsrv -I cron -p /usr/sbin/cron -a -n
Applied the instructions from this answer and it worked
Just to point out a more copy paste like answer ( because cygwin installation procedure is kind of anti-copy-paste wise implemented )
Click WinLogo button , type cmd.exe , right click it , choose "Start As Administrator". In cmd prompt:
cd <directory_where_i_forgot_the setup-x86_64.exe> cygwin installer:
set package_name=cygrunsrv cron
setup-x86_64.exe -n -q -s http://cygwin.mirror.constant.com -P %package_name%
Ensure the installer does not throw any errors in the prompt ... If it has - you probably have some cygwin binaries running or you are not an Windows admin, or some freaky bug ...
Now in cmd promt:
C:\cygwin64\bin\cygrunsrv.exe -I cron -p /usr/sbin/cron -a -D
or whatever full file path you might have to the cygrunsrv.exe and
start the cron as windows service in the cmd prompt
net start cron
Now in bash terminal run
crontab -e
set up you cron entry an example bellow:
#sync my gdrive each 10th minute
*/10 * * * * /home/Yordan/sync_gdrive.sh
# * * * * * command to be executed
# - - - - -
# | | | | |
# | | | | +- - - - day of week (0 - 6) (Sunday=0)
# | | | +- - - - - month (1 - 12)
# | | +- - - - - - day of month (1 - 31)
# | +- - - - - - - hour (0 - 23)
# +--------------- minute
I figured out how to get the Cygwin cron service running automatically when I logged on to Windows 7. Here's what worked for me:
Using Notepad, create file C:\cygwin\bin\Cygwin_launch_crontab_service_input.txt with content no on the first line and yes on the second line (without the quotes). These are your two responses to prompts for cron-config.
Create file C:\cygwin\Cygwin_launch_crontab_service.bat with content:
#echo off
C:
chdir C:\cygwin\bin
bash cron-config < Cygwin_launch_crontab_service_input.txt
Add a Shortcut to the following in the Windows Startup folder:
Cygwin_launch_crontab_service.bat
See http://www.sevenforums.com/tutorials/1401-startup-programs-change.html if you need help on how to add to Startup. BTW, you can optionally add these in Startup if you would like:
Cygwin
XWin Server
The first one executes
C:\cygwin\Cygwin.bat
and the second one executes
C:\cygwin\bin\run.exe /usr/bin/bash.exe -l -c /usr/bin/startxwin.exe
The correct syntax to install cron in cygwin as Windows service is to pass -n as argument and not -D:
cygrunsrv --install cron --path /usr/sbin/cron --args -n
-D returns usage error when starting cron in cygwin:
$
$cygrunsrv --install cron --path /usr/sbin/cron --args -D
$cygrunsrv --start cron
cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062:
The service has not been started.
$cat /var/log/cron.log
cron: unknown option -- D
usage: /usr/sbin/cron [-n] [-x [ext,sch,proc,parc,load,misc,test,bit]]
$
Below page has a good explanation.
Installing & Configuring the Cygwin Cron Service in Windows:
https://www.davidjnice.com/cygwin_cron_service.html
P.S. I had to run Cygwin64 Terminal on my Windows 10 PC as administrator in order to install cron as Windows service.
Getting updatedb to work in cron on Cygwin -- debugging steps
1) Make sure cron is installed.
a) Type 'cron' tab tab and look for completion help.
You should see crontab.exe, cron-config, etc. If not install cron using setup.
2) Run cron-config. Be sure to read all the ways to diagnose cron.
3) Run crontab -e
a) Create a test entry of something simple, e.g.,
"* * * * * echo $HOME >> /tmp/mycron.log" and save it.
4) cat /tmp/mycron.log. Does it show cron environment variable HOME
every minute?
5) Is HOME correct? By default mine was /home/myusername; not what I wanted.
So, I added the entry
"HOME='/cygdrive/c/documents and settings/myusername'" to crontab.
6) Once assured the test entry works I moved on to 'updatedb' by
adding an entry in crontab.
7) Since updatedb is a script, errors of sed and find showed up in
my cron.log file. In the error line, the absolute path of sed referenced
an old version of sed.exe and not the one in /usr/bin. I tried changing my
cron PATH environment variable but because it was so long crontab
considered the (otherwise valid) change to be an error. I tried an
explicit much-shorter PATH command, including what I thought were the essential
WINDOWS paths but my cron.log file was empty. Eventually I left PATH alone and
replaced the old sed.exe in the other path with sed.exe from /usr/bin.
After that updatedb ran to completion. To reduce the number of
permission error lines I eventually ended up with this:
"# Run updatedb at 2:10am once per day skipping Sat and Sun'
"10 2 * * 1-5 /usr/bin/updatedb --localpaths='/cygdrive/c' --prunepaths='/cygdrive/c/WINDOWS'"
Notes: I ran cron-config several times throughout this process
to restart the cygwin cron daemon.

Creating crontab via Capistrano instead of using crontab -e

I would like to include cron tasks in my Capistrano deployment files instead of using the following command to manually edit the crontab file:
crontab -e [username]
Is there a script I could use within the Capistrano run command to set the contents of the crontab?
Check out the Whenever gem -- this may be stretching beyond what you're intending to do, but it uses very simple (Ruby) syntax and makes it dead simple to setup cron jobs within a capistrano deployment script.
On my linux box
crontab -u userName -l > fileName
lists the crontab file for userName in fileName.
Then I would use a ruby (or another language) script to update the file.
Finally I would use
crontab -u userName fileName
to update the crontab for userName
given that you have a variable set that is :new_user
and that you are using use_sudo true
desc "install crontab"
task :install_crontab do
run "echo '0 23 * * * /home/#{new_user}/scripts/backup_#{new_user}.sh' | #{sudo} crontab -u #{new_user} -"
end
def crontab_add(line)
config = capture(%Q{crontab -l}).split "\n"
return if config.include? line
run %Q{(crontab -l; echo "#{line}") | crontab -}
end
Why not include a crontab that can be installed to /etc/cron.d?

Resources