To automate remote server access securely, you can write a Bash script that accepts an IP address and password as arguments. This script utilizes the
sshpass utility to provide credentials non-interactively, allowing you to execute commands on a target machine without manual input. This approach is ideal for simple automation tasks where managing SSH keys might be overkill or impractical.
Prerequisites and Installation
Before writing the script, ensure your system has the necessary tools installed. The standard OpenSSH client handles the connection, but it does not support password authentication in scripts by default due to security concerns. You need
sshpass, a lightweight utility designed specifically for this purpose. On Debian-based systems like Ubuntu, install it using:
sudo apt-get install sshpass
On Red Hat-based systems such as CentOS or Fedora, use:
sudo yum install sshpass
Verify the installation by running
sshpass -V. If the command returns a version number, the tool is ready. Without this package, any attempt to pass passwords via standard SSH will fail because the prompt cannot be automated easily.
Script Structure and Argument Handling
A robust script must handle its inputs correctly. We define two variables: one for the destination IP and one for the password. It is crucial to validate these inputs to prevent errors when running the script. Here is a basic structure:
#!/bin/bash
# Check if both arguments are provided
if [ $# -ne 2 ]; then
echo "Usage: $0 <DESTINATION_IP> <PASSWORD>"
exit 1
fi
DEST_IP=$1
PASSWORD=$2
The script checks the number of arguments (
$#). If it is not exactly two, it prints usage instructions and exits. This prevents partial execution. The first argument becomes
DEST_IP and the second becomes
PASSWORD. Always quote variables when passing them to avoid issues with spaces or special characters. For more details on handling complex filenames and quoting, see
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting.
Executing Commands with SSH Pass
The core functionality relies on the
sshpass command. It prefixes the
ssh command and provides the password via the
-p flag. To execute a single command, such as checking disk space, use the following syntax:
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no user@$DEST_IP "df -h"
Several important flags are used here. The
-o StrictHostKeyChecking=no option disables the host key verification prompt. In automated scripts, you cannot answer "yes" to accept the fingerprint, so disabling this check allows the connection to proceed automatically. Note that this reduces security slightly by making you vulnerable to man-in-the-middle attacks, but it is often acceptable for trusted internal networks.
You can replace
"df -h" with any valid shell command. To run multiple commands, wrap them in quotes and separate them with semicolons:
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no user@$DEST_IP "uptime; whoami"
This executes both uptime and whoami sequentially on the remote host.
Security Best Practices
While
sshpass is convenient, it stores passwords in plain text within the command line. Other users on the system might see these passwords in process lists. To mitigate this risk, consider using environment variables instead of direct arguments:
export SSH_PASS="your_password"
sshpass -p "$SSH_PASS" ssh ...
Alternatively, use SSH keys for production environments. Keys are more secure and do not require password management. If you encounter permission issues despite correct credentials, refer to
Fixing Permission denied with OpenSSH: Manually adding authorized_keys for troubleshooting steps related to key configuration.
For persistent connections or more complex scripting needs, consider embedding scripts within other scripts to modularize your logic. See
Running a script inside another script for advanced techniques.
Troubleshooting Common Errors
If the script fails, check the output carefully. A common error is "Permission denied (publickey,password)." This usually means the username or password is incorrect, or the SSH service is not running on the target. Another issue is "kex_exchange_identification," which indicates a problem with the key exchange protocol. Review
Troubleshooting kex_exchange_identification Error in Linux SSH Connection for solutions.
Ensure the remote user exists and has SSH access enabled. Also, verify that the firewall on the destination allows port 22 traffic. If you are connecting to network devices like Cisco routers, additional permissions may apply. See
Permission denied when trying to SSH into CISCO virtual router for device-specific advice.
Frequently Asked Questions
Is sshpass safe to use in production?
It is generally not recommended for high-security production environments because passwords appear in process listings. Use SSH keys whenever possible for better security and reliability.
How do I handle special characters in passwords?
Enclose the password variable in double quotes when passing it to sshpass. If the password contains dollar signs or backticks, escape them or use single quotes around the variable expansion if appropriate.
Can I run interactive commands like nano?
No, sshpass works best with non-interactive commands. Interactive editors require a pseudo-terminal, which complicates automation. Use command-line tools like sed or awk for text processing instead.
What if the remote server uses a non-standard SSH port?
Add the
-p PORT_NUMBER flag to the ssh command itself, not sshpass. For example:
ssh -p 2222 user@ip. Ensure sshpass passes this flag correctly to the underlying ssh client.
Why does StrictHostKeyChecking cause warnings?
Disabling strict host key checking removes fingerprint verification. While convenient for scripts, it exposes you to MITM attacks. Only disable it on trusted local networks or add known hosts to the config file manually.