Install packages (debian):
sudo apt-get install -y jpegoptim optipng
Then get wordpress wp-content path, for example /var/www/website-example.com/wp-content/
and run the following commands:
find /var/www/website-example.com/wp-content/ -name "*.png" -exec optipng '{}' \;
find /var/www/website-example.com/wp-content/ -name "*.jpg" -exec jpegoptim --all-progressive --strip-all '{}' \;
Remember you can add them to crontab.