Working as a web developer, you will eventually get familiar with server configuration, like how to setting up Nginx or Apache, how to check production logs, how to tune server for better performance, etc. Almost all of those things are done via SSH. In the past, I had to log in to the machine I want to run a certain command to do something on server. Inspired by the funny story of a lazy developer (https://github.com/NARKOZ/hacker-scripts), I started getting the habit of automating every repetitive tasks. For example: every week, I need to check how many users are currently in the production database. Today I am going to show you how it can be accomplished by executing command remotely via SSH.
- Preparing your command
First of all, you need to prepare in advance how your command looks like. In general, it should be short and easy to remember because you don't want to put a long command over a single SSH, it will be very hard to read. I usually create a shell script file on server and then call that script remotely.
Here is one example of a script to connect to MySQL server and then execute SQL (on server)
SCRIPT="SELECT count(*) FROM users;" HOST="localhost" USER="root" PASSWORD="123" mysql -h $HOST -u $USER -p$PASSWORD MyAppDB -e $SCRIPT
In the above script, the MySQL Server is running on the same machine with the web server, its username is
root and password is
123, the database name is
MyAppDB, and our script will return number of rows in the
users table. Notice that there is no space between
-p and the password, and also no space between the
= operator and the environment variables.
If I put this in a file called
query_user.sh and grant
execute permission to it like this
chmod +x query_user.sh
I can run this shell script like this (assuming that I am in the folder containing the file)
- Calling it remotely
This is very simple because it looks very similar to how to login via SSH. The syntax is
ssh <username>@<host> <command_on_server>
In our example, assume that my username is
deploy and the host is
example.com, my SSH command will be:
ssh firstname.lastname@example.org ./query_user.sh
- Executing it in background
By default, the SSH session will not be ended until the script on server finishes. To let the SSH session run in background, we can add
ssh -f email@example.com ./query_user.sh
I hope this post is helpful to you. There are many tips like this and if you know how to apply them properly, your work will become much easier and you save time to do other great things.