Cron job fails to execute python script that writes to text file - python-3.x

I need to run a python script on a remote server (I'm not the owner of this server, so I cannot check var/log/syslog). The script is put in a folder with other files that the scripts depends on to be able to run. The script will write out a text files, the information being written includes runtime of the script.
If I executed the script manually, it will write text file with all correct information. However, when I set a test cron job to make sure my script run and the output file looks like what I'd like, the output file has only one line that includes a very small float which I assume to be the runtime of the script. The default python version of the server is python 2.7. However, my script need python3 to run. Below is the crontab command that I use
# crontab command
# the time is just an example
23 23 13 4 6 /usr/bin/python3 /home/user_name/path/to/file.py
I have tried using just python3 files.py and python3.5 files.py, same result for all cases.
All the files in the folder I tried to run my scripts and my script itself is chmod 707
Also, side question, I'm sharing this server with other people; however, I don't want them to be able to open my files, what chmod should I set my files and folder to so that cron would still be able to execute my files and people won't be able to view it (beside the owner of the server)

First, permissions:
Every user has a crontab, and the entries in a user's crontab run as that user.
The three numbers in a files permission are user, group and other.
Typically a user has their own group, and they are the only member of it.
So that means if you want to keep your stuff to your self, only grant permissions to your user (and optionally, your group, which is the same thing if you're the only member). Your crontab will have no trouble accessing anything your user can access.
Thus, give all the relevant directories and all the text files ownership of user_name:user_name and permissions of 660 (only you can read and write to them). Give all the executable files the same ownership but permissions of 770 (so you can also execute them).
Then, if you have ssh access, just execute /usr/bin/python3 /home/user_name/path/to/file.py from the command line to see where it's falling over. Assuming you don't have ssh access, then you need to capture the output from the crontab execution. Use this crontab line:
23 23 13 4 6 /usr/bin/python3 /home/user_name/path/to/file.py > /home/user_name/output.txt 2>&1
That will redirect all STDERR to STDOUT (the 2>&1 bit) and redirect STDOUT to output.txt (the > bit).
Let that run and check the contents of output.txt. I'm guessing you'll find Python had trouble getting access to something and bombed out before writing much to the file.

Related

linux file access read/write by root, execute by all

I'm trying to create a shell script that can only be read/written by root but can be executed by everyone. I created a file test.sh, set ownership to "chown root:me test.sh" and set permissions to "chmod 711 test.sh", hoping this would do the trick. However, this results in a file that always needs sudo in order to execute. Is it possible to edit the rights such that anyone (without using sudo) can execute the script, but only root (using sudo) can read/write the file?
this is not possible to be achieved, at least with shell scripts.
In fact, at the moment of the execution, the shell program (I presume Bash) needs to read the content of the shell file and the process runs with your user name and permissions.
Having said this, the BASH program (ZSH, SH or any other shell follow the same rules) needs to be able to read the content of the file and this can be achieved only by granting read privileges +r. So, the bare minimum would be a 755 permission model.
An alternative is to run an actual program which does the job and wouldn't require read permission in order to be executed. But this is a totally different pattern.
This response explains it as well.
https://unix.stackexchange.com/questions/34202/can-a-script-be-executable-but-not-readable

What is preventing my cron job from running

I have created a list of cron jobs (see below) using sudo crontab -e in the root crontab file. When I run the commands individually on the command line, they work fine, however none of the jobs are run by cron. Any help would be appreciated. Do I need to add something else into the crontab file?
48 * * * * sudo gzip -k /calcservergc.log.*
49 * * * * for file in /calcservergc.log.*.gz; do sudo mv $file $(hostname).${file:1}; done
50 * * * * sudo rm $(hostname)..log..gz
sudo
The sudo command may not work in a crontab. Generally you need a password to run sudo but there might be a way to have it run without a password when running in a cron job. This would not be recommended however to attempt.
cron
You'll need to run the cron as a user that has access to do what you need to accomplish. Cron runs with a short list of specific paths. By default that list is pretty short. On a linux box I use the path is /sbin:/usr/sbin:/bin:/usr/bin.
Also, the paths need to be more specific. Cron doesn't run as a normal user so you have to be more specific with paths and output of those commands.
For instance, on the first command, where will the gzip file be placed?
logrotate
It looks like you're trying to zip a log file, then move log files, then remove old log files - this is exactly what logrotate accomplishes. It would be worth installing. Logrotate solves problems like the log file being opened when you run this command - generally the process that has the log file opened doesn't lose the file handle even if you rename it so the log continues to be written to even after you move it. It also handles the problem of keeping an archive of the recent log files, like syslog.1.gz, syslog.2.gz, syslog.x.gz or as many back as you have storage space for or want to keep for posterity.
Summary
Don't use sudo in cron
Be specific in paths when running commands in cron
Use logrotate to accomplish this specific task in your question
I don't have 50 points of reputation so can't comment on your question, so I'll try to say it in one shot.
I detect a possible problem with your 3 commands each called at one minute apparts. Let's say the first operation takes more than one minute to run (shouldn't happen but in theory it could), your second call won't work or worst, it could work on half the data). You don't want to loose time by, lets say, put 5 minutes delay between your commands, that would be a lost of time.
What you could do is create a shell script in which you put the 3 commands. This way it will prevent your operations to "crash". So just put your 3 commands in a script shell and they will be executed one after the other.
Then put your file in a place like /bin (you can also create a symbolic link with ln -s) and call your script with cron. (Be careful with the paths in the script shell)
Now, for the sudo problem... well even if you put it in a shell script, you would still need to pass your sudo password, and cron runs in the background so you won't be able to enter your password.
You could try two solutions. Change the rights on the containing folder where your files are stored (by using chmod -r 777 or chmod 755 on the folder) or move/copy your files in a directory where you have access to read and write.

What step am I missing in creating a cron job?

I can't seem to run cron jobs and I can't figure out why. I'm new to this so I might be making an amateur mistake.
First, I create a script and call it 'test.sh', putting it in the /usr/local/bin folder. The script contains:
#!/bin/bash
echo "This test works!"
Next, I create a file called 'randomtest' in the /etc/cron.d folder. The file contains:
00 09 * * * root /usr/local/bin/test.sh >> /var/log/test.log
I expect the cron job to run at 9:00 AM every day, but for some reason, it doesn't. I also don't get a log file as expected. I checked the permissions on the test.sh file and it's currently set to 755, which should work.
Is there something I'm doing wrong? Am I missing a crucial element? Do I need to add my 'randomtest' file to the crontab or something?
Reload the cron daemon by using /etc/init.d/crond reload.
(Even if it's already running!)
The problem is that you're messing around with the /etc/cron.d directory rather than using the crontab command.
Unless you definitely need a cron job to run as root, just add it to your own crontab using the crontab command. You can use crontab -e to edit it, but it's better to keep your own copy of your crontab (ideally under version control) and use the crontab filename version of the command to install it. This ensure that the cron daemon will be aware of the update, and that any syntax errors will be caught. It also means you don't need to run any commands as root; avoiding root commands unless they're actually necessary is always a good idea.
Note that system crontabs (those in /etc/crontab and under the /etc/cron.d directory -- though those locations are implementation details that you ideally shouldn't have to worry about) have a different syntax than user crontabs; each line has an extra field that specifies the account under which the commans is to be run.
If you need a command to run as root, you can either update a system crontab file (carefully!), or you can set up a user crontab for the root user, using the normal crontab command as you would for any user account.

I want a shell script to be executable but not readable

I created a script which I want other users on our shared system to execute but not read. I set the permissions as executable for all but revoked the R/W rights.
---x--x--x 1 dilletante staff 0 2013-04-02 11:42 expect.sh
However the script Fails to execute...The reason is simple.. The interpreter also needs to read the script
I want a workaround if any..Can I embed it into some compiled language..Would that work?
If yes, could you point to the resources where I can learn how to do so..
The shell has to be able to read a script to execute it. You are asking for the impossible if it is a script.
You can certainly use 111 permission on an executable program (as produced by the ld command, typically invoked by the compiler of your chosen compiled implementation language). The owner can always change the permission to read the program if they want to, but it is more conventional to use 511 than 111 permission.
There are often compilers for a specific script language that will generate a C program equivalent to the script:
Compilers for shell scripts.
How to compile a Linux shell script as a binary.
Compiling shell scripts.
shc — shell script compiler.
Etc.
If you want this for other users try sudo
Example:
Change execution right
chmod 500 /usr/bin/script.bash
ll /usr/bin/script.bash
-r-x------ 1 <USER> <GROUP> 1174 23. Jan 13:24 /usr/bin/script.bash
As root change sudoers
visudo
## Allows ALL to run /usr/bin/script.bash as <USER> without password
## The asterisk is if you want to use any commandline parameters
ALL ALL=(<USER>) NOPASSWD: /usr/bin/script.bash *
Run script with sudo
sudo /usr/bin/script.bash <PARAMETERS>
For further information concerning sudo read the sudo manpages
There's an alternative to securing your shell scripts. Since the goal here is to make sure no one can read or alter them, you may want to give the following link a try:
http://www.kinglazy.com/shell-script-encryption-kinglazy-shieldx.htm
On the above page, all you have to do is submit your shell script (you can submit a sample script first for your peace of mind). A zip file will be generated for you.
Installation:
wget link-to-the-zip-file
unzip the-newly-downloaded-zip-file
cd /tmp/KingLazySHIELD
./install.sh /var/tmp/KINGLAZY/SHIELDX-(name-of-your-script) /bin -force
What the above install command will do for you is:
It'll install the encrypted script in the directory /var/tmp/KINGLAZY/SHIELDX-(name-of-your-script).
It'll place a link to this encrypted script in /bin - that way, you need not type the absolute path to your script each time you want to run it.
Ensures NO ONE can modify the script - Any attempts to modify the encrypted script will render it inoperable...until the attempts are removed.
Ensures absolutely NO ONE can make working copies of it. No one can copy your script to a secluded location and try to screw around with it to see how it works. If they try to, it'll abort and will not run.
I made my own bash obfuscator to overcome some shortcomings of shc which really bugged me (the primary one as being able to see the script in almost clear text with the use of ps).
You could have a look if https://github.com/louigi600/obash serves you any better then shc.

script for cron.daily

I need to have my Java program run on a linux box once a day. So I created a simple file with just one line:
java -jar /opt/location/my_jar.jar
and put it in etc/cron.daily, assuming it would run once a day. But it doesn't run at all. I tried both to have the .sh extension, or simply the file name with no extension. Still, no luck.
I googled it and I'm getting quite a bit of conflicting info. Can someone please help?
EDIT:
I'm summarizing the place it is right now, based on the answers given by Satish and Mithrandir.
1.I created the run_conversions script using vi, to get over the problem with the end of line character on windows. Now the script is
#!/bin/sh
/usr/bin/java -jar /opt/location/my_jar.jar
2.I put it in /etc/cron.hourly.
3.Checking the log at /var/log/cron I'm seeing the it's starting run_conversions and finishing run_conversions every hour. So far so good.
4.But it doesn't seem like my jar file is running. I know this because when it's running properly it should update a database -- and the database is not updating.
5.Here's the strange thing: when I'm running cron.hourly manually, but calling
run-parts /etc/cron.hourly
the jar file is hit propertly, and the database is updating.
To sum it up: when running it through run-parts, it works. When leaving it to run hourly by itself, it doesn't.
Any ideas?
EDIT 2:
Following advice from Satish, Mithrandir and vahid I changed my run_conversions_loc to look like this:
#!/bin/bash
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bexport SHELL=/bin/bash
/usr/bin/java -jar /opt/tf/conversions/aff_networks2.jar > /opt/tf/conversions/runconversions.txt
I removed the script from cron.hourly and added this line to crontab:
*/10 * * * * /opt/tf/conversions/run_conversions_loc
The script now runs every 10 minutes, and is registered in the cron log like this:
Feb 24 09:30:01 backsome CROND[7933]: (root) CMD (/opt/tf/conversions/run_conversions_loc)
So far it looks good. But the database -- which it should update -- isn't updated.
Looking deeper into it, the jar file, aff_networks2.jar is looking for an ftr.properties file in the local directory -- the same directory where it's at. The file exists in this directory. But it's not read properly. I know this because in the output file, runconversions.txt, the value that should be read from the properties file is null.
Two things to complete the picture:
Everything in the conversions directory has 777 permissions. I know it's not recommended to give such extended permissions but I wanted to make sure (at least try) it's not the issue.
When I run the script from the shell by calling ./run_conversions_loc it runs, finds the properties file, and updates the database. I am logged into the shell as root, and I also created all the relevant files as root, and installed as root the line for calling the script in crontab.
Any ideas why isn't cron reading the properties file?
its probably your environment variables
does it work as the current user logged in when executing the script ?
if so
run:
env|egrep "(^PATH=|^SHELL=)"|awk '{print "export "$1}'
then take the output and put it on the top of your script and try another cron in 2 minutes from now to see if it worked
Updated answer in response to Eddy's Comment 24th Feb 2013.
I want to give you a crash course on crontab.
setting up crontab can be done via global /etc/crontab or under user as crontab -e (to edit specific user's cron) or crontab -l (lists - stored in /var/spool/cron for each user)
I see you are trying to attempt a run ever 10 minutes which is fine in /etc/crontab
The reason why I suggested giving the entire class path of your current shell is because most of the time the script is trying to use a unix command that is not available as part of the crontab's PATH (which resides right at the very top of /etc/crontab file itself)
To debug path issues its usually a good idea to watch the mailbox of the user that crontab is executing the task as :
so tail -100 /var/spool/mail/root and looking out for any messages related to that cron task as well as the cron logs itself as someone has suggested -
I do not think your problem is paths here though..
You are trying to run a java jar file and it may be that your jar file needs other files in that conversion folder and that when you are running it you are already in that folder....
so in your script you could run
cd /opt/tf/conversions/;
/usr/bin/java -jar aff_networks2.jar > /opt/tf/conversions/runconversions.txt
But since this is such a small script you could get away with placing the entire thing as a cron entry and bypassing a shell script altogether something like this
*/10 * * * * root cd /opt/tf/conversions/; /usr/bin/java -jar aff_networks2.jar > /opt/tf/conversions/runconversions.txt
Hope this helps solve this issue
Solution with example:
Run command manually on command line:
[root#04 cron.daily]# /usr/bin/java -jar /root/HelloWorld.jar
Hello World #1
Let create a script in /etc/cron.daily/test.sh and give execute permission:
#!/bin/bash
/usr/bin/java -jar /root/HelloWorld.jar
Notes: run dos2unix in case you have dos character issue or error /bin/bash^M: bad interpreter: No such file or directory
[root#04 cron.daily]# unix2dos test.sh
unix2dos: converting file test.sh to DOS format ...
Test it, voila!!
[root#04 cron.daily]# run-parts /etc/cron.daily
/etc/cron.daily/ldiscan:
kcore: Value too large for defined data type
/etc/cron.daily/test.sh:
Hello World #1
Change your file to:
#!/bin/sh
/usr/bin/java -jar /opt/location/my_jar.jar
Check if /usr/bin/java is actually where the command is istalled (which java).
Change the permissions of you file to be executable:
chmod +x /opt/location/my_jar.jar

Resources