When working with remote servers, we frequently need to inspect directory contents before performing file operations. While SCP (Secure Copy Protocol) handles file transfers beautifully, there isn't a direct equivalent for simply listing remote directory contents without transferring files.
The simplest method is to use SSH directly:
ssh username@remote_host "ls -l /path/to/directory"
This executes the ls command remotely and displays the results locally. For more readable output with colors:
ssh username@remote_host "ls --color=auto -lh /path"
For recursive directory listing (similar to ls -R):
ssh username@host "find /target/path -type f -printf '%TY-%Tm-%Td %TT %p\\n'"
This provides a detailed listing with timestamps, excellent for auditing purposes.
SFTP can also be used interactively:
sftp username@host
sftp> ls /remote/path
sftp> quit
Add this to your ~/.bashrc for quick access:
alias rls='function _rls(){ ssh $1 "ls -lah $2"; };_rls'
Usage becomes:
rls username@host "/path/to/list"
While primarily for file transfers, rsync can list files without transferring:
rsync --list-only username@host:/path/
Add -v for more verbose output or -h for human-readable sizes.
All these methods rely on SSH, so they inherit its security model. For sensitive environments:
- Use SSH keys instead of passwords
- Consider restricting commands in authorized_keys
- Use -q flag for quiet mode when logging is sensitive
The simplest way to achieve remote directory listing is by combining SSH with the ls command:
ssh username@remotehost "ls /path/to/directory"
This executes the ls command on the remote machine and displays the output locally. You can add any standard ls options:
ssh user@server "ls -la /var/www"
For more complex listings, you can pipe the output through other commands:
ssh user@example.com "ls -l /home/user | grep 'May 15'"
Or create a formatted listing:
ssh admin@webserver "find /var/log -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r"
While SCP itself doesn't support directory listing, SFTP (which uses the same SSH protocol) does:
sftp user@host
sftp> ls /remote/path
Or in one line:
echo "ls -l" | sftp user@host 2>/dev/null
Consider these specialized tools for remote directory operations:
# Using rsync (lists files without transferring)
rsync --list-only user@remote:/path/
# Using sshfs (mounts remote directory locally)
sshfs user@remote:/remote/path /local/mountpoint
ls /local/mountpoint
Common use cases with corresponding commands:
# Check disk usage remotely
ssh dbadmin@dbserver "du -sh /var/lib/mysql"
# Find recently modified files
ssh deploy@production "find /app -type f -mtime -7"
# List sorted by size (human readable)
ssh backup@nas "ls -lSh /backups"
Remember to configure SSH keys for password-less access when automating these commands.