October 22, 2024
Chicago 12, Melborne City, USA
security

How to Track SSH Access by UserName (whoami) on an Ubuntu 22.04?


I am managing an Ubuntu 22.04 (AWS EC2) server. I am looking for a way to track SSH access to the server, specifically by obtaining the username (whoami) of the developer’s laptop when they connect via SSH. Is there a method or configuration that can help me identify who accessed the server based on their username (whoami)

NOTE:
I can’t do anythings in developers laptop we want to manage through the Remote server

What I Tried:
I created a custom script (track-ssh.sh) to log SSH connection details, aiming to capture each developer’s local username along with their IP address and username.

track-ssh.sh

#!/bin/bash
# Get the IP address of the incoming connection
IP=$(echo $SSH_CONNECTION | awk '{print $1}')

# Get the username from the environment
USERNAME=$(whoami)

# Get the SSH client's environment details
SSH_CLIENT_DETAILS=$(echo $SSH_CLIENT)
SSH_TTY_DETAILS=$(echo $SSH_TTY)

# Try to resolve the hostname from the IP address
REMOTE_HOSTNAME=$(nslookup $IP | grep 'name=" | awk "{print $4}' | sed 's/\.$//')

# Log the connection details
echo "SSH connection from IP: $IP (Username: $USERNAME, Hostname: $REMOTE_HOSTNAME, SSH Client: $SSH_CLIENT_DETAILS, TTY: $SSH_TTY_DETAILS)" >> /var/log/ssh-connections.log

# Get the username corresponding to the hostname
if [ -n "$REMOTE_HOSTNAME" ]; then
    REMOTE_USERNAME=$(getent passwd | grep "$REMOTE_HOSTNAME" | cut -d: -f1)
    if [ -z "$REMOTE_USERNAME" ]; then
        REMOTE_USERNAME="Unknown User"
    fi
else
    REMOTE_USERNAME="Unknown Hostname"
fi

# Log the username associated with the hostname
echo "Resolved username for hostname $REMOTE_HOSTNAME: $REMOTE_USERNAME" >> /var/log/ssh-connections.log

# Ensure the SSH session proceeds
if [ -z "$SSH_ORIGINAL_COMMAND" ]; then
    exec /bin/bash
else
    exec "$SSH_ORIGINAL_COMMAND"
fi

What I Expected:
I expected the logs to show the developer’s username when they SSH into the server, allowing me to identify which developer accessed the server.

What Actually Happened:
The logs only show the IP address and username (root), but the username is not captured correctly. Instead of displaying the developer’s username, the logs contain no username information.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video