SFTP doesn't natively support passing passwords via command line arguments due to security concerns. When automating transfers, you'll typically encounter:
sftp user@host:/path
And then get prompted for password input - which breaks automation scripts.
Option 1: Using sshpass (most straightforward)
sshpass -p "your_password" sftp -oBatchMode=no user@host:/remote/path
Note: sshpass needs to be installed first (sudo apt-get install sshpass on Debian/Ubuntu)
Option 2: SSH Key Authentication (recommended for production)
First generate keys:
ssh-keygen -t rsa -b 4096
ssh-copy-id user@host
Then simply:
sftp user@host:/path
For complex scenarios requiring multiple interactions:
#!/usr/bin/expect -f
spawn sftp user@host
expect "password:"
send "your_password\r"
expect "sftp>"
send "cd /target/path\r"
interact
1. Never store passwords in plain text scripts
2. Use restricted permissions (chmod 600)
3. Consider using environment variables for sensitive data
4. For production systems, always prefer SSH keys
Example using env vars:
export SFTP_PASS="yourpass"
sshpass -p "$SFTP_PASS" sftp user@host
Here's a complete script for scheduled backups:
#!/bin/bash
REMOTE_USER="backup_user"
REMOTE_HOST="files.example.com"
REMOTE_PATH="/backups/$(date +%Y-%m-%d)"
LOCAL_FILE="/var/backups/db_dump.sql"
sshpass -p "${SFTP_PASSWORD}" sftp -oBatchMode=no ${REMOTE_USER}@${REMOTE_HOST} << EOF
mkdir ${REMOTE_PATH}
put ${LOCAL_FILE} ${REMOTE_PATH}/db_backup.sql
bye
EOF
When automating file transfers, the standard SFTP command sftp user@host prompts for password interactively, which breaks automation workflows. Many developers search for ways to include credentials directly in the command line.
Contrary to common assumption, SFTP doesn't have a -p password parameter. This is intentional for security reasons - command lines are visible in process listings and shell history.
# This WON'T work (security risk if it did):
sftp -p PASSWORD user@host # Fiction!
1. SSH Key Authentication
The proper solution is setting up SSH keys:
ssh-keygen -t rsa -b 4096
ssh-copy-id user@host
sftp user@host:/path # Now passwordless
2. Using sshpass (Temporary Solution)
For testing or temporary use, sshpass can pass credentials:
sshpass -p "PASSWORD" sftp user@host:/path
Warning: This exposes password in command history. Better alternative:
read -s PASS && sshpass -p "$PASS" sftp user@host:/path
3. Expect Automation
For complex automation needs, use Expect:
#!/usr/bin/expect
spawn sftp user@host
expect "password:"
send "PASSWORD\r"
interact
For serious implementations:
- Use SSH certificates instead of keys
- Implement secret management with Vault or AWS Secrets Manager
- Consider SCP or rsync for simpler transfers
Any method exposing passwords carries risks:
- Command history exposure (
~/.bash_history) - Process listing visibility (
ps aux) - Password leakage in logs