To reliably inspect the exact SSH command executed on a target machine, you must use the
SSH_CONNECTION environment variable or the
ps command to view the process arguments. Directly echoing
$0 is unreliable because shell parsing alters quoting and argument structures before execution. This guide provides accurate methods for debugging SSH sessions and verifying remote command invocations without relying on flawed assumptions about how the shell handles input.
Why Echoing $0 Fails
Many users attempt to capture the original command by running
echo "$0" or similar constructs within their
.bashrc or profile scripts. This approach fundamentally misunderstands how the shell processes arguments. When an SSH client sends a command, it is passed as a string that the remote shell parses. The
$0 variable typically refers to the name of the shell itself (e.g.,
-bash) or the script being executed, not the full command line string sent by the client. Furthermore, any quotes, spaces, or special characters in the original command are interpreted by the local shell before transmission, meaning the remote side never sees the literal "exact" string typed on the source machine. It only sees the resulting parsed arguments. Therefore, relying on
$0 or
$@ in interactive shells often yields incomplete or misleading data, making it unsuitable for forensic analysis or precise debugging of remote executions.
Using SSH_CONNECTION Environment Variables
The most robust method for identifying who connected and from where involves the built-in environment variables provided by the SSH daemon. These variables are automatically set when a session is established and remain consistent across different shell configurations. You can view these variables by running
env | grep SSH or specifically querying
SSH_CONNECTION.
The output contains four values: the IP address of the client, the client port number, the IP address of the server, and the server port number. For example:
192.168.1.10 54321 192.168.1.20 22
This information confirms the connection details but does not reveal the specific command executed if one was passed via
ssh user@host 'command'. However, it is critical for logging and security auditing. If you need to log every command run during a session, you should configure the
sshd_config file on the target machine. Add or modify the following line:
PrintLastLog yes
While this does not print the command, it ensures proper logging integration. For actual command capture, consider using
ForceCommand in
sshd_config if you are restricting access, or simply rely on the audit logs mentioned below.
Capturing Commands with Process Listing
If you need to see what command is currently running on the remote machine, the
ps utility is the standard tool. Run
ps auxf or
ps -ef on the target machine. Look for the process owned by your user that corresponds to the SSH session. The command column will show the actual executable and its arguments. Note that complex commands involving pipes or subshells may appear truncated or split across multiple lines in the process table. To get a more detailed view, you can check
/proc/<PID>/cmdline, but be aware that null bytes separate arguments, requiring tools like
tr or
xargs to display them cleanly:
cat /proc/self/cmdline | tr '\0' ' '
This method shows the state of the process at the time of inspection, which is useful for troubleshooting hanging connections or verifying that a specific script was invoked correctly.
Advanced Auditing with Auditd
For enterprise environments where tracking the exact command string is mandatory for compliance, the Linux Audit Framework (
auditd) is the correct solution. By configuring rules to monitor
execve syscalls, you can log every command execution along with its full argument list. This bypasses shell parsing issues entirely because it intercepts the system call before the shell interprets the arguments. Set up an audit rule such as:
-a always,exit -F arch=b64 -S execve -k ssh_commands
This generates entries in
/var/log/audit/audit.log that contain the full command line, including all quoted strings and special characters exactly as they were processed by the kernel. This is the only method that guarantees fidelity to the original intent, regardless of shell quirks.
Debugging Connection Issues
When diagnosing why a command fails remotely, verbose SSH flags are more helpful than trying to capture the command string. Use
ssh -vvv user@host to see the negotiation phase. This helps identify issues like key exchange failures or permission denied errors, which are common obstacles. For related connectivity problems, see
Troubleshooting kex_exchange_identification Error in Linux SSH Connection. Additionally, ensure that your local shell is not altering the command before it leaves your machine. Single quotes preserve literal strings, while double quotes allow variable expansion, so
ssh host '$VAR' behaves differently than
ssh host "$VAR". Understanding this distinction prevents many apparent "missing command" mysteries.
Frequently Asked Questions
Can I log every command typed in an SSH session?
Yes, you can enable logging in
sshd_config by setting
LogLevel VERBOSE or using
auditd for comprehensive syscall tracing. Standard shell history files on the remote host also record commands if the user has write permissions to their home directory.
Why does my remote script show different arguments than what I sent?
Shell parsing occurs on both the client and server sides. Quotes and escapes are consumed during the initial transmission and subsequent shell interpretation, so the remote process sees the resolved arguments rather than the raw text string.
Is there a way to see the command before it executes?
You can use
strace to trace system calls, but this requires root privileges and significant performance overhead. For non-root users,
auditd is the preferred lightweight alternative for capturing command-line arguments.
How do I prevent accidental variable expansion in SSH commands?
Always wrap your remote command in single quotes on the local machine, e.g.,
ssh host 'echo $HOME'. This prevents the local shell from expanding
$HOME before sending it to the remote server.
What if the SSH connection drops before I can check the process?
Check the remote authentication logs in
/var/log/auth.log or
/var/log/secure. While these won't show the command, they confirm whether the connection was established and authenticated successfully before termination.