MySQL Create UTF-8 Encoded Database

Tags

,

MySQL Create UTF-8 Encoded Database

In mysql it’s easy to create utf-8 encoded database using command line, I’m using universe as the database’s name and SUPER_HEROS as the table’s name.

  • Create the script file

DROP SCHEMA IF EXISTS `universe`;

CREATE SCHEMA IF NOT EXISTS `universe` DEFAULT CHARACTER SET utf8

COLLATE utf8_general_ci;

USE `universe`;

DROP TABLE IF EXISTS `universe`.`SUPER_HEROS` ;

GRANT ALL ON universe.* TO ‘admin’@’localhost’ IDENTIFIED BY ‘admin’;

FLUSH PRIVILEGES;

CREATE TABLE IF NOT EXISTS `universe`.`SUPER_HEROS` (

`SUHR_ID` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,

`SUHR_NAME` VARCHAR(32) NOT NULL,

`SUHR_DESCRIPTION` TEXT NULL,

PRIMARY KEY (`SUHR_ID`),

UNIQUE INDEX `SUHR_ID_UNIQUE` (`SUHR_ID` ASC),

UNIQUE INDEX `SUHR_NAME_UNIQUE` (`SUHR_NAME` ASC))

ENGINE = InnoDB;

— —————————————————–

— Data for table `universe`.`SUPER_HEROS`

— —————————————————–

START TRANSACTION;

USE `universe`;

INSERT INTO `universe`.`SUPER_HEROS` (`SUHR_ID`, `SUHR_NAME`)

VALUES (NULL, ‘Superman’, ‘I am a superman’);

COMMIT;

  • Login mysql command line

mysql -u root -p<password>

  • Source the script file

source <path_to_script>

  • Check the database and table

SHOW DATABASE;

USER universe;

DESC SUPER_HEROS;

SELECT * FROM SUPER_HEROS;

Run Multiple Tomcat Instances on One Server

Tags

, ,

Run Multiple Tomcat Instances on One Server

Sometimes we may want to have multiple tomcat instances running on one server, because they may be using different Java version, or better performance, or load balance, etc… To achieve this we need to understand Tomcat structure first and then set up the configuration for different tomcat instances or services. Below instructions are based on Tomcat 7 running on CentOS 6.5.

Tomcat Structure

Tomcat Running Ports

Turn Tomcat into a Service

Service Script

Service Configuration

System V Runlevels

Tomcat Structure

When creating multiple instances of tomcat server, we need to play with the folders inside the server. These folders contain the actual scripts and code for the server. We have the option to either use the code base for tomcat in shared mode where all tomcat instances refer to the same physical code or we can create separate copies of these folder for each tomcat instance.

  • /bin : This directory contains the startup and shutdown scripts for both Windows and Linux.
  • /conf : This directory contains the main configuration files for Tomcat. The two most important are the server.xml and the global web.xml .
  • /server : This directory contains the Tomcat Java Archive files.
  • /lib : This directory contains Java Archive files that Tomcat is dependent upon.
  • /logs : This directory contains Tomcat’s log files.
  • /src : This directory contains the source code used by the Tomcat server. Once Tomcat is released, it will probably contain interfaces and abstract classes only.
  • /webapps : All web applications are deployed in this directory; it contains the WAR file.
  • /work : This is the directory in which Tomcat will place all servlets that are generated from JSPs. If you want to see exactly how a particular JSP is interpreted, look in this directory.

Tomcat Running Ports

Having a good understanding of tomcat ports is essential to manage the multiple instances of the same server installation. These ports are used by tomcat for startup, deployment and shutdown operations. The detail of each port is as:

  • Connector Port : This is the port where Apache Tomcat listen for the HTTP requests.
  • Shutdown Port : This port is used when we try to shutdown the Apache Tomcat Server.
  • AJP (Apache JServ Protocol) Connector Port : The Apache JServ Protocol (AJP) is a binary protocol that can conduct inbound requests from a web server through to an application server that sits behind the web server.
  • Redirect Port : Any redirection happening inside Apache Tomcat will happen through this port. In Apache TOMCAT there are two instance where redirectPort is mentioned. First one is for the Apache TOMCAT server and other one is for the AJP port.

Apache-Tomcat-Server-AJP-Port Apache-Tomcat-Server-Shutdown-Port

Apache-Tomcat-Server-Connector-Port

We need to make sure all tomcat instances use different ports above of HTTP, HTTPS, AJP, Redirect Port and SHUTDOWN. The configuration is in the file of $CATALINA_HOME/conf/server.xml.

Turn Tomcat into a Service

Essentially we want to have all tomcat instances (if only one as well) running as a service after we have the tomcat configured correctly. By doing this we can easily make tomcat run with different java version and start automatically with system bootup.

Service Script

We need to create the individual service script in /etc/init.d/ for each of the services we want tomcat running with. In the scripting file we need to specify the JAVA_HOME and CATALINA_HOME if the instance needs to run differently with the system wide settings. Here is a sample service script file named as my-service (I store my tomcat under /opt/my-service/):

#!/bin/bash

# description: my-service  Start Stop Restart

# processname: tomcat

# chkconfig: 234 20 80

name=my-service

JAVA_HOME=/etc/alternatives/java_sdk_1.7.0

export JAVA_HOME

PATH=$JAVA_HOME/bin:$PATH

export PATH

CATALINA_HOME=/opt/${name}/apache-tomcat-7.0.57

# have tomcat process running under user tomcat

# we need to make this script is runnable for user tomcat

# and tomcat location is writable for user tomcat

case $1 in

start)

/bin/su tomcat $CATALINA_HOME/bin/startup.sh

;;

stop)

/bin/su tomcat $CATALINA_HOME/bin/shutdown.sh

;;

restart)

/bin/su tomcat $CATALINA_HOME/bin/shutdown.sh

/bin/su tomcat $CATALINA_HOME/bin/startup.sh

;;

esac

exit 0

Also the script and tomcat installation need to be runnable and writable by tomcat user:

chmod 755 /etc/init.d/my-service

chown tomcat <tomcat_installation>

By now the service can easily be manipulated using service my-service start|stop|restart.

Service Configuration

We may also want to the service start automatically with system bootup. We need to add my-service to the chkconfig and make it automatically start:

chkconfig –add my-service

chkconfig –level 234 on

chkconfig –list my-service will show the config for my-service:

my-service                 0:off        1:off        2:on        3:on        4:on        5:off        6:off

System V Runlevels

A little words about runlevels of SysV init, there 6 six runlevels of CentOS:

  • 0 – Halt
  • 1 – Single-user text mode
  • 2 – Not used (user-definable)
  • 3 – Full multi-user text mode
  • 4 – Not used (user-definable)
  • 5 – Full multi-user graphical mode (with an X-based login screen)
  • 6 – Reboot

In general, users operate CentOS at runlevel 3 or 5 – both full multi-user modes.

CentOS Add nologin User

Tags

,

CentOS Add a User with Disabled Login

Sometimes we want to have some user on the server, they are just for the application running permission, but not necessary to be able to login. There are two approaches to achieve this, one is adding a new user with specifing nologin shell, and the other is to modifying an existing user with nologin shell. CentOS comes with a nologin shell located under /sbin/, we can specify nologin shell to the user when creating or modifying.

Add a New User with Disabled Login

useradd -s /sbin/nologin <username>

Modify an Existing User with Disabled Login

usermod -s /sbin/nologin <username>

 

Grails 2.4.x Create RESTful Service

Tags

,

Create RESTful Service with Grails 2.4.x

With Grails 2.3 (I assume 2.4 the same) it is really easy to create restful service. This tutorial is pretty simple, I just want to access localhost/StateService/state and get a response in json format:

[{

        'id': 1,

        'name': 'OH'

        

}]

Create Grails Project

grails createapp StateService

Create Domain Class

createdomainclass edu.osumc.bmi.ird.state.service.State

Edit State.groovy with the attributes

package edu.osumc.bmi.ird.state.service

import groovy.transform.EqualsAndHashCode

import groovy.transform.ToString

@ToString(includeNames = true, includeFields = true,

       excludes = 'dateCreated, lastUpdated, metaClass')

@EqualsAndHashCode

class State {

   // gorm default attributes

   Long id

   Long version

   // gorm timestamp

   Date dateCreated

   Date lastUpdated

   String name

   String fullName

   static constraints = {

       name blank: false, nullable: false, unique: true, minSize: 2, maxSize: 2

       fullName blank: false, nullable: false, minSize: 3, maxSize: 32

   }

}

Bootstrap Some Sample Data

import edu.osumc.bmi.ird.state.service.State

import grails.util.Environment

class BootStrap {

   def init = { servletContext ->

       switch (Environment.current) {

           case Environment.DEVELOPMENT:

               seedDevData()

               break;

       }

   }

   def destroy = {

   }

   private void seedDevData() {

       State.findByName("OH") ?: new State(name: "OH", fullName: "Ohio")

               .save(flush: true, failOnError: true)

       State.findByName("MI") ?: new State(name: "MI", fullName: "Michigan")

               .save(flush: true, failOnError: true)

       State.findByName("CA") ?: new State(name: "CA", fullName: "California")

               .save(flush: true, failOnError: true)

       assert State.count == 2

   }

}

Create a Controller

createcontroller edu.osumc.bmi.ird.state.service.State

Make Created Controller RESTful

From Grails document if we want to make a controller be a restful controller, just extending grails.rest.RestfulController.

package edu.osumc.bmi.ird.state.service

import grails.rest.RestfulController

class StateController extends RestfulController<State> {

   static responseFormats = ['json', 'xml']

   StateController() {

       super(State)

   }

}

Test the Service

Run the service: runapp in grails interactive mode

  • Testing in browser

        Access http://localhost:8080/StateService/state and get the result in json array:

        [{"class":"edu.osumc.bmi.ird.state.service.State","id":1,"dateCreated":"2015-04-07T19:21:06Z","fullName":"Ohio","lastUpdated":"2015-04-07T19:21:06Z","name":"OH"},{"class":"edu.osumc.bmi.ird.state.service.State","id":2,"dateCreated":"2015-04-07T19:21:06Z","fullName":"Michigan","lastUpdated":"2015-04-07T19:21:06Z","name":"MI"},{"class":"edu.osumc.bmi.ird.state.service.State","id":3,"dateCreated":"2015-04-07T19:21:06Z","fullName":"California","lastUpdated":"2015-04-07T19:21:06Z","name":"CA"}]

  • Testing using curl
  1. curl with json response

        $>>> curl X GET H "Accept:application/json" http://localhost:8080/StateService/state

[{"class":"edu.osumc.bmi.ird.state.service.State","id":1,"dateCreated":"2015-04-07T19:21:06Z","fullName":"Ohio","lastUpdated":"2015-04-07T19:21:06Z","name":"OH"},{"class":"edu.osumc.bmi.ird.state.service.State","id":2,"dateCreated":"2015-04-07T19:21:06Z","fullName":"Michigan","lastUpdated":"2015-04-07T19:21:06Z","name":"MI"},{"class":"edu.osumc.bmi.ird.state.service.State","id":3,"dateCreated":"2015-04-07T19:21:06Z","fullName":"California","lastUpdated":"2015-04-07T19:21:06Z","name":"CA"}]

  1. curl with xml response

        curl X GET H "Accept:application/xml" http://localhost:8080/StateService/state

<?xml version="1.0" encoding="UTF-8"?><list><state id="1"><dateCreated>2015-04-07 15:21:06.235 EDT</dateCreated><fullName>Ohio</fullName><lastUpdated>2015-04-07 15:21:06.235 EDT</lastUpdated><name>OH</name></state><state id="2"><dateCreated>2015-04-07 15:21:06.260 EDT</dateCreated><fullName>Michigan</fullName><lastUpdated>2015-04-07 15:21:06.260 EDT</lastUpdated><name>MI</name></state><state id="3"><dateCreated>2015-04-07 15:21:06.267 EDT</dateCreated><fullName>California</fullName><lastUpdated>2015-04-07 15:21:06.267 EDT</lastUpdated><name>CA</name></state></list>

  • Testing with Grails Spock
  1. Create Testing Spec

package edu.osumc.bmi.ird.state.service

import grails.test.mixin.Mock

import grails.test.mixin.TestFor

import spock.lang.Specification

@TestFor(StateController)

@Mock(State)

class StateControllerSpec extends Specification {

   def setup() {

   }

   def cleanup() {

   }

   void "test index returns all states in json format"() {

       given:

       new State(name: "OH", fullName: "Ohio")

               .save(flush: true, failOnError: true)

       new State(name: "MI", fullName: "Michigan")

               .save(flush: true, failOnError: true)

       new State(name: "CA", fullName: "California")

               .save(flush: true, failOnError: true)

       when:

       request.method = 'GET'

       response.format = 'json'

       controller.index()

       then:

       response.status == 200

   }

}

Run testing in grails interactive mode: test-app

Add URL Mapping

Now the service is responding to this url: localhost:8080/StateService/state, we want to add a url mapping to make it localhost:8080/StateService/service/state. Edit conf/UrlMappings.groovy :

class UrlMappings {

  static mappings = {

       "/$controller/$action?/$id?(.$format)?"{

           constraints {

               // apply constraints here

           }

       }

       "/"(view:"/index")

       "500"(view:'/error')

       // restful state service

       "/service/state"(resources: 'state')

  }

}

Now the service can be accessed with both urls.

Exclude Properties from Response

Until now the response contains all fields of the domains which is not the expectation we want. In real situation we’d like to hide some infos like lastUpdated and meta data of the class. To achieve this we need to edit conf/spring/resources.groovy file:

import edu.osumc.bmi.ird.state.service.State

import grails.rest.render.json.JsonRenderer

// Place your Spring DSL code here

beans = {

   stateJsonRenderer(JsonRenderer, State) {

       excludes = ['class', 'dateCreated']

   }

   stateXmlRenderer(JsonRenderer, State) {

       excludes = ['class', 'dateCreated']

   }

}

The bean’s name doesn’t matter, spring just scan the environment and put the beans in the spring context. Now when we access the url we got this:

http://localhost:8080/StateService/service/state

[{"id":1,"fullName":"Ohio","lastUpdated":"2015-04-07T20:01:06Z","name":"OH"},{"id":2,"fullName":"Michigan","lastUpdated":"2015-04-07T20:01:06Z","name":"MI"},{"id":3,"fullName":"California","lastUpdated":"2015-04-07T20:01:06Z","name":"CA"}]

If we only want to retrieve state with id 1:

http://localhost:8080/StateService/service/state/1

{"id":1,"fullName":"Ohio","lastUpdated":"2015-04-07T20:01:06Z","name":"OH"}

That’s it, this is all we need to do to create a restful service with grails 2.4.x. Source code is available at my github: RESTful StateService

Grails Criteria Query with DataTables

Tags

, ,

Grails Criteria Query with DataTables

This tutorial is about how to integrate Grails criteria query with DataTables pagination, filtering and sorting.

Grails version: 2.4

DataTables version: 1.10

Controller

Controller needs to parse request parameter to map DataTables to Grails criteria parameters.

class HomeController {

        def list() {

        def orderIndex = params.“order[0][column]”

        def index = “columns[“ + orderIndex + “][name]”

        def sort = params.“$index”

        def orderDir = params.“order[0][dir]”

        def filter = params.“search[value]”

        def criteria = Project.createCriteria()

        def recordsTotal = Project.countByUser(user)

        def projects = criteria.list(max: params.length, offset: params.start,

                sort: sort, order: orderDir) {

            and {

                eq(“user”, user)

                or {

                    ilike(‘name’, “%$filter%”)

                    ilike(‘description’, “%$filter%”)

                    ilike(‘tag’, “%$filter%”)

                }

            }

        }

        def dateFormat = message(code: ‘only.date.format’)

        def jsonProjects = []

        projects.each { project ->

            def jsonAnnotations = []

            project.annotations.each { annotation ->

                jsonAnnotations << [

                        annotation.id,

                        annotation.label

                ]

            }

            jsonProjects << [

                    project.id,

                    project.name,

                    project.description,

                    project.tag,

                    project.dateCreated.format(dateFormat)            ]

        }

        def data = [“data”           : jsonProjects,

                    “recordsFiltered”: projects.totalCount,

                    “recordsTotal”   : recordsTotal]

        render data as JSON

}

}

gsp

  1. Create a static table within html body

                 <table class=“display cell-border” id=“my-table”>

                    <thead>

                        <tr>

                            <th>Id</th>

                            <th>Name</th>

                            <th>Description</th>

                            <th>Tags</th>

                            <th>Created Time</th>

                           </tr>

                    </thead>

             <tbody></tbody>

                    </table>

  1. Initialize the table to be a DataTable with javascript

if (myTable == null) {

                    myTable = $(‘#my-table’).DataTable({

                        “processing”: true,

                        “serverSide”: true,

                        “ajax”: {

                            “url”: tableController/list“,

                            “dataType”: “json”

                        },

                        “paging”: true,

                        “columnDefs”: [

                            {“name”: “id”, “visible”: false, “targets”: 0},

                            {“name”: “name”, “width”: “10%”,

                                “render”: function (data, type, row) {

                                    return ‘<a href=’ +  + ‘/’ + row[0] + ‘>’ + data + ‘</a>’

                                },

                                “targets”: 1

                            },

                            {“name”: “description”, “width”: “35%”, “targets”: 2},

                            {“name”: “tag”, “width”: “30%”, “targets”: 3},

                            {“name”: “dateCreated”, “searchable”: “false”, “width”: “15%”, “targets”: 4}

 ]

                    });

                } else {

                    myTable.ajax.reload();

                }

Spring MVC UTF-8 Encoding

Tags

, ,

Spring MVC UTF-8 Encoding

In a spring MVC web application setting utf-8 encoding is tricky somehow. Since a web application involves backend database, middle tier application and frontend pages (jsps and javascripts), all those fields need to be taken care to make sure utf-8 encoded application works as expected.

Set UTF-8 Encoding in Database

Set UTF-8 Encoding with DataSource

Add UTF-8 Encoding Filter to Web Initializer

Make Controller Respond UTF-8 Encoded Content

Set Page Encode to Be UTF-8

Set UTF-8 Encoding in Tomcat

Set UTF-8 Encoding in Database

Depending on the database which is used setting utf-8 encoding is not generic, but it should be documented pretty detailed in the corresponding manual.

Set UTF-8 Encoding with DataSource

After the database is configured to support utf-8 encoding, the next step is to make sure the data source connection in spring is also utf-8 encoded. I’m using Java Configuration to configure my DataSource, here is the snippet of the code for my datasource bean definition.

@Bean(name = “dataSource”)

public DataSource dataSource() {

   LOG.debug(“Creating instance of singleton bean ‘” + BasicDataSource.class.getName() + “‘”);

   BasicDataSource dataSource = new BasicDataSource();

   dataSource.setDriverClassName(env.getProperty(“jdbc.driverClassName”));

   dataSource.setUrl(env.getProperty(“jdbc.url”));

   dataSource.setUsername(env.getProperty(“jdbc.username”));

   dataSource.setPassword(env.getProperty(“jdbc.password”));

   // requires utf 8 to support Chinese query

   dataSource.addConnectionProperty(“useUnicode”, “yes”); // make sure charset is utf-8

   dataSource.addConnectionProperty(“characterEncoding”, “UTF-8”); // make sure utf-8 charset

   return dataSource;

}

I have all env properties stored in an external properties files, and the last 2 properties for the connection is to set utf-8 encoding when initiating the database connection.

Add UTF-8 Encoding Filter to Web Initializer

If you go with Java configuration for spring mvc, create a Web app initialization extending

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer

 and override the method:

@Override

protected Filter[] getServletFilters() {

   // if encoding has issues we need to add UTF-8 encoding filter

   CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();

   encodingFilter.setForceEncoding(true);

   encodingFilter.setEncoding(“UTF-8”);

   // encoding filter must be the first one

   return new Filter[]{encodingFilter,

           new DelegatingFilterProxy(“springSecurityFilterChain”),

           new OpenEntityManagerInViewFilter()};

}

Note that filters order doesn’t matter, but the encodingFilter must be presented.

Make Controller Respond UTF-8 Encoded Content

If all above steps are taken care of the web app should already be able to support utf-8 encoding. But the for json response there is one more step to make sure spring also encode json response string as utf-8. On all the methods of the controller which respond json adding this annotation will solve the issue:

@RequestMapping(value = “”, method = RequestMethod.GET,

       produces = “application/json;charset=UTF-8”)

public

@ResponseBody

String list(HttpServletRequest request)

The key part is the produces parameter, if specify the produces you must have charset=UTF=8 set; You can also omit the produces and let spring use the default produces which will be utf-8 encoding.

Set Page Encode to Be UTF-8

On the jsps adding this meta data will make sure the page encode is utf-8.

<%@ page language=“java” contentType=“text/html; charset=UTF-8” pageEncoding=“UTF-8” %>

Set UTF-8 Encoding in Tomcat

This one is optional, but it’s better to do it if you use old version of tomcat. Add this encoding parameters to the connector tags of tomcat web.xml file.

 URIEncoding=“UTF-8” useBodyEncodingForURI=“true”

That’s it. Now the spring mvc application is able to support all major languages around the world. Even DataTables real time search works like a charm.

Grails Tests Classes under src/groovy

Tags

,

Grails: How to Test Classes under src/groovy

Groovy classes under src/groovy  are not a controller or service or a domain class, so unit testing those classes is a little bit tricky. Here is the right way to test them and make them aware by the grails context when invoking grails test-app.

  1. Since the test is a unit test, it should be created under the test/unit/<package>;
  2. The class must extends Groovy built-in base class GroovyTestCase;
  3. Make sure the filename of the test class matches the class name (unlike Java, the filename doesn’t need to match the filename of the target class).

By meeting all those 3 requirements the test class can be run manually or grails test-app.

Generate Random String with Groovy

Tags

Generate Random String with Groovy

Groovy makes really easy to generate random string sequence, here is the code snippet for random string generator:

def length = 16 // the size of the random string

def pool = [‘a‘..’z‘, A‘..’Z‘, 0..9, ‘-‘].flatten() // generating pool

Random random = new Random(System.currentTimeMillis())

// the loop should be from 0 to length – 1, then the char length would be length

def randomChars = (0..length 1).collect { pool[random.nextInt(pool.size())] }

def randomString = randomChars.join()

Generate SSH Key

Tags

,

Generate SSH Key

Check existing SSH keys

Generate a new SSH key

Add private key to ssh-agent

Add public key <fileName>.pub to the server eg. github.com

Test the connection with the server eg. github.com

(Optional) Make git use different keys based on hostname

  1. Check existing SSH keys

        ls al ~/.ssh

        # list all ssh keys if existing, one key pair can be use on multiple servers

  1. Generate a new SSH key

        sshkeygen t rsa C email@me.com f <keyName>

        # create a new ssh key pair using rsa algorithm, email as label

# and keyName as filename, id_rsa by default if not specified

# follow the prompt to enter file name(if not specified) and passphrase,

# at the end a fingerprint or id of the key would be given

  1. Add private key to ssh-agent

  • Ensure ssh-agent is enabled

                eval $(sshagent s)” # start the ssh-agent in the background

  • Add new private key to the agent

                sshadd ~/.ssh/<fileName>

  1. Add public key <fileName>.pub to the server eg. github.com

  2. Test the connection with the server eg. github.com

        ssh -i <fileName> -T git@github.com

        # i flag specifies the ssh file used, id_rsa would be used if not specified

        # T flag disabled pseudo-tty allocation

  1. (Optional) Make git use different keys based on hostname

        Git does not have i flag like ssh to specify the key file to use, but we can configure git to use the corresponding key files based on the host we try to git.

  • Create ~/.ssh/config file if not existing

        touch ~/.ssh/config

  • Add these to ~/.ssh/config file

Host GitLab

    HostName gitlab.com

    User git

    IdentityFile ~/.ssh/<gitlab-filename>

    IdentitiesOnly yes

Host github

    HostName github.com

    User git

    IdentityFile ~/.ssh/<github-filename>

    IdentitiesOnly yes

  • Test git connection

        Git should be able to pull/push if those keys are already added to the servers

SSH without a Password

Tags

, ,

SSH without a Password

SSH to a Remote Machine Without a Password

  1. Generate SSH key pairs on local machine
  • Create .ssh dir if not existing: mkdir -p $HOME/.ssh
  • Change permission for .ssh: chmod 0700 $HOME/.ssh
  • Generate key pairs: ssh-keygen
  • Follow the prompt
  • This should result in two files: $HOME/.ssh/id_rsa(private key) and $HOME/.ssh/id_rsa.pub(public key)
  • Copy public key to the remote machine:

scp $HOME/.ssh/id_rsa.pub <user>:<path>

  1. Append public key to the authorized keychain on remote machine
  • Create .ssh dir if not existing:

mkdir -p $HOME/.ssh

  • Change permission for .ssh:

chmod 0700 $HOME/.ssh

  • Append uploaded public key to the authorized keys:

cat <path>/id_rsa.pub >> $HOME/.ssh/authorized_keys

  • Change permission for authorized_keys:

chmod 0600 $HOME/.ssh/authorized_keys

  1. SSH to the remote machine on local machine
  • ssh -i $HOME/.ssh/id_rsa <user>
  • An alias can be created for future shortcut:

alias ssh<name>=’ssh -2 -x <user>