BASH

Securely Execute Commands on Remote Servers via SSH

Learn to securely run commands on remote servers using SSH. Execute single commands, multi-line scripts, and pass arguments for server management.

#!/bin/bash
REMOTE_USER="ubuntu"
REMOTE_HOST="your-server-ip-or-hostname"
APP_PATH="/var/www/my-app"

# 1. Execute a single command remotely
echo "Checking remote disk space:"
ssh "$REMOTE_USER@$REMOTE_HOST" "df -h $APP_PATH"

# 2. Execute a command with variables passed from local
NEW_VERSION="2.1.0"
echo "Setting remote app version to $NEW_VERSION:"
ssh "$REMOTE_USER@$REMOTE_HOST" "echo \"New version deployed: $NEW_VERSION\" > $APP_PATH/version.txt"

# 3. Execute a multi-line script remotely (using heredoc)
echo "Performing remote cleanup and restart:"
ssh -T "$REMOTE_USER@$REMOTE_HOST" <<'EOF'
  echo "Running cleanup in $APP_PATH..."
  cd "$APP_PATH" || exit 1
  rm -rf node_modules/*.bak # Example cleanup
  echo "Restarting service..."
  sudo systemctl restart my-web-app.service
  echo "Remote script finished."
EOF

if [ $? -eq 0 ]; then
  echo "Remote operations completed successfully."
else
  echo "Remote operations failed."
fi
How it works: This script demonstrates how to execute commands on a remote server using SSH. It covers running single commands, passing local variables to remote commands, and executing multi-line scripts using a heredoc for more complex operations. The `-T` flag for heredocs disables pseudo-terminal allocation, which is often preferred for automated scripts. This is a fundamental skill for web developers managing remote infrastructure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs