我有两个脚本位于/home/luis,用户具有管理员权限。一个是。sh和一个是一些ruby代码,我试图执行在同一文件夹中生成一个txt文件。
linux_users.rb
class User
attr_reader :username, :home_directory
def initialize(username, home)
@username = username
@home_directory = home
end
end
unix_users = []
File.open('/etc/passwd').readlines.each do |line|
split = line.split(':')
unix_users << User.new(split[0], split[5])
end
file = File.open("users.txt", "w")
unix_users.each do |user|
file.puts "#{user.username}:#{user.home_directory}"
end
file.close
md5_validation.sh
#!/bin/bash
/home/luis/.rbenv/shims/ruby /home/luis/linux_users.rb
if [[ ! -f "/var/log/current_users.txt" ]] #If the file current_users doesn't exist --> Create it
then
echo "creating current_users.txt and user_changes.txt"
touch /var/log/current_users.txt /var/log/user_changes.txt
fi
md5_users="$(md5sum "/home/luis/users.txt" | cut -d' ' -f1)" #Storing the md5 hash into a variable
if [ -s /var/log/current_users.txt ] #If current_users.txt is not empty,
then
current_users_txt_hash=`cat /var/log/current_users.txt` #collect it's content.
if [ "$md5_users" == "$current_users_txt_hash" ] #if the linux users hash match the old one, fine,
then
echo "No changes in the MD5 hash detected"
else #otherwise store the new hash into current_users.txt
echo "$md5_users" > "/var/log/current_users.txt"
echo "A change occured in the MD5 hash"
now=$(date +"%m_%d_%Y_%T") #creating a user_changes.txt file that logs the changing
echo "$now changes occured" > "/var/log/user_changes.txt"
fi
else
echo "Storing the MD5 hash into the filename.." #store the linux users hash into the current_users.txt (first script launch)
echo "$md5_users" > "/var/log/current_users.txt"
fi
如果我从终端运行。/md5_validation.sh,一切正常,ruby代码被执行。但是,当我用sudo systemctl start cron启动crontab时,1分钟后,只执行。/md5_validation.sh bash代码和
行/home/luis/.rbenv/shims/ruby /home/luis/linux_users.rb
包含的。sh文件脚本被忽略了,它不会生成我需要的TXT文件。
用于创建crontab的命令:
sudo crontab -e
crontab的内容
*/1 * * * * /usr/bin/sh /home/luis/md5_validation.sh
更多有用信息
➜ log whereis sh
sh: /usr/bin/sh /usr/share/man/man1/sh.1.gz
➜ log whereis ruby
ruby: /home/luis/.rbenv/shims/ruby
试试这个:
#!/bin/bash
cd /home/luis
/home/luis/.rbenv/shims/ruby /home/luis/linux_users.rb
# ...
如果它不工作。也许真的有问题。
您可以检查/var/log/syslog
如果看到日志中包含(CRON) info (No MTA installed, discarding output)
将命令行输出重定向到一个随机文件中以查看日志:
*/1 * * * * /usr/bin/sh /home/luis/md5_validation.sh > /home/luis/cron.log
# btw, you can dismiss the /usr/bin/sh if you do chmod +x md5_validation.sh
# so it can be little shorter
# */1 * * * * /home/luis/md5_validation.sh > /home/luis/cron.log
如果出现任何错误,请查看cron.log。