Warning: If you are connecting remotely via SSH, read the answer in full before attempting any of the steps to avoid being locked out.
In /etc/ssh/sshd_config, add the following line:
ForceCommand logger -p user.notice "$SSH_ORIGINAL_COMMAND"
And then reload ssh systemctl reload ssh. Commands executed via ssh will now be sent to the system log file (eg. /var/log/syslog for Ubuntu, possibly /var/log/messages for your distro). However, the commands will no longer execute. Therefore, you should not close your existing ssh session to test if it works. Attempt to open a new one instead. If you would like your commands to execute, try this line:
ForceCommand logger -p user.notice "$SSH_ORIGINAL_COMMAND"; bash -c "$SSH_ORIGINAL_COMMAND"
This command uses bash to execute the command after logging it using logger. Example usage:
> ssh ubuntu@ubuntu-server ls -al
total 36
drwxr-x--- 4 ubuntu ubuntu 4096 Apr 21 17:50 .
drwxr-xr-x 3 root root 4096 Apr 21 17:07 ..
-rw------- 1 ubuntu ubuntu 148 Apr 21 17:14 .bash_history
-rw-r--r-- 1 ubuntu ubuntu 220 Jan 6 2022 .bash_logout
-rw-r--r-- 1 ubuntu ubuntu 3771 Jan 6 2022 .bashrc
drwx------ 2 ubuntu ubuntu 4096 Apr 21 17:08 .cache
-rw-r--r-- 1 ubuntu ubuntu 807 Jan 6 2022 .profile
-rw------- 1 ubuntu ubuntu 0 Apr 21 17:46 .python_history
drwx------ 2 ubuntu ubuntu 4096 Apr 21 17:47 .ssh
-rw-r--r-- 1 ubuntu ubuntu 0 Apr 21 17:08 .sudo_as_admin_successful
-rw------- 1 ubuntu ubuntu 1369 Apr 21 17:50 .viminfo
ubuntu@ubuntu-server:~$ tail -3 /var/log/syslog
Apr 21 17:51:01 ubuntu-server systemd[1]: Started Session 5 of User ubuntu.
Apr 21 17:51:02 ubuntu-server ubuntu: ls -al
Apr 21 17:51:02 ubuntu-server systemd[1]: session-5.scope: Deactivated successfully.
Note that your shell still might not start in interactive mode.