SSH – Force Command execution on login even without Shell

后端 未结 4 1649
粉色の甜心
粉色の甜心 2021-01-31 20:39

I am creating a restricted user without shell for port forwarding only and I need to execute a script on login via pubkey, even if the user is connected via ssh -N user@ho

4条回答
  •  日久生厌
    2021-01-31 21:36

    I am the author of the OP. Also, you can implement a simple logwatcher as the following written in python3, which keeps reading for a file and executes a command when line contains pattern.

    logwatcher.python3

    #!/usr/bin/env python3
    
    # follow.py
    #
    # Follow a file like tail -f.
    
    import sys
    import os
    import time
    
    def follow(thefile):
        thefile.seek(0,2)
        while True:
            line = thefile.readline()
            if not line:
                time.sleep(0.5)
                continue
            yield line
    
    if __name__ == '__main__':
        logfilename = sys.argv[1]
        pattern_string = sys.argv[2]
        command_to_execute = sys.argv[3]
    
        print("Log filename is: {}".format(logfilename))
    
        logfile = open(logfilename, "r")
        loglines = follow(logfile)
    
        for line in loglines:
            if pattern_string in line:
                os.system(command_to_execute)
    

    Usage

    1. Make the above script executable:

    chmod +x logwatcher.python3

    1. Add a cronjob to start it after reboot

    crontab -e

    Then write this line there and save it after this:

    @reboot /home/YOURUSERNAME/logwatcher.python3 "/var/log/auth.log" "session opened for user" "/sbin/myscript.sh"

    The first argument of this script is the log file to watch, and the second argument is the string for which to look in it. The third argument is the script to execute when the line is found in file.

    It is best if you use something more reliable to start/restart the script in case it crashes.

提交回复
热议问题