Automate SSH Logins with sshpass: Install, Options, and Secure Usage
This guide explains how to install sshpass on Linux, details its command‑line options, and provides practical examples for automating SSH, SCP, and rsync operations while highlighting security considerations and safer alternatives for production environments.
When managing Linux servers, repeatedly entering passwords for SSH connections can be cumbersome; sshpass offers a lightweight way to supply passwords non‑interactively.
Installation
# RedHat/CentOS
yum -y install sshpass
# Debian/Ubuntu
apt-get install sshpassSyntax
sshpass (options)Options
-f filename: read the password from a file. -d number: read the password from the given file descriptor. -p password: provide the password directly on the command line (insecure). -e: read the password from the environment variable SSHPASS or from standard input if the variable is not set. -P prompt: specify the password prompt string to look for. -v: enable verbose output. -h: display help information. -V: print version information.
Only one of -f, -d, -p or -e may be used at a time.
Usage Examples
Directly pass a password to run a remote command: sshpass -p your_password ssh -p 22 root@IP Check disk usage on the remote host:
sshpass -p your_password ssh -p 22 root@IP 'df -h'Test a remote port with telnet via SSH:
sshpass -p your_password ssh -p 22 root@IP 'telnet targetIP targetPort'Read the password from a file:
sshpass -f your_password_filename ssh -p 22 root@IPUse an environment variable (safer than -p) :
export SSHPASS='your_password'
echo $SSHPASS
sshpass -e ssh -p 22 root@IPTo make the variable persistent, add the export line to /etc/profile and reload it with source /etc/profile.
Combine sshpass with scp for automated file transfer:
scp -r /etc/nginx/nginx.conf --rsh="sshpass -p 'your_password' ssh -l jacktian" IP:/home/jacktianCombine sshpass with rsync for backup synchronization:
rsync --rsh="sshpass -p 'your_password' ssh -l jacktian" IP:/data/backup/ /backup/These methods expose passwords in command lines, environment variables, or scripts and are therefore insecure for production use; consider key‑based authentication or other secure mechanisms instead.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
