How can I allow access to SSH only at a specific time?

Based on Ubuntu 18.04,

I want to allow users to access only from 9 a.m. to 5 p.m.(working time) on the SSH server. (used OpenSSH-server package)

I've looked up all the materials I think will help you from user management to PAM settings on Google, but I don't think there's any information to restrict access by SSH time zone.

(But, I have not to use firewall-related services like ufw.)

If you can help me, please let me know. Thank you.

(Please understand that my English can be unnatural because I am not good at English.)


Use a cron job to stop and start the ssh server at specific times. For example create a file /etc/cron.d/start-stop-ssh with the following contents:

0 9 * * * root /usr/sbin/service ssh start
0 17 * * * root /usr/sbin/service ssh stop

This will start the ssh service everyday at 9:00 and stop it everyday at 17:00.

Please note that when the service is stopped nobody (even admin) will be able to login via ssh.


The pam_time module is designed for this.

  1. Add pam_time as the first account statement in the ssh pam config. This command will insert the statement account required pam_time.so just above the line @include common-account.
sed -i -e '/^.include common-account/i account required pam_time.so' /etc/pam.d/sshd
  1. configure /etc/security/time.conf as desired. This command will add the configuration sshd;*;*;Wk0900-1700. This limits ssh connections for all users to weekdays between 9am and 5pm.
echo 'sshd;*;*;Wk0900-1700' >> /etc/security/time.conf

See Also

  • http://manpages.ubuntu.com/manpages/focal/en/man8/pam_time.8.html
  • http://manpages.ubuntu.com/manpages/focal/en/man5/time.conf.5.html