How to Automate SSH Password Authentication for Privilege Escalation (su) in .ssh/config


2 views

When working with servers requiring privilege escalation via su, manually entering passwords breaks automation workflows. While SSH keys solve primary authentication, the secondary su password prompt remains problematic.

The scenario presents specific requirements:

1. Mandatory two-step authentication (user → su)
2. Passphrase-protected SSH key usage
3. Need for non-interactive execution

Combine sshpass with Expect scripting:

Host server
  HostName hostname.server.com
  User not-root
  Port 1234
  RemoteCommand expect -c 'spawn su; expect "Password:"; send "your_root_password\\r"; interact'

For production environments, consider these alternatives:

  • SSH certificate-based authentication
  • Configure sudo without password for specific commands
  • Use SSH forced commands with limited privileges

Create a dedicated expect script (su_wrapper.exp):

#!/usr/bin/expect
set timeout 20
spawn su
expect "Password:"
send "actual_password\\r"
interact

Then modify your SSH config:

Host server
  HostName hostname.server.com
  User not-root
  Port 1234
  RemoteCommand /path/to/su_wrapper.exp
  • Test expect scripts directly before SSH integration
  • Verify file permissions on expect scripts (chmod 700)
  • Check system logs for authentication failures

When working with servers that require privilege escalation, manually typing passwords breaks automation workflows. The standard .ssh/config approach fails because:

  • SSH config doesn't natively support password passing (for security reasons)
  • RemoteCommand su triggers an interactive password prompt
  • Key-based auth alone won't solve the post-login su requirement

Here are three battle-tested methods I've used in production environments:

Method 1: SSH + Expect Script

#!/usr/bin/expect -f
set timeout 20
spawn ssh -F /path/to/config server
expect "password:"
send "your_root_password\r"
interact

Method 2: SSH Config with ProxyCommand

Host server
  HostName hostname.server.com
  User not-root
  Port 1234
  ProxyCommand bash -c 'sshpass -p "your_password" ssh -tt %h %n su -c "bash -i"'

Method 3: Combined Key and Password Solution

Host server
  HostName hostname.server.com
  User not-root
  IdentityFile ~/.ssh/special_key
  RemoteCommand echo "your_password" | su -c "cd $HOME; exec \$SHELL -l"
  RequestTTY force

While these methods work, consider these precautions:

  • Set strict file permissions (chmod 600 ~/.ssh/config)
  • Use SSH certificates instead of raw passwords when possible
  • Implement session timeouts for sensitive operations
  • Consider sudo with NOPASSWD for specific commands

For a cleaner solution without exposing passwords in config files:

function ssh_server() {
  ssh -t server "echo 'YOUR_PASSWORD' | su -c 'your_command'"
}