Run (system) script on SSH login and/or logout












12















I'd like my OpenSSH server to start a script whenever a user logs in using SSH, ideally passing the host name or IP, as well as the user name. Additionally I'd like it to run a script, whenever a session is terminated (passing the username). These scripts should not run in the user's session, but system wide.



The idea is to give an audio warning on login and logout, e.g. using espeak, and to display the information on an external display.



I've seen that there is a pam-scripts package but I'm not sure if this does what I want, nor how to use it.










share|improve this question





























    12















    I'd like my OpenSSH server to start a script whenever a user logs in using SSH, ideally passing the host name or IP, as well as the user name. Additionally I'd like it to run a script, whenever a session is terminated (passing the username). These scripts should not run in the user's session, but system wide.



    The idea is to give an audio warning on login and logout, e.g. using espeak, and to display the information on an external display.



    I've seen that there is a pam-scripts package but I'm not sure if this does what I want, nor how to use it.










    share|improve this question



























      12












      12








      12


      10






      I'd like my OpenSSH server to start a script whenever a user logs in using SSH, ideally passing the host name or IP, as well as the user name. Additionally I'd like it to run a script, whenever a session is terminated (passing the username). These scripts should not run in the user's session, but system wide.



      The idea is to give an audio warning on login and logout, e.g. using espeak, and to display the information on an external display.



      I've seen that there is a pam-scripts package but I'm not sure if this does what I want, nor how to use it.










      share|improve this question
















      I'd like my OpenSSH server to start a script whenever a user logs in using SSH, ideally passing the host name or IP, as well as the user name. Additionally I'd like it to run a script, whenever a session is terminated (passing the username). These scripts should not run in the user's session, but system wide.



      The idea is to give an audio warning on login and logout, e.g. using espeak, and to display the information on an external display.



      I've seen that there is a pam-scripts package but I'm not sure if this does what I want, nor how to use it.







      ssh server scripts session






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 6 '16 at 19:00









      muru

      1




      1










      asked Oct 29 '10 at 18:02









      sunsidesunside

      163116




      163116






















          5 Answers
          5






          active

          oldest

          votes


















          9














          You can force a command onto your SSH-users instead of the one they request (or their shell if they don't give a specific command). This can be done by specifying that command with something like ForceCommand /root/ssh-wrapper in /etc/ssh/sshd_config (it doesn't matter where the script is located or how it's named, just make sure it is executable by all users and the sshd configuration file points to it). You also need to restart/reload sshd. The original command is accessible to the forced command as $SSH_ORIGINAL_COMMAND.



          I just hacked this script together:



          #! /bin/sh

          # add logger options when needed
          log="logger -t ssh-wrapper"

          # find IP address
          ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

          $log $USER login from $ip
          espeak "$USER just logged in from $ip" > /dev/null 2>&1

          $log command: ${SSH_ORIGINAL_COMMAND:-shell}
          ${SSH_ORIGINAL_COMMAND:-shell}

          $log $USER logout
          espeak "$USER just logged out" > /dev/null 2>&1


          Now every time I login or logout a voice tells me about it, and a log entry gets written to syslog. It also logs the command. You can use something like the following to "follow" your sshd usage:



          tailf /var/log/syslog | grep ssh-wrapper


          Please note that this script is mostly untested, so use at your own risk! ;-)



          PS: remember that this script is run as the user that logged in, so you can't do everything you want if you change it to add more features...






          share|improve this answer


























          • Hi, Is there any way to detect situation when the user just closed the window with ssh client. Your script does not hook this situation.. Thanks.

            – Dmitry Eskin
            Jul 7 '15 at 14:05











          • Should shell in ${SSH_ORIGINAL_COMMENT:-shell} be replaced with the actual path to the shell, eg. /bin/bash? When I just try to run that, it complains that there's no such command as shell. Actually, I guess maybe what you meant is $SHELL? That should run the user's specified shell.

            – Ibrahim
            May 27 '17 at 1:43



















          1














          I've seen this matching events in log file before (which would allow you flexibility on matching anything). This page is poorly formatted but it might help you get started:
          https://help.ubuntu.com/community/AudibleLogs#Play with esound






          share|improve this answer
























          • I think you/they mean espeak instead of esound?

            – JanC
            Oct 30 '10 at 0:59



















          0














          (Answer cross-posted from the same question on ServerFault)



          Just write a script to do whatever you want and then stick it in /etc/profile or possibly/etc/bash.bashrc depending on your needs. Changes to those files will apply to all users. I'm not sure how you'd go about notifying on logout with this approach, though.



          Alternatively, another way to do this would be to have a simple daemon monitoring /var/log/auth for new (and closing) ssh sessions. That way it would be able to send notifications on both login and logout.






          share|improve this answer

































            0














            You can use the sshrc (man sshd , search for sshrc)



            ssh will execute the /etc/ssh/sshrc if it exists and you can run one script (or call multiple scripts) from there



            you can call any bash variable, like $USER or get the IP via



            read -d " " ip <<< $SSH_CONNECTION


            you can write a script to test or log what ever you want.



            Logout script... well, that is what i'm searching for! :D






            share|improve this answer































              0














              I think PAM is the best option. It's system-wide and can't be overriden by user's config files.



              You can follow these steps. They worked for me on Ubuntu 14.04.4 LTS.



              Run:



              $ sudo pico /opt/custom/bin/info-session.sh


              Edit that empty file and add these lines:



              #!/bin/sh

              [ "$PAM_TYPE" = "open_session" ] || exit 0

              INFO=$(date +"%Y/%m/%d %T $PAM_USER ($PAM_RHOST) $PAM_SERVICE $PAM_TTY") # You can customize message.

              echo "PAM access: $INFO" | write user > /dev/null 2>&1 # See Note 1.

              exit 0


              After that, give execute permission to the script:



              $ sudo chmod ugo+x /opt/custom/bin/info-session.sh


              Now, run:



              $ sudo pico /etc/pam.d/common-session


              Add these lines at the end of the file:



              # Modified by user:
              session optional pam_exec.so /opt/custom/bin/info-session.sh


              There's no need to restart any service. Note that this script will also be run when a user logs in from terminal instead of SSH.



              Note 1: You can pipe to espeak or any other process which fits your needs (email, push notification, and so on...). If you use write and user is logged in, he or she will see output messages directly on their terminal.



              References:
              https://blog.stalkr.net/2010/11/login-notifications-pamexec-scripting.html
              https://blog.redbranch.net/2014/06/04/pam_exec-so-execute-commands-on-user-login/



              Related:
              How do I set up an email alert when a ssh login is successful?
              https://serverfault.com/questions/400613/how-can-i-configure-my-server-to-notify-me-whenever-it-is-remotely-accessed-via
              https://serverfault.com/questions/395393/email-notification-about-each-ssh-connection-to-linux-server






              share|improve this answer










              New contributor




              Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.




















                Your Answer








                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "89"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f10294%2frun-system-script-on-ssh-login-and-or-logout%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                9














                You can force a command onto your SSH-users instead of the one they request (or their shell if they don't give a specific command). This can be done by specifying that command with something like ForceCommand /root/ssh-wrapper in /etc/ssh/sshd_config (it doesn't matter where the script is located or how it's named, just make sure it is executable by all users and the sshd configuration file points to it). You also need to restart/reload sshd. The original command is accessible to the forced command as $SSH_ORIGINAL_COMMAND.



                I just hacked this script together:



                #! /bin/sh

                # add logger options when needed
                log="logger -t ssh-wrapper"

                # find IP address
                ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

                $log $USER login from $ip
                espeak "$USER just logged in from $ip" > /dev/null 2>&1

                $log command: ${SSH_ORIGINAL_COMMAND:-shell}
                ${SSH_ORIGINAL_COMMAND:-shell}

                $log $USER logout
                espeak "$USER just logged out" > /dev/null 2>&1


                Now every time I login or logout a voice tells me about it, and a log entry gets written to syslog. It also logs the command. You can use something like the following to "follow" your sshd usage:



                tailf /var/log/syslog | grep ssh-wrapper


                Please note that this script is mostly untested, so use at your own risk! ;-)



                PS: remember that this script is run as the user that logged in, so you can't do everything you want if you change it to add more features...






                share|improve this answer


























                • Hi, Is there any way to detect situation when the user just closed the window with ssh client. Your script does not hook this situation.. Thanks.

                  – Dmitry Eskin
                  Jul 7 '15 at 14:05











                • Should shell in ${SSH_ORIGINAL_COMMENT:-shell} be replaced with the actual path to the shell, eg. /bin/bash? When I just try to run that, it complains that there's no such command as shell. Actually, I guess maybe what you meant is $SHELL? That should run the user's specified shell.

                  – Ibrahim
                  May 27 '17 at 1:43
















                9














                You can force a command onto your SSH-users instead of the one they request (or their shell if they don't give a specific command). This can be done by specifying that command with something like ForceCommand /root/ssh-wrapper in /etc/ssh/sshd_config (it doesn't matter where the script is located or how it's named, just make sure it is executable by all users and the sshd configuration file points to it). You also need to restart/reload sshd. The original command is accessible to the forced command as $SSH_ORIGINAL_COMMAND.



                I just hacked this script together:



                #! /bin/sh

                # add logger options when needed
                log="logger -t ssh-wrapper"

                # find IP address
                ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

                $log $USER login from $ip
                espeak "$USER just logged in from $ip" > /dev/null 2>&1

                $log command: ${SSH_ORIGINAL_COMMAND:-shell}
                ${SSH_ORIGINAL_COMMAND:-shell}

                $log $USER logout
                espeak "$USER just logged out" > /dev/null 2>&1


                Now every time I login or logout a voice tells me about it, and a log entry gets written to syslog. It also logs the command. You can use something like the following to "follow" your sshd usage:



                tailf /var/log/syslog | grep ssh-wrapper


                Please note that this script is mostly untested, so use at your own risk! ;-)



                PS: remember that this script is run as the user that logged in, so you can't do everything you want if you change it to add more features...






                share|improve this answer


























                • Hi, Is there any way to detect situation when the user just closed the window with ssh client. Your script does not hook this situation.. Thanks.

                  – Dmitry Eskin
                  Jul 7 '15 at 14:05











                • Should shell in ${SSH_ORIGINAL_COMMENT:-shell} be replaced with the actual path to the shell, eg. /bin/bash? When I just try to run that, it complains that there's no such command as shell. Actually, I guess maybe what you meant is $SHELL? That should run the user's specified shell.

                  – Ibrahim
                  May 27 '17 at 1:43














                9












                9








                9







                You can force a command onto your SSH-users instead of the one they request (or their shell if they don't give a specific command). This can be done by specifying that command with something like ForceCommand /root/ssh-wrapper in /etc/ssh/sshd_config (it doesn't matter where the script is located or how it's named, just make sure it is executable by all users and the sshd configuration file points to it). You also need to restart/reload sshd. The original command is accessible to the forced command as $SSH_ORIGINAL_COMMAND.



                I just hacked this script together:



                #! /bin/sh

                # add logger options when needed
                log="logger -t ssh-wrapper"

                # find IP address
                ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

                $log $USER login from $ip
                espeak "$USER just logged in from $ip" > /dev/null 2>&1

                $log command: ${SSH_ORIGINAL_COMMAND:-shell}
                ${SSH_ORIGINAL_COMMAND:-shell}

                $log $USER logout
                espeak "$USER just logged out" > /dev/null 2>&1


                Now every time I login or logout a voice tells me about it, and a log entry gets written to syslog. It also logs the command. You can use something like the following to "follow" your sshd usage:



                tailf /var/log/syslog | grep ssh-wrapper


                Please note that this script is mostly untested, so use at your own risk! ;-)



                PS: remember that this script is run as the user that logged in, so you can't do everything you want if you change it to add more features...






                share|improve this answer















                You can force a command onto your SSH-users instead of the one they request (or their shell if they don't give a specific command). This can be done by specifying that command with something like ForceCommand /root/ssh-wrapper in /etc/ssh/sshd_config (it doesn't matter where the script is located or how it's named, just make sure it is executable by all users and the sshd configuration file points to it). You also need to restart/reload sshd. The original command is accessible to the forced command as $SSH_ORIGINAL_COMMAND.



                I just hacked this script together:



                #! /bin/sh

                # add logger options when needed
                log="logger -t ssh-wrapper"

                # find IP address
                ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

                $log $USER login from $ip
                espeak "$USER just logged in from $ip" > /dev/null 2>&1

                $log command: ${SSH_ORIGINAL_COMMAND:-shell}
                ${SSH_ORIGINAL_COMMAND:-shell}

                $log $USER logout
                espeak "$USER just logged out" > /dev/null 2>&1


                Now every time I login or logout a voice tells me about it, and a log entry gets written to syslog. It also logs the command. You can use something like the following to "follow" your sshd usage:



                tailf /var/log/syslog | grep ssh-wrapper


                Please note that this script is mostly untested, so use at your own risk! ;-)



                PS: remember that this script is run as the user that logged in, so you can't do everything you want if you change it to add more features...







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jun 6 '16 at 19:00









                muru

                1




                1










                answered Oct 30 '10 at 3:55









                JanCJanC

                16.7k13446




                16.7k13446













                • Hi, Is there any way to detect situation when the user just closed the window with ssh client. Your script does not hook this situation.. Thanks.

                  – Dmitry Eskin
                  Jul 7 '15 at 14:05











                • Should shell in ${SSH_ORIGINAL_COMMENT:-shell} be replaced with the actual path to the shell, eg. /bin/bash? When I just try to run that, it complains that there's no such command as shell. Actually, I guess maybe what you meant is $SHELL? That should run the user's specified shell.

                  – Ibrahim
                  May 27 '17 at 1:43



















                • Hi, Is there any way to detect situation when the user just closed the window with ssh client. Your script does not hook this situation.. Thanks.

                  – Dmitry Eskin
                  Jul 7 '15 at 14:05











                • Should shell in ${SSH_ORIGINAL_COMMENT:-shell} be replaced with the actual path to the shell, eg. /bin/bash? When I just try to run that, it complains that there's no such command as shell. Actually, I guess maybe what you meant is $SHELL? That should run the user's specified shell.

                  – Ibrahim
                  May 27 '17 at 1:43

















                Hi, Is there any way to detect situation when the user just closed the window with ssh client. Your script does not hook this situation.. Thanks.

                – Dmitry Eskin
                Jul 7 '15 at 14:05





                Hi, Is there any way to detect situation when the user just closed the window with ssh client. Your script does not hook this situation.. Thanks.

                – Dmitry Eskin
                Jul 7 '15 at 14:05













                Should shell in ${SSH_ORIGINAL_COMMENT:-shell} be replaced with the actual path to the shell, eg. /bin/bash? When I just try to run that, it complains that there's no such command as shell. Actually, I guess maybe what you meant is $SHELL? That should run the user's specified shell.

                – Ibrahim
                May 27 '17 at 1:43





                Should shell in ${SSH_ORIGINAL_COMMENT:-shell} be replaced with the actual path to the shell, eg. /bin/bash? When I just try to run that, it complains that there's no such command as shell. Actually, I guess maybe what you meant is $SHELL? That should run the user's specified shell.

                – Ibrahim
                May 27 '17 at 1:43













                1














                I've seen this matching events in log file before (which would allow you flexibility on matching anything). This page is poorly formatted but it might help you get started:
                https://help.ubuntu.com/community/AudibleLogs#Play with esound






                share|improve this answer
























                • I think you/they mean espeak instead of esound?

                  – JanC
                  Oct 30 '10 at 0:59
















                1














                I've seen this matching events in log file before (which would allow you flexibility on matching anything). This page is poorly formatted but it might help you get started:
                https://help.ubuntu.com/community/AudibleLogs#Play with esound






                share|improve this answer
























                • I think you/they mean espeak instead of esound?

                  – JanC
                  Oct 30 '10 at 0:59














                1












                1








                1







                I've seen this matching events in log file before (which would allow you flexibility on matching anything). This page is poorly formatted but it might help you get started:
                https://help.ubuntu.com/community/AudibleLogs#Play with esound






                share|improve this answer













                I've seen this matching events in log file before (which would allow you flexibility on matching anything). This page is poorly formatted but it might help you get started:
                https://help.ubuntu.com/community/AudibleLogs#Play with esound







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Oct 29 '10 at 18:47









                kanakakanaka

                21313




                21313













                • I think you/they mean espeak instead of esound?

                  – JanC
                  Oct 30 '10 at 0:59



















                • I think you/they mean espeak instead of esound?

                  – JanC
                  Oct 30 '10 at 0:59

















                I think you/they mean espeak instead of esound?

                – JanC
                Oct 30 '10 at 0:59





                I think you/they mean espeak instead of esound?

                – JanC
                Oct 30 '10 at 0:59











                0














                (Answer cross-posted from the same question on ServerFault)



                Just write a script to do whatever you want and then stick it in /etc/profile or possibly/etc/bash.bashrc depending on your needs. Changes to those files will apply to all users. I'm not sure how you'd go about notifying on logout with this approach, though.



                Alternatively, another way to do this would be to have a simple daemon monitoring /var/log/auth for new (and closing) ssh sessions. That way it would be able to send notifications on both login and logout.






                share|improve this answer






























                  0














                  (Answer cross-posted from the same question on ServerFault)



                  Just write a script to do whatever you want and then stick it in /etc/profile or possibly/etc/bash.bashrc depending on your needs. Changes to those files will apply to all users. I'm not sure how you'd go about notifying on logout with this approach, though.



                  Alternatively, another way to do this would be to have a simple daemon monitoring /var/log/auth for new (and closing) ssh sessions. That way it would be able to send notifications on both login and logout.






                  share|improve this answer




























                    0












                    0








                    0







                    (Answer cross-posted from the same question on ServerFault)



                    Just write a script to do whatever you want and then stick it in /etc/profile or possibly/etc/bash.bashrc depending on your needs. Changes to those files will apply to all users. I'm not sure how you'd go about notifying on logout with this approach, though.



                    Alternatively, another way to do this would be to have a simple daemon monitoring /var/log/auth for new (and closing) ssh sessions. That way it would be able to send notifications on both login and logout.






                    share|improve this answer















                    (Answer cross-posted from the same question on ServerFault)



                    Just write a script to do whatever you want and then stick it in /etc/profile or possibly/etc/bash.bashrc depending on your needs. Changes to those files will apply to all users. I'm not sure how you'd go about notifying on logout with this approach, though.



                    Alternatively, another way to do this would be to have a simple daemon monitoring /var/log/auth for new (and closing) ssh sessions. That way it would be able to send notifications on both login and logout.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 13 '17 at 12:14









                    Community

                    1




                    1










                    answered Oct 29 '10 at 18:54









                    EEAAEEAA

                    1012




                    1012























                        0














                        You can use the sshrc (man sshd , search for sshrc)



                        ssh will execute the /etc/ssh/sshrc if it exists and you can run one script (or call multiple scripts) from there



                        you can call any bash variable, like $USER or get the IP via



                        read -d " " ip <<< $SSH_CONNECTION


                        you can write a script to test or log what ever you want.



                        Logout script... well, that is what i'm searching for! :D






                        share|improve this answer




























                          0














                          You can use the sshrc (man sshd , search for sshrc)



                          ssh will execute the /etc/ssh/sshrc if it exists and you can run one script (or call multiple scripts) from there



                          you can call any bash variable, like $USER or get the IP via



                          read -d " " ip <<< $SSH_CONNECTION


                          you can write a script to test or log what ever you want.



                          Logout script... well, that is what i'm searching for! :D






                          share|improve this answer


























                            0












                            0








                            0







                            You can use the sshrc (man sshd , search for sshrc)



                            ssh will execute the /etc/ssh/sshrc if it exists and you can run one script (or call multiple scripts) from there



                            you can call any bash variable, like $USER or get the IP via



                            read -d " " ip <<< $SSH_CONNECTION


                            you can write a script to test or log what ever you want.



                            Logout script... well, that is what i'm searching for! :D






                            share|improve this answer













                            You can use the sshrc (man sshd , search for sshrc)



                            ssh will execute the /etc/ssh/sshrc if it exists and you can run one script (or call multiple scripts) from there



                            you can call any bash variable, like $USER or get the IP via



                            read -d " " ip <<< $SSH_CONNECTION


                            you can write a script to test or log what ever you want.



                            Logout script... well, that is what i'm searching for! :D







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jun 6 '16 at 18:53









                            higuitahiguita

                            1,697198




                            1,697198























                                0














                                I think PAM is the best option. It's system-wide and can't be overriden by user's config files.



                                You can follow these steps. They worked for me on Ubuntu 14.04.4 LTS.



                                Run:



                                $ sudo pico /opt/custom/bin/info-session.sh


                                Edit that empty file and add these lines:



                                #!/bin/sh

                                [ "$PAM_TYPE" = "open_session" ] || exit 0

                                INFO=$(date +"%Y/%m/%d %T $PAM_USER ($PAM_RHOST) $PAM_SERVICE $PAM_TTY") # You can customize message.

                                echo "PAM access: $INFO" | write user > /dev/null 2>&1 # See Note 1.

                                exit 0


                                After that, give execute permission to the script:



                                $ sudo chmod ugo+x /opt/custom/bin/info-session.sh


                                Now, run:



                                $ sudo pico /etc/pam.d/common-session


                                Add these lines at the end of the file:



                                # Modified by user:
                                session optional pam_exec.so /opt/custom/bin/info-session.sh


                                There's no need to restart any service. Note that this script will also be run when a user logs in from terminal instead of SSH.



                                Note 1: You can pipe to espeak or any other process which fits your needs (email, push notification, and so on...). If you use write and user is logged in, he or she will see output messages directly on their terminal.



                                References:
                                https://blog.stalkr.net/2010/11/login-notifications-pamexec-scripting.html
                                https://blog.redbranch.net/2014/06/04/pam_exec-so-execute-commands-on-user-login/



                                Related:
                                How do I set up an email alert when a ssh login is successful?
                                https://serverfault.com/questions/400613/how-can-i-configure-my-server-to-notify-me-whenever-it-is-remotely-accessed-via
                                https://serverfault.com/questions/395393/email-notification-about-each-ssh-connection-to-linux-server






                                share|improve this answer










                                New contributor




                                Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.

























                                  0














                                  I think PAM is the best option. It's system-wide and can't be overriden by user's config files.



                                  You can follow these steps. They worked for me on Ubuntu 14.04.4 LTS.



                                  Run:



                                  $ sudo pico /opt/custom/bin/info-session.sh


                                  Edit that empty file and add these lines:



                                  #!/bin/sh

                                  [ "$PAM_TYPE" = "open_session" ] || exit 0

                                  INFO=$(date +"%Y/%m/%d %T $PAM_USER ($PAM_RHOST) $PAM_SERVICE $PAM_TTY") # You can customize message.

                                  echo "PAM access: $INFO" | write user > /dev/null 2>&1 # See Note 1.

                                  exit 0


                                  After that, give execute permission to the script:



                                  $ sudo chmod ugo+x /opt/custom/bin/info-session.sh


                                  Now, run:



                                  $ sudo pico /etc/pam.d/common-session


                                  Add these lines at the end of the file:



                                  # Modified by user:
                                  session optional pam_exec.so /opt/custom/bin/info-session.sh


                                  There's no need to restart any service. Note that this script will also be run when a user logs in from terminal instead of SSH.



                                  Note 1: You can pipe to espeak or any other process which fits your needs (email, push notification, and so on...). If you use write and user is logged in, he or she will see output messages directly on their terminal.



                                  References:
                                  https://blog.stalkr.net/2010/11/login-notifications-pamexec-scripting.html
                                  https://blog.redbranch.net/2014/06/04/pam_exec-so-execute-commands-on-user-login/



                                  Related:
                                  How do I set up an email alert when a ssh login is successful?
                                  https://serverfault.com/questions/400613/how-can-i-configure-my-server-to-notify-me-whenever-it-is-remotely-accessed-via
                                  https://serverfault.com/questions/395393/email-notification-about-each-ssh-connection-to-linux-server






                                  share|improve this answer










                                  New contributor




                                  Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.























                                    0












                                    0








                                    0







                                    I think PAM is the best option. It's system-wide and can't be overriden by user's config files.



                                    You can follow these steps. They worked for me on Ubuntu 14.04.4 LTS.



                                    Run:



                                    $ sudo pico /opt/custom/bin/info-session.sh


                                    Edit that empty file and add these lines:



                                    #!/bin/sh

                                    [ "$PAM_TYPE" = "open_session" ] || exit 0

                                    INFO=$(date +"%Y/%m/%d %T $PAM_USER ($PAM_RHOST) $PAM_SERVICE $PAM_TTY") # You can customize message.

                                    echo "PAM access: $INFO" | write user > /dev/null 2>&1 # See Note 1.

                                    exit 0


                                    After that, give execute permission to the script:



                                    $ sudo chmod ugo+x /opt/custom/bin/info-session.sh


                                    Now, run:



                                    $ sudo pico /etc/pam.d/common-session


                                    Add these lines at the end of the file:



                                    # Modified by user:
                                    session optional pam_exec.so /opt/custom/bin/info-session.sh


                                    There's no need to restart any service. Note that this script will also be run when a user logs in from terminal instead of SSH.



                                    Note 1: You can pipe to espeak or any other process which fits your needs (email, push notification, and so on...). If you use write and user is logged in, he or she will see output messages directly on their terminal.



                                    References:
                                    https://blog.stalkr.net/2010/11/login-notifications-pamexec-scripting.html
                                    https://blog.redbranch.net/2014/06/04/pam_exec-so-execute-commands-on-user-login/



                                    Related:
                                    How do I set up an email alert when a ssh login is successful?
                                    https://serverfault.com/questions/400613/how-can-i-configure-my-server-to-notify-me-whenever-it-is-remotely-accessed-via
                                    https://serverfault.com/questions/395393/email-notification-about-each-ssh-connection-to-linux-server






                                    share|improve this answer










                                    New contributor




                                    Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.










                                    I think PAM is the best option. It's system-wide and can't be overriden by user's config files.



                                    You can follow these steps. They worked for me on Ubuntu 14.04.4 LTS.



                                    Run:



                                    $ sudo pico /opt/custom/bin/info-session.sh


                                    Edit that empty file and add these lines:



                                    #!/bin/sh

                                    [ "$PAM_TYPE" = "open_session" ] || exit 0

                                    INFO=$(date +"%Y/%m/%d %T $PAM_USER ($PAM_RHOST) $PAM_SERVICE $PAM_TTY") # You can customize message.

                                    echo "PAM access: $INFO" | write user > /dev/null 2>&1 # See Note 1.

                                    exit 0


                                    After that, give execute permission to the script:



                                    $ sudo chmod ugo+x /opt/custom/bin/info-session.sh


                                    Now, run:



                                    $ sudo pico /etc/pam.d/common-session


                                    Add these lines at the end of the file:



                                    # Modified by user:
                                    session optional pam_exec.so /opt/custom/bin/info-session.sh


                                    There's no need to restart any service. Note that this script will also be run when a user logs in from terminal instead of SSH.



                                    Note 1: You can pipe to espeak or any other process which fits your needs (email, push notification, and so on...). If you use write and user is logged in, he or she will see output messages directly on their terminal.



                                    References:
                                    https://blog.stalkr.net/2010/11/login-notifications-pamexec-scripting.html
                                    https://blog.redbranch.net/2014/06/04/pam_exec-so-execute-commands-on-user-login/



                                    Related:
                                    How do I set up an email alert when a ssh login is successful?
                                    https://serverfault.com/questions/400613/how-can-i-configure-my-server-to-notify-me-whenever-it-is-remotely-accessed-via
                                    https://serverfault.com/questions/395393/email-notification-about-each-ssh-connection-to-linux-server







                                    share|improve this answer










                                    New contributor




                                    Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    share|improve this answer



                                    share|improve this answer








                                    edited 1 hour ago





















                                    New contributor




                                    Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    answered 2 hours ago









                                    PestroPestro

                                    11




                                    11




                                    New contributor




                                    Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.





                                    New contributor





                                    Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






                                    Pestro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Ask Ubuntu!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f10294%2frun-system-script-on-ssh-login-and-or-logout%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        GameSpot

                                        connect to host localhost port 22: Connection refused

                                        Getting a Wifi WPA2 wifi connection