While useradd -p
technically exists, its requirement for pre-encrypted passwords using the legacy crypt() function makes it impractical for automated deployments. Modern RedHat systems (RHEL 7+) use SHA-512 hashing by default in /etc/login.defs
, but there's no straightforward way to generate compatible hashes within a script.
The most reliable one-line method combines useradd
with chpasswd
:
useradd sftpuser && echo "sftpuser:MySecureP@ssw0rd" | chpasswd
For AWS automation with KMS decrypted passwords:
# Retrieve encrypted password from AWS Secrets Manager
PASSWORD=$(aws secretsmanager get-secret-value --secret-id MyApp/SFTPCreds | jq -r '.SecretString' | jq -r .password)
# Create user with decrypted password
useradd -m -d /var/sftp/sftpuser -s /bin/false sftpuser && \
echo "sftpuser:$PASSWORD" | chpasswd && \
chown root:root /var/sftp/sftpuser && \
chmod 755 /var/sftp/sftpuser
1. Always use /bin/false
or /sbin/nologin
shell for SFTP-only users
2. Restrict home directory permissions (chmod 755 for root ownership)
3. Consider using mkpasswd
from whois package if you need pre-hashed passwords:
useradd -p $(mkpasswd --method=SHA-512 MySecureP@ssw0rd) sftpuser
If chpasswd fails:
- Verify PAM configuration in /etc/pam.d/chpasswd
- Check password complexity requirements in /etc/security/pwquality.conf
- Test password hashing with openssl passwd -6
for SHA-512
When neither chpasswd nor mkpasswd are available:
#!/usr/bin/expect
spawn passwd sftpuser
expect "New password:"
send "MySecureP@ssw0rd\r"
expect "Retype new password:"
send "MySecureP@ssw0rd\r"
expect eof
In automated environments like AWS deployments, creating users with predefined passwords becomes crucial. The traditional useradd -p
approach fails because:
- Modern RedHat/CentOS systems no longer include the
crypt
utility - Interactive
passwd
prompts break automation workflows - KMS-retrieved passwords shouldn't be stored as plaintext
Here are three production-tested methods to create users with passwords in one line:
1. Using chpasswd with stdin
sudo useradd sftpuser && echo "sftpuser:SecurePass123" | sudo chpasswd
2. Leveraging openssl for Password Hashing
sudo useradd -p $(openssl passwd -6 'SecurePass123') sftpuser
3. Python One-Liner Alternative
sudo python3 -c 'import crypt; print(crypt.crypt("SecurePass123", crypt.mksalt(crypt.METHOD_SHA512)))' | xargs -I {} sudo useradd -p {} sftpuser
When implementing these solutions:
- Always retrieve passwords from secure sources (AWS Secrets Manager, KMS)
- Use temporary environment variables rather than script-embedded values
- Consider implementing password rotation policies
#!/bin/bash
PASSWORD=$(aws secretsmanager get-secret-value --secret-id /prod/sftp/credentials --query SecretString --output text)
sudo useradd -m -d /sftp/sftpuser -s /bin/false sftpuser
echo "sftpuser:$PASSWORD" | sudo chpasswd
sudo mkdir -p /sftp/sftpuser/uploads
sudo chown sftpuser:sftpuser /sftp/sftpuser/uploads