Turning Commands Into a Bash Script

30 minutes
  • 4 Learning Objectives

About this Hands-on Lab

In this hands-on lab, we’re going to write a shell script for connecting to Linux Academy Linux servers from another Linux (or Mac) host, without having to first accept the RSA fingerprint.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Determine What Options Should Be Used with the `ssh` Command
  1. View the man page for the ssh command, and determine the option to use to disable host key checking.
    man ssh
  2. The syntax to use is:
    ssh -o StrictHostKeyChecking=no user@host
Build a Script from the Required Commands
  1. Create a bin folder in cloud_user‘s home directory.
    mkdir bin
  2. Use vim or nano to create the file lab.sh in the new bin folder.
    vim bin/lab.sh
  3. Start with the shebang at the top of the file.
    #!/bin/bash
  4. Add a line to ssh using the variable from above and taking the first parameter as the host address.
    ssh -o StrictHostKeyChecking=no $login_user@$1
  5. Add a line to set a variable for the login user.
    login_user=cloud_user
  6. Add two lines to make sure that that the first variable is not null and close the script.
    if [ -n $1 ]
    fi
  7. The completed script should look like this

    #!/bin/bash  
    
    login_user=cloud_user
    if [ -n $1 ]
    then
      ssh -o StrictHostKeyChecking=no $login_user@$1
    fi
  8. Then save the file by running:
    :wq!
Execute and Verify the Script
  1. Save the file, and make it executable.
    chmod u+x bin/lab.sh
  2. Run the script, passing 10.0.1.10 as the first parameter to be assigned to $1.
    ./bin/lab.sh 10.0.1.10
  3. Once prompted input the cloud_user‘s password.
Add the New `bin` Directory to the `PATH` Variable
  1. Append to the .bashrc file in cloud_user‘s home directory to add the new bin folder to the PATH environment variable.
    echo 'PATH="$HOME/bin:$PATH"' >> .bashrc
  2. Source .bashrc to pick up the change.
    source .bashrc
  3. Verify that you can run lab.sh without specifying the path to the script.
    lab.sh 10.0.1.10

Additional Resources

Your supervisor is tired of having to accept the RSA key fingerprint every time they log in to a new hands-on lab. They've asked you to write a shell script that can be run from their local Linux desktop to connect to these servers without prompting to accept the key.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?