Run Shell Script From Your Website

Here’s how to run a shell script from your website. You’ll need 2 files.

Here’s the contents of foo.php. Wrap your output with ‘pre’ for better formatting.

<?php
$output = shell_exec('/var/www/html/bar.sh 2>&1');
echo "$output";

Here’s the content of bar.sh. Output will be displayed on web page.

#!/bin/bash
now="$(date +'%y%m%d')"
echo $now
aws s3 ls

MySQL Backup To S3 Bucket

Here’s my MySQL backup script to the S3 Bucket.

Just a couple of things about the script. It’s using …

  1. AWS CLI
  2. Mysqldump

They must be setup and configured to work properly.

#!/bin/bash
cd /root/database
TIMESTAMP=$(date +%Y-%m-%d)
S3FILE="s3://bucketname/sqlbackup/backup-$TIMESTAMP.sql"
/usr/bin/mysqldump dbname > dbname.sql
/usr/local/bin/aws s3 cp dbname.sql $S3FILE
sleep 3s
rm dbname.sql

Finally, set the S3 bucket with a 7 day retention. Backups older than 7 days are automatically deleted.