Notifications on next ssh login

2019-09-05 17:26发布

问题:

This is a hypothetical question because I'd like to know if it's even possible before I delve in to scripting it, but is it theoretically possible to have the output of a script/process (in particular one run via cron for instance) spit out in to terminal on the next ssh login?

Some pseudocode that I hope illustrates my point:

#!/bin/bash

# Download latest example of a database (updated automatically and periodically)
wget -mirror "http://somedatabase/database_latest

# Run a command that generates an output for a set of files queried against the latest database)
for file in /some/dir/*;
do
    command -output $file.txt -database database_latest
done

# Now for the bit I'm more interested in.
# If the database has been updated, the 'output.txt' 
# for each file will be different.
# So, using diff...:

if [ diff $file.txt $file_old.txt == 1 ] # where file_old.txt is 
                                         # the output of the command the 
                                         # last time it ran for that file.
    then
        mv $file_old ./archive/ # Keep the old file but stash it in a separate dir
    else
        break
fi

 # Make some report file from all of the outputs
 cat *.txt > report.txt

So my question being, is it possible to have the script 'inform me' next time I log in to our server, if any differences were found for each file? There are a lot of files, and the 'report.txt' would become large quickly, so I only want to check it if differences are found.

回答1:

How about this:

  • create three directories: new, cur, old
  • your weekly cronjob writes data to new. This script should delete everything from new before writing new data. Or else you won't be able to notice that a file is missing
  • cur contains the last version of the data that you looked at or consideret
  • old contains the previous version of the data

Each time you log on, run:

#!/bin/bash

# clear the archive
rm old/*

# move all the old files to the archive
cp cur/* old

# move all the new files to the location of the old
cp new/* cur

# show which files have changed between
diff -q cur old | tee report.txt

The diff-command will print which files are new, which are missing and which are changed. Output from diff will also be in report.txt. The cur-directory will contain all files from the last run and you can look closer at these in an editor, or you can compare them to the previous version in old. Note that if a file is missing in new, it won't be deleted from cur. The next time you log on, you will lose the contents of the old-directory. If you want to keep a history of all previous results, this should be managed by the weekly cronjob, not the login-script (you want to store a separate version each time you generate the data, not each time you log in)



标签: ssh cron diff