In order to migrate Virtual machines from on premises to AWS we need to do the following things .


* Remove vmware tools

* create a user with sudo permission

* install ssh

*Enable DHCP option in NIC configuration



You must provide an Amazon S3 bucket and an IAM role named vmimport.

Amazon S3 Bucket

VM Import requires an Amazon S3 bucket to store your disk images, in the region where you want to import your VMs. You can create a bucket as follows, or use an existing bucket if you prefer.

(Optional) To create an S3 bucket

  1. Open the Amazon S3 console at
  2. Choose Create Bucket.
  3. In the Create a Bucket dialog box, do the following:
    1. For Bucket Name, type a name for your bucket. This name must be unique across all existing bucket names in Amazon S3. In some regions, there might be additional restrictions on bucket names. For more information, see Bucket Restrictions and Limitations in the Amazon Simple Storage Service Developer Guide.
    2. For Region, select the region that you want for your AMI.
    3. Choose Create.

VM Import Service Role

VM Import requires a role to perform certain operations in your account, such as downloading disk images from an Amazon S3 bucket. You must create a role named vmimport with a trust relationship policy document that allows VM Import to assume the role, and you must attach an IAM policy to the role.

To create the service role

  1. Create a file named trust-policy.json with the following policy:
       "Version": "2012-10-17",
       "Statement": [
             "Effect": "Allow",
             "Principal": { "Service": "" },
             "Action": "sts:AssumeRole",
             "Condition": {
                   "sts:Externalid": "vmimport"

    You can save the file anywhere on your computer. Take note of the location of the file, because you’ll specify the file in the next step.

  2. Use the create-role command to create a role named vmimport and give VM Import/Export access to it. Ensure that you specify the full path to the location of the trust-policy.json file.
    aws iam create-role --role-name vmimport --assume-role-policy-document file://trust-policy.json
  3. Create a file named role-policy.json with the following policy, where disk-image-file-bucket is the bucket where the disk images are stored:
       "Version": "2012-10-17",
       "Statement": [
             "Effect": "Allow",
             "Action": [
             "Resource": [
                "arn:aws:s3:::disk-image-file-bucket" ] }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::disk-image-file-bucket/*" ] }, { "Effect": "Allow", "Action":[ "ec2:ModifySnapshotAttribute", "ec2:CopySnapshot", "ec2:RegisterImage", "ec2:Describe*" ], "Resource": "*" } ] }
  4. Use the following put-role-policy command to attach the policy to the role created above. Ensure that you specify the full path to the location of the role-policy.json file.
    aws iam put-role-policy --role-name vmimport --policy-name vmimport --policy-document file://role-policy.json

For more information about IAM roles, see IAM Roles in the IAM User Guide.

Upload the Image to Amazon S3

Upload your VM image file to your Amazon S3 bucket using the upload tool of your choice. For information about uploading files through the S3 console, see Uploading Objects into Amazon S3. For information about the Enhanced Uploader Java applet, see Using the Enhanced Uploader.

Import the VM

After you upload your VM image file to Amazon S3, you can use the AWS CLI to import the image. These tools accept either a URL (public Amazon S3 file, a signed GET URL for private Amazon S3 files) or the Amazon S3 bucket and path to the disk file.

Use the import-image command to create an import image task.

Example 1: Import an OVA

aws ec2 import-image --description "Windows 2008 OVA" --license-type BYOL --disk-containers file://containers.json

The following is an example containers.json file.

    "Description": "Windows 2008 OVA", "Format": "ova", "UserBucket": { "S3Bucket": "my-import-bucket", "S3Key": "vms/my-windows-2008-vm.ova" } }]

Example 2: Import Multiple Disks

$ C:\> aws ec2 import-image --description "Windows 2008 VMDKs" --license-type BYOL --disk-containers file://containers.json

The following is an example containers.json file.

    "Description": "First disk", "Format": "vmdk", "UserBucket": { "S3Bucket": "my-import-bucket", "S3Key": "disks/my-windows-2008-vm-disk1.vmdk" } }, { "Description": "Second disk", "Format": "vmdk", "UserBucket": { "S3Bucket": "my-import-bucket", "S3Key": "disks/my-windows-2008-vm-disk2.vmdk" } } ]

Check the Status of the Import Task

Use the describe-import-image-tasks command to return the status of an import task.

Status values include the following:

  • active — The import task is in progress.
  • deleting — The import task is being canceled.
  • deleted — The import task is canceled.
  • updating — Import status is updating.
  • validating — The imported image is being validated.
  • converting — The imported image is being converted into an AMI.
  • completed — The import task is completed and the AMI is ready to use.
aws ec2 describe-import-image-tasks --import-task-ids import-ami-abcd1234

(Optional) Cancel an Import Task

Use the cancel-import-task command to cancel an active import task.

aws ec2 cancel-import-task --import-task-id import-ami-abcd1234



Status check example output


Thats it you will have AMI of your Virtual machine on the region which you used. use that AMI and launch a new instance.



In this post, we’ll cover how to automate EBS snapshots for your AWS infrastructure using Lambda and CloudWatch.   We’ll build a solution that creates nightly snapshots for volumes attached to EC2 instances and deletes any snapshots older than 10 days.   This will work across all AWS regions.

Lambda offers the ability to execute “serverless” code which means that AWS will provide the run-time platform for us.   It currently supports the following languages: Node.js, Java, C# and Python.   We’ll be using Python to write our functions in this article.

We’ll use a CloudWatch rule to trigger the execution of the Lambda functions based on a cron expression.

IAM Role

Before we write any code, we need to create an IAM role that has permissions to do the following:

  • Retrieve information about volumes and snapshots from EC2
  • Take new snapshots using the CreateSnapshot API call
  • Delete snapshots using the DeleteSnapshot API call
  • Write logs to CloudWatch for debugging

In the AWS management console, we’ll go to IAM > Roles > Create New Role.   We name our role “ebs-snapshots-role”.

For Role Type, we select AWS Lambda.   This will grant the Lambda service permissions to assume the role.

On the next page, we won’t select any of the managed policies so move on to Next Step.

Go back to the Roles page and select the newly created role.   Under the Permissions tab, you’ll find a link to create a custom inline policy.

Paste the JSON below for the policy:

    "Version": "2012-10-17",
    "Statement": [
            "Effect": "Allow",
            "Action": [
            "Resource": "arn:aws:logs:*:*:*"
            "Effect": "Allow",
            "Action": "ec2:Describe*",
            "Resource": "*"
            "Effect": "Allow",
            "Action": [
            "Resource": [

Create Snapshots Function in Lambda

Now, we can move on to writing the code to create snapshots.   In the Lambda console, go to Functions > Create a Lambda Function -> Configure function and use the following parameters:

In our code, we’ll be using Boto library which is the AWS SDK for Python.

Paste the code below into the code pane:

# Backup all in-use volumes in all regions

import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    # Get list of regions
    regions = ec2.describe_regions().get('Regions',[] )

    # Iterate over regions
    for region in regions:
        print "Checking region %s " % region['RegionName']

        # Connect to region
        ec2 = boto3.client('ec2', region_name=reg)
        # Get all in-use volumes in all regions  
        result = ec2.describe_volumes( Filters=[{'Name': 'status', 'Values': ['in-use']}])
        for volume in result['Volumes']:
            print "Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone'])
            # Create snapshot
            result = ec2.create_snapshot(VolumeId=volume['VolumeId'],Description='Created by Lambda backup function ebs-snapshots')
            # Get snapshot resource 
            ec2resource = boto3.resource('ec2', region_name=reg)
            snapshot = ec2resource.Snapshot(result['SnapshotId'])
            volumename = 'N/A'
            # Find name tag for volume if it exists
            if 'Tags' in volume:
                for tags in volume['Tags']:
                    if tags["Key"] == 'Name':
                        volumename = tags["Value"]
            # Add volume name to snapshot for easier identification
            snapshot.create_tags(Tags=[{'Key': 'Name','Value': volumename}])

The code will create snapshots for any in-use volumes across all regions.   It will also add the name of the volume to the snapshot name tag so it’s easier for us to identify whenever we view the list of snapshots.

Next, select the role we created in the Lamba function handler and role section.

The default timeout for Lambda functions is 3 seconds, which is too short for our task.  Let’s increase the timeout to 1 minute under Advanced Settings.    This will give our function enough time to kick off the snapshot process for each volume.

Click Next then Create Function in the review page to finish.

Schedule Trigger as CloudWatch Rule

Navigate to the Triggers tab and click on Add Trigger which brings up the following window:

Snap 2017-02-13 at 22.58.19.png

Selecting CloudWatch Event – Schedule from the dropdown list allows us to configure a rule based on a schedule. It’s important to note that the times listed in the cron entry are in UTC.

You’ll be prompted to enter a name, description, and schedule for the rule.

It’s important to note that the times listed for the cron expression are in UTC.  In the example below, we are scheduling the Lambda function to run each weeknight at 11pm UTC.


We can test our function immediately by click on the Save and Test button in the function page.   This will execute the function and show the results in the console at the bottom of the page.

Snap 2017-02-13 at 23.48.10.png


After verifying that the function runs successfully, we can take a look at the CloudWatch logs by clicking on the link shown in the Log Output section.

You’ll notice a Log Group was created with the name /aws/lambda/ebs-create-snapshots.  Select the most recent Log Stream to view individual messages:

11:00:19  START RequestId: bb6def8d-f26d-11e6-8983-89eca50275e0 Version: $LATEST
11:00:21  Backing up volume vol-0c0b66f7fd875964a in us-east-2a
11:00:22  END RequestId: bb6def8d-f26d-11e6-8983-89eca50275e0
11:00:22  REPORT RequestId: bb6def8d-f26d-11e6-8983-89eca50275e0 Duration: 3256.15 ms Billed Duration: 3300 ms Memory Size: 128 MB Max Memory Used: 40 MB

Delete Snapshots Function in Lambda

Let’s take a look at how we can delete snapshots older than the retention period which we’ll say is 10 days.

Before using the code below, you’ll want to replace account_id with your AWS account number and adjust retention_days according to your needs.

# Delete snapshots older than retention period

import boto3
from botocore.exceptions import ClientError

from datetime import datetime,timedelta

def delete_snapshot(snapshot_id, reg):
    print "Deleting snapshot %s " % (snapshot_id)
        ec2resource = boto3.resource('ec2', region_name=reg)
        snapshot = ec2resource.Snapshot(snapshot_id)
    except ClientError as e:
        print "Caught exception: %s" % e
def lambda_handler(event, context):
    # Get current timestamp in UTC
    now =

	# AWS Account ID    
	account_id = '1234567890'
    # Define retention period in days
    retention_days = 10
    # Create EC2 client
    ec2 = boto3.client('ec2')
    # Get list of regions
    regions = ec2.describe_regions().get('Regions',[] )

    # Iterate over regions
    for region in regions:
        print "Checking region %s " % region['RegionName']
        # Connect to region
        ec2 = boto3.client('ec2', region_name=reg)
        # Filtering by snapshot timestamp comparison is not supported
        # So we grab all snapshot id's
        result = ec2.describe_snapshots( OwnerIds=[account_id] )
        for snapshot in result['Snapshots']:
            print "Checking snapshot %s which was created on %s" % (snapshot['SnapshotId'],snapshot['StartTime'])
            # Remove timezone info from snapshot in order for comparison to work below
            snapshot_time = snapshot['StartTime'].replace(tzinfo=None)
            # Subtract snapshot time from now returns a timedelta 
            # Check if the timedelta is greater than retention days
            if (now - snapshot_time) > timedelta(retention_days):
                print "Snapshot is older than configured retention of %d days" % (retention_days)
                delete_snapshot(snapshot['SnapshotId'], reg)
                print "Snapshot is newer than configured retention of %d days so we keep it" % (retention_days)          

Its for document purpose source from :


For those of you who didn’t know, OwnCloud is a free and open-source software which enables you to create a private “file-hosting” cloud. OwnCloud is similar to DropBox service with the diference of being free to download and install on your private server. Owncloud made by PHP and backend database MySQL (MariaDB), SQLLite or PostgreSQL. OwnCloud also enables you to easily view and sync address book, calendar events, tasks and bookmarks. You can access it via the good looking and easy to use web interface or install OwnCloud client on your Desktop or Laptop machine (supports Linux, Windows and Mac OSX).

This article assumes you have at least basic knowledge of linux, know how to use the shell, and most importantly, you host your site on your own VPS. The installation is quite simple. I will show you through the step by step installation OwnCloud 8 on Ubuntu 14.04.

Install OwnCloud 8 on Ubuntu 14.04

Step 1. First of all log in to your server as root and make sure that all packages are up to date.



apt-get update

Apt-get upgrade

Step 2. Instal Apache web server on your Ubuntu 14.04 VPS if it is not already installed.


apt-get install apache2

Step 3. Next, install PHP on your server.


apt-get install php5 php5-mysql

Once the installation is done add the following PHP modules required by OwnCloud:


apt-get install php5-gd php5-json php5-curl php5-intl php5-mcrypt php5-imagick

Step 4. Install MySQL database server.


apt-get install mysql-server

By default, MySQL is not hardened. You can secure MySQL using the mysql_secure_installation script. you should read and below each steps carefully which will set root password, remove anonymous users, disallow remote root login, and remove the test database and access to secure MySQL.



Step 5. Create a new MySQL database for OwnCloud using the following commands.









#mysql -u root -p

Enter password:

mysql> CREATE USER ‘ownclouduser’@’localhost’ IDENTIFIED BY ‘YOURPASSWORD’;

mysql> CREATE DATABASE ownclouddb;

mysql> GRANT ALL ON ownclouddb.* TO ‘ownclouduser’@’localhost’;


mysql> exit

Step 6. Installing Owncloud 8.

First we will need to download the latest stable release of OwnCloud on your server (at the time version 8.2.2).



tar -xvf owncloud-8.2.2.tar.bz2 -C /var/www/html/

Set the directory permissions:


chown www-data:www-data -R /var/www/html/owncloud/

Step 7. Configuring Apache for OwnCloud.

While configuring Apache web server, it is recommended that you to enable .htaccess to get a enhanced security features, by default .htaccess is disabled in Apache server. To enable it, open your virtual host file and make AllowOverride is set to All.For example, here i used external config file instead of modifying main file.












### nano /etc/apache2/sites-available/owncloud.conf

<IfModule mod_alias.c>

Alias /owncloud /var/www/html/owncloud


<Directory “/var/www/html/owncloud”>

Options Indexes FollowSymLinks

AllowOverride All

Order allow,deny

allow from all


Remember to restart all services related to Apache server.


service apache2 restart

Step 8. Access OwnCloud application.

Navigate to or http://your-ip-address and follow the easy instructions. Enter username and password for the administrator user account, click on the ‘Advanced options’ hyperlink and enter the data directory (or leave the default setting), then enter database username, database password, database name, host (localhost) and click ‘Finish setup’


Change the data directory as ” /var/ownclouddata ” to restrict public access of all user data

mkdir /var/ownclouddata

chown -R www-data:www-data /var/ownclouddata

if you faced any issue while configure this OwnCloud initial setup drop all tables in the given data base and

complete the setup again.

Two-step verification (also known as Two-factor authentication, abbreviated to TFA) is a process involving two stages to verify the identity of an entity trying to access services in a computer or in a network. This is a special case of a multi-factor authentication which might involve only one of the three authentication factors (a knowledge factor, a possession factor, and an inheritance factor) for both steps. If each step involves a different authentication factor then the two-step verification is additionally two-factor authentication.
Link to original post:

Google’s two-step verification process

Google was one of the first Internet companies to introduce a two-step verification process. To access a Google service using the two-step verification process, a user has to go through the following two stages:

The first step is to log in using the username and password. This is an application of the knowledge factor.
The implementation of the second step requires a mobile phone or the Google Authenticator application, which is an application of the possession factor.

If the user opts to use a mobile phone, he/she has to register his/her phone number with Google. When one attempts to authenticate with username and password, Google will send via SMS a new, unique code to the phone. Receiving the SMS demonstrates that the user has the phone (or, in the case of GSM like networks the appropriate SIM chip).

If the user opts to use the Google Authenticator (or another supported code generator application), he/she simply opens the application, which generates a new code every 30 seconds. This code is to be entered to complete the log in process. As a backup option in case the registered mobile phone or device running Google Authenticator is lost, stolen, or otherwise unavailable, the user can print a set of static single-use backup codes (also the knowledge factor) and store them in a safe place.

The following are some other sites which offer two-step verification service:

  1. Amazon Web Services,
  2. ANX
  4. Apple ID
  5. Authy
  7. Bitstamp
  9. Box
  10. Dropbox
  11. eBay
  12. Etrade
  13. Evernote
  14. Facebook
  15. GitHub
  16. GoDaddy
  17. HootSuite
  18. Lastpass
  19. LinkedIn
  20. LocalBitcoins
  21. Microsoft
  22. MongoLab
  23. Namecheap
  24. PayPal
  25. SocialFlow
  26. timetotrade
  27. Tumblr
  28. Twitter
  29. Viaduct
  30. WordPress
  31. Yahoo! Mail
  33. zoho

Google Authenticator

Google Authenticator implements TOTP security tokens from RFC6238 in mobile apps made by Google, sometimes branded “two-step authentication”. The Authenticator provides a six digit one-time password users must provide in addition to their username and password to log into Google services or other sites. The Authenticator can also generate codes for third party applications, such as password managers or file hosting services. Some versions of the software are open source.
[Source: WikiPedia]

14 - Securing SSH with two factor authentication using Google Authenticator - blackMORE Ops

Note: Google Authenticator doesn’t “call home” to Google — all the work happens on your SSH server and your phone. Google Authenticator is a open-source software, that means you can check the codes yourself. I guess after what happened with openSSL, that’s not a bad idea after all.

In this article I will demonstrate how to secure SSH by setting up Two Factor Authentication (TFA) with Google Authenticator for the following Linux operating systems:

  1. Debian
  2. Ubuntu
  3. Linux Mint
  4. Kali Linux
  5. Red Hat
  6. CentOS
  7. Fedora

Google Authenticator can be used in the following smartphones:

  1. Android,
  2. iOS and
  3. Blackberry.

I am not too sure if you can use this on a Windows Based phone (i.e. new Nokia phones or Windows Mobiles devices). Feel free to try and report back.

App Download Links as follows:

  1. Android:
  2. iOS:
  3. Blackberry:

More detailed per device install instructions can be found on this page:

The implementation is exactly same except for some package name differences. So you can implement this in any Linux Operating System that uses these packages.


Followings are the requirements for using Google Authenticator on your system:

  1. A PC running Linux
  2. A smartphone
  3. A running SSH server on your machine.

In case you don’t have SSH server running, just follow this guide to install openSSH server.

Step 1: Install dependencies for Google Authenticator Module

You need to have either root or sudo privileges on the machine where you want to secure SSH by enabling Two Factor Authention using Google Authenticator. Login to your machine and use the following commands to install required dependency packages:

On Debian, Kali, Ubuntu, Linux Mint (they all are Debian based system that uses aptitude as package manager i.e. apt-get/aptitude)

apt-get install libpam0g-dev

1 - Install dependencies for Google Authenticator PAM module - blackMORE Ops

On Red Hat, CentOS and Fedora (they all are RedHat based where you use yum as the package manager):

yum install pam-devel

That’s it. That should install the necessary dependencies on your system. In case you have a very restricted system where you dont have GCC, make and wget, you can install them using the following command(s):

yum install make gcc wget
apt-get install make gcc wget

Step 2: Download Google Authenticator Module

Google Authenticator is available on GoogleCode website.


You can just copy paste the codes below to download and extract Google Authenticator codes. I personally use Kali Linux, that means I am always logged in as root user, if you’re using any of the other Linux distributions like Debian, Ubuntu, Linux Mint, Red Hat, CentOS or Fedora where you don’t usually login as root user, then you should choose your own directory to download and extract these codes.

To download Source code of the Google Authenticator PAM library module use the following command:

root@kali:~# wget

At the time of writing this article, v1.0 was available.

2 - Download Google Authenticator PAM module from GoogleCode - blackMORE Ops

Now extract your tarball:

root@kali:~# tar -xvf libpam-google-authenticator-1.0-source.tar.bz2

Change directory to the extracted folder:

root@kali:~# cd libpam-google-authenticator-1.0/

3 - Extract Google Authenticator PAM module from GoogleCode - blackMORE Ops

Step 3: Compile and Install Google Authenticator PAM module

So far we’ve installed dependencies, downloaded and extracted Google Authenticator PAM module. Now we need to compile the codes and install compiled software on our system.
use the following command to compile your downloaded source codes:

root@kali:~/libpam-google-authenticator-1.0# make

4 - Compile extracted Google Authenticator PAM module from GoogleCode - blackMORE Ops

Now install Google Authenticator PAM module on your system:

root@kali:~/libpam-google-authenticator-1.0# make install

5 - Install compiled Google Authenticator PAM module from GoogleCode - blackMORE Ops

Step 4: Run and configure Google Authenticator

Just run Google Authenticator PAM module from command line to configure it for your system:

Run Google Authenticator PAM module using the following command:

root@kali:~/libpam-google-authenticator-1.0# google-authenticator

It should present you with bunch of question where you get to choose Y or N . Let’s have a quick look at those questions and the outputs.

Do you want authentication tokens to be time-based (y/n) y|0&cht=qr&chl=otpauth://totp/root@kali%3Fsecret%3DWKHM6UVJNTPYSPTQ
Your new secret key is: WKHM6UVJNTPYSPTQ
Your verification code is 434260
Your emergency scratch codes are:

So on your first question, you get a secret key, Your new secret key is: WKHM6UVJNTPYSPTQ and 5 emergency scratch codes. You use the emergency key on your mobile so that you can get the correct verification code next time you login. Emergency codes are used when you’ve lost your mobile.
Next it asks you if you want to use this for your root account? Me being root users, I’ve chosen Yes.

Do you want me to update your "/root/.google_authenticator" file (y/n) y

Next up, it asks you if you want to disallow multiple uses of the same verification code. Unless you have a good reason not to, choose Yes.

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y

Next part is time based login. From the point of getting the code on your mobile to typing in to your login prompt, 30 seconds should be more than enough. If you’r time sync is bad on your system or you’ve giving the code to someone over phone or you are a VERY slow keyboard warrior, I see no reason to change it. Select Yes here.

By default, tokens are good for 30 seconds and in order to compensate for
possible time-skew between the client and the server, we allow an extra
token before and after the current time. If you experience problems with poor
time synchronization, you can increase the window from its default
size of 1:30min to about 4min. Do you want to do so (y/n) y

Last up, well, of course we want to enable rate-limiting, by enabling this, you ensure that only 3 login attempts every 30s can be made.

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting (y/n) y

This finishes your initial setup for Google Authenticator PAM module. Now we need to configure PAM and SSH to actually use this technique. This is really awesome.

6 - Configure google-authenticator PAM module for the first time - blackMORE Ops

Note: Leave this terminal window open (DO NOT CLOSE). We need the codes for next steps.

Step 5: Configure SSH to use Google Authenticator PAM Module

Open your PAM configuration file /etc/pam.d/sshd

root@kali:~# vi /etc/pam.d/sshd

and add the following line:

auth       required

7 - Configure SSHD PAM to use Google Authenticator PAM Module - blackMORE Ops

Next up, open your SSH configuration file /etc/ssh/sshd_config

root@kali:~# vi /etc/ssh/sshd_config

and modify the line containing ChallengeResponseAuthentication no:

ChallengeResponseAuthentication no
(change it to)
ChallengeResponseAuthentication yes

8 - Configure sshd_config PAM to use Google Authenticator PAM Module - blackMORE Ops

To have these changes take effect, restart SSH server:

service ssh restart
service sshd restart
/etc/init.d/ssh restart
/etc/init.d/sshd restart

Why 4 commands? Depending on your Linux distribution, some refers SSH Daemon as SSHD, some as SSH, some got service module installed, some requires you to go into /etc/init.d folder and restart SSH service manually.

For GUI Authentication:

Finally, add the following line to /etc/pam.d/gdm-password file:

auth required

Save and close the file. On your next login, you should see a prompt for a verification code:

Fig.04: Google Authenticator code to protect Linux desktop login

Fig.04: Google Authenticator code to protect Linux desktop login

Step 6: Configure your SmartPhone for Google Authenticator App

Like I said before, Google Authenticator can be used in the following smartphones:

  1. Android:
  2. iOS:
  3. Blackberry:

More detailed per device install instructions can be found on this page:

Assuming you managed to install the App properly, Launch your Google Authenticator app in your SmartPhone.

From Menu select Set up account

9 - Configure SMARTPhone to use Google Authenticator - blackMORE Ops

Step 6.1: Google Authenticator Setup Account

Remember the secret key you got when you initialized Google-Authenticator PAM module on your computer? I hope you still got that window open. Select Enter provided key.

10 - Select Enter provided key on SMARTPhone to use Google Authenticator - blackMORE Ops

Next window you give it a name (something you can remember or relates to your workstation .. i.e. Home Workstation or My SuperAwesome LinuxBox … I’m going to use blackMORE Ops as the name.

Type in your Secret Key on the next field and click on Add button.

11 - Manually enter name and secret key on SMARTPhone to use Google Authenticator - blackMORE Ops

Once it’s added it will generate a one time verification code (pin number) that will keep changing every 30 seconds.

Step 7: Login to your computer via SSH

Because I am doing all these in the same computer I will just login to localhost (IP: If you got 2 or more machines or VirtualBox/VMWare machines then you can try to login from a different one. One thing to note, you MUST have SSH server running.

In case you don’t have SSH server running, just follow this guide to install openSSH server.

So we type in the following command: (this is where you need to find out your SSH server’s IP address, I’ve shown using localhost or IP but this can be anything from an IP, FQDN or Domain name.)

root@kali:~# ssh

and immediately you see a prompt asking for Verification code. This is your Google Authenticator code that you get from your Google Authenticator Mobile App.

12 - Verification Key on SMARTPhone to use Google Authenticator - blackMORE Ops

Type in the numbers from your SmartPhones Google Authenticator App and then it will prompt your for your password. Type in your password to login now.

13 - Securely SSH and enter Google Authenticator Verification Key and password to login to SSH - blackMORE Ops

If you failed to type in the Verification code within 30 seconds, you have to try the next code shown on your SmartPhones Google Authenticator App. Awesome? Wouldn’t you agree?

Alternatives to Google Authenticator SmartPhone App:

In case you don’t own a SmartPhone or don’t want to use any, you can use the following add-on on your FireFox or IceWeasel browser:

FireFox/IceWeasel App: GAuth Authenticator

15 - Secure SSH with two factor authentication using Google Authenticator from FireFox- blackMORE Ops

Interesting Fact:


Got a response from the dev behind the Google Authenticator add-on for Chrome, Gerard Braad, who explained that Google have taken it down but gave no explanation as to why even after being asked several times.

The Firefox version is still available though and work great. Hopefully he may look into the issue with the Chrome version and re-submit.

Here is the FF version for those wishing to use it:


How about that?

[ Source:!topic/chrome/P9rTLaeyHjg ]


Securing SSH with two factor authentication using Google Authenticator is possibly the best security model you can out there for free. You can always restrict SSH by IP, change port, rate-limit and do all sorts of crazy stuffs. But those who wants to open SSH to the outside world and implement all these extra security models (i.e. Brute-force detection etc.) have to constantly worry about the fact that who is trying is and what you’ve missed while securing your system. Securing SSH with two factor authentication using Google Authenticator possibly relieves you from that worry and you stop getting emails in the middle of the night saying someone tried to login via SSH X amount of times.

Source from:


I searched so many sites but the following method worked perfectly i have write this for help other who are looking  for this replication features:


PostgreSQL is a great advanced open source database. It offers many features, one of them being database replication. PostgreSQL 9.4 offers many different solutions to the replication problems, each one of them having it’s number of up’s and down’s. In the end it is up to the system or database administrator to decide which solution is best for specific scenario.

In the following post i decided to present how to configure PostgreSQL synchronous streaming database replication. Follow the steps closely and by the end of this tutorial you will have a working master/standby synchronous PostgreSQL replication. The benefit of a synchronous PostgreSQL replication over an asynchronous is that in case of master PostgreSQL database server failure you are sure you did not lose any data. The database client connected to the master PostgreSQL database gets a success message only once the data is written to both, master and standby PostgreSQL database server therefore there is no chance of loosing valuable data in the process.

Please note that the master/standby configuration actually means that the master server is in read/write mode while the standby server is in read-only mode. The read-only mode can however still be useful for reporting or similar activity.

Configure PostgreSQL Synchronous Streaming Database Replication

1. Install and Initialize PostgreSQL 9.4

To start configuring PostgreSQL Synchronous Streaming Database Replication i assume you have successfully installed and initialized PostgreSQL 9.4 on both linux servers you would like to use.

You can follow my posts on “Install PostgreSQL 9.3 on CentOS 6” or “Install PostgreSQL 9.4 on CentOS 7” if you need any help.


Stop firewall first.

/etc/init.d/iptables stop

2. Create PostgreSQL Replication Role

For the PostgreSQL Synchronous Streaming Database Replication to work, the standby instance connects to the master instance using a database user with replication privileges. Therefore we need to create a role and allow it to be used for replication purposes. Do this on the master instance.

Connect to master PostgreSQL server via “psql” and issue the following command:

postgres=# CREATE ROLE replication WITH REPLICATION PASSWORD 'password' LOGIN;

3. PostgreSQL Listen on IP Address

By default PostgreSQL only listens on “localhost” therefore denying outside connections to the database server. Firstly we must make the PostgreSQL database server to listen on desired IP address, which can be reconfigured in “/var/lib/pgsql/9.4/data/postgresql.conf” configuration file. Do this on the master instance.

Find the following line:

#listen_addresses = 'localhost'

Uncomment it and change to the desired IP address as follows:

listen_addresses = ''

Be sure to restart PostgreSQL service for changes to take effect.

4. Allow Replication Connection

You also need to allow connections from the PostgreSQL standby instance using the newly created replication role. You can configure this in “/var/lib/pgsql/9.4/data/pg_hba.conf” configuration file. Do this on the master instance.

Append the following lines at the bottom of configuration file – change the IP address with the one of your standby PostgreSQL server instance:

host replication replication trust

Note that by applying the “trust” for “replication” user from slave IP address “” this will allow connection to master PostgreSQL instance without password authentication.

Be sure to restart PostgreSQL service for changes to take effect.

5. Configure Streaming Parameters on Master

You need to edit “/var/lib/pgsql/9.4/data/postgresql.conf” configuration file and change some parameters accordingly to configure the PostgreSQL streaming replication. Do this on the master instance.

Find the following parameters in “postgresql.conf” and configure them as follows (uncomment if required):


wal_level = hot_standby # This sets slave server in read-only mode
fsync = on # Force synchronization
synchronous_commit = on # Enable synchronous commit
wal_sync_method = open_sync # Write WAL files with open() option O_SYNC


max_wal_senders = 1 # Max number of WAL senders - one slave, one sender
synchronous_standby_names = 'slave_node1' # Make this up, but remember it, will be used on slave instance configuration file

6. Start and Stop Master PostgreSQL

Once “postgresql.conf” file was reconfigured for “hot_standby” we need to start it to write out WAL logs with this configuration enabled. Once the master PostgreSQL has successfully started you can turn it off again.

7. Sync Data – Master to Slave

While both PostgreSQL instances are down, use rsync or some other tool to copy all of the contents in folder “/var/lib/pgsql/” from master PostgreSQL instance to slave PostgreSQL instance.

Skip the “/var/lib/pgsql/9.4/data/postgresql.conf” and “/var/lib/pgsql/9.4/data/pg_hba.conf” configuration files:

[root@node-1 /]# rsync -avr --exclude postgresql.conf --exclude pg_hba.conf /var/lib/pgsql/

8. Configure Streaming Parameters on Slave

Your PostgreSQL Synchronous Streaming Database Replication is almost up and running. Now you just need to open up the “/var/lib/pgsql/9.4/data/postgresql.conf” configuration file and apply the following change:

hot_standby = on
hot_standby_feedback = on

Create a new PostgreSQL slave instance specific configuration file “/var/lib/pgsql/recovery.conf”. Insert the following lines to “recovery.conf” file:

standby_mode = 'on'
primary_conninfo = 'host= port=5432 user=replication application_name=slave_node1'

The “recovery.conf” file provides information required for successful slave PostgreSQL connection to master instance. Note that IP address of the master instance must be changed accordingly along with the port number. Also the “application_name” is the “synchronous_standby_names” parameter configured on master PostgreSQL instance.

Change the owner of “/var/lib/pgsql/recovery.conf” to “postgres” user and make it rw for owner only:

[root@node-2 /]# chown postgres:postgres /var/lib/pgsql/9.4/data/recovery.conf
[root@node-2 /]# chmod 600 /var/lib/pgsql/9.4/data/recovery.conf

9. Start Slave PostgreSQL

Start slave PostgreSQL instance and check if the recovering process is up and running:

[root@node-2 /]# service postgresql-9.4 start
Redirecting to /bin/systemctl start postgresql-9.4.service
[root@node-2 /]# ps auxf |grep postgres
root 6692 0.0 0.1 112640 984 pts/0 S+ 15:13 0:00 _ grep --color=auto postgres
postgres 6679 0.1 2.0 337480 15212 ? S 15:13 0:00 /usr/pgsql-9.4/bin/postgres -D /var/lib/pgsql/9.4/data
postgres 6680 0.0 0.1 192596 1364 ? Ss 15:13 0:00 _ postgres: logger process 
postgres 6681 0.0 0.2 337596 2240 ? Ss 15:13 0:00 _ postgres: startup process recovering 000000010000000000000001
postgres 6682 0.0 0.2 337480 1676 ? Ss 15:13 0:00 _ postgres: checkpointer process 
postgres 6683 0.0 0.2 337480 1684 ? Ss 15:13 0:00 _ postgres: writer process 
postgres 6684 0.0 0.2 192724 1576 ? Ss 15:13 0:00 _ postgres: stats collector process

10. Start Master PostgreSQL

Start master PostgreSQL instance and check if the WAL sender process is up and running:

[root@node-1 /]# service postgresql-9.4 start
Redirecting to /bin/systemctl start postgresql-9.4.service
[root@node-1 /]# ps auxf |grep postgres
root 28875 0.0 0.1 112640 984 pts/0 S+ 15:14 0:00 _ grep --color=auto postgres
postgres 28864 0.1 1.9 337444 15196 ? S 15:14 0:00 /usr/pgsql-9.4/bin/postgres -D /var/lib/pgsql/9.4/data
postgres 28865 0.0 0.1 190496 1340 ? Ss 15:14 0:00 _ postgres: logger process 
postgres 28867 0.0 0.2 337444 1688 ? Ss 15:14 0:00 _ postgres: checkpointer process 
postgres 28868 0.0 0.2 337444 1696 ? Ss 15:14 0:00 _ postgres: writer process 
postgres 28869 0.0 0.2 337444 1692 ? Ss 15:14 0:00 _ postgres: wal writer process 
postgres 28870 0.0 0.3 337844 2560 ? Ss 15:14 0:00 _ postgres: autovacuum launcher process 
postgres 28871 0.0 0.2 192724 1756 ? Ss 15:14 0:00 _ postgres: stats collector process 
postgres 28873 0.6 0.4 338240 3092 ? Ss 15:14 0:00 _ postgres: wal sender process replication streaming 0/1718C90

11. Check PostgreSQL Synchronous Streaming Database Replication Status

Connect to the master PostgreSQL instance and run the following query to check the replication status:

postgres=# SELECT * FROM pg_stat_replication;
 pid | usesysid | usename | application_name | client_addr | client_hostname | client_port | backend_start | backend_xmin | state | sent_location | write_location | flush_location | rep
lay_location | sync_priority | sync_state 
 28383 | 16384 | replication | slave_node1 | | | 53789 | 2015-08-10 14:56:13.610889+02 | | streaming | 0/1718D38 | 0/1718D38 | 0/1718D38 | 0/1718D38 | 1 | sync
(1 row)

As you can see the PostgreSQL Synchronous Streaming Database Replication status is OK, the state is “streaming” and the sync_state is “sync” which means the configured replication is synchronous.





Install Oracle Java JDK 6/7/8 on Ubuntu 13.04 / 12.10 / 12.04

Before you install it, remove OpenJDK, if you have it installed:

$ sudo apt-get purge openjdk*

To install Java 8/7/6, do this:

In order not to get issues with the add-apt-repository command, install the following package:

$ sudo apt-get install software-properties-common

Add the PPA:

$ sudo add-apt-repository ppa:webupd8team/java

Update the repo index:

$ sudo apt-get update

Install Java 8:

$ sudo apt-get install oracle-java8-installer

Or, install Java 7:

$ sudo apt-get install oracle-java7-installer

Or, install Java 6:

$ sudo apt-get install oracle-java6-installer

set the java home in /etc/profile

sudo gedit /etc/profile

export JAVA_HOME
export JRE_HOME
export PATH

then execute the javapos.bin file

Create a file in /etc/init.d location named as adempiere like /etc/ini.d/adempiere, copy the given below script into the adempiere file and grant the execution permission by following command “chmod +x /etc/init.d/adempier” Use the following script and replace the ADEMPIERE_HOME and ADEMPIERE_USER with your current requirement. after that use the following command to make adempiere run on startup

“chkconfig adempiere on”  for centos

“update-rc.d adempiere defaults” for ubuntu


# chkconfig: 2345 99 1
# description: Starts and stops the Adempiere ERP system

#Check for valid ADEMPIERE_HOME
if [ -f $ADEMPIERE_HOME/utils/ ]; then
. ./ Server
echo “Unable to locate, ADEMPIERE_HOME invalid?”

start() {

su – $ADEMPIERE_USER -m -c “cd $ADEMPIERE_HOME/utils; ./ &” >> $CONSOLE_LOG 2>&1

stop() {
su – $ADEMPIERE_USER -m -c “cd $ADEMPIERE_HOME/utils; ./ &” >> $CONSOLE_LOG 2>&1

restart() {

case “$1” in
sleep 30
echo “Usage: $0 {start|stop|restart}”
exit 1

E-Mail notification for Every ssh Login

Posted: November 14, 2015 in Linux

I was tried to configure my ubuntu server to send email notification for every ssh login and i found a blog that is worked for me so i posted this blog to help other to get this easier.

Sometimes you just want something simple. Here’s how you can be notified every time someone logs into a Linux system via ssh (Secure Shell). We’ve assumed that your users run the bash shell, but the same principle can be adopted for other shells.

Put the following in /etc/profile

if [ -n “$SSH_CLIENT” ]; then
TEXT=”$(date): ssh login to ${USER}@$(hostname -f)”
TEXT=”$TEXT from $(echo $SSH_CLIENT|awk ‘{print $1}’)”
echo $TEXT|mail -s “ssh login” you@your.domain

How it works The script /etc/profile is executed at every login (for bash shell users). The if statement will only return true if the user has logged in via ssh, which in turn will cause the indented code block to be run. Next, we then build the text of the message:
$(date) will be replaced by the output of the “date” command
${USER} will be replaced by the user’s login name
$(hostname -f) will be replaced by the full hostname of the system being logged into
The second TEXT line adds to the first, giving the IP address of the system this user is logging in from.

Finally, the generated text is sent in an email to your address.

Linux will, by default, record every system login, whether by ssh or not, in the system log files, but sometimes – particularly for a system that is seldom accessed via ssh – a quick and dirty notification can be useful.

If you are looking for svn server installation without apache and you need to grant access to particular user to the particular project use this following method it worked for me and right now i am using this in my environment with ubuntu 14.04.

If you plan to expose your Subversion (SVN) repository through your firewall, I would use only HTTPS or SVN+SSH (never straight HTTP or SVN). I prefer SVN+SSH because there is no Apache or SSL setup required, so it is easier to get going (but a little less convenient because you can’t access your repository in a web browser). Second, if you are a home-hoster like me, the SVN protocol serves up over a non-80 port, which is good because some ISP’s (*cough* Verizon) block port 80.

These instructions assume SSH is already active on the server.


Install Subversion

The usual:

sudo apt-get install subversion


Add your local user and the anonymous web user (www-data) to a new group called “subversion”. Change “rbrooks” below accordingly.

sudo groupadd subversion
sudo usermod -a -G subversion rbrooks
sudo usermod -a -G subversion www-data

I like to always verify that it succeeded.

id rbrooks
id www-data

Verify that you see “(subversion)” in the above output.

Create a place for your repositories and permission it. Its location doesn’t necessarily need to be /home/svn.

sudo mkdir /home/svn
cd /home/svn
sudo mkdir myproject
sudo chown -R www-data:subversion myproject
sudo chmod -R g+rws myproject

Create Repository

Create a repository and permission it again in the same way we did above.

sudo svnadmin create /home/svn/myproject
sudo chown -R www-data:subversion /home/svn/myproject
sudo chmod -R g+rws /home/svn/myproject

Some people opt to create a single repository, then make all of their projects subfolders of that. I would recommend you create a separate repository for each project. This way, projects are isolated so they can be permissioned differently if need be. You may decide you need to allow Mikael from Sweden into your project at some point. You may not want him to see all of your other projects (especially some of your questionable side projects). Plus, if you are connecting the repository to a project-management system with an SVN repository browser (eg, Trac), these systems often have a one-to-one relationship between their concept of “Project” and its SVN repository.

Access Control

Edit SVN config file for the new repository:

sudo nano /home/svn/myproject/conf/svnserve.conf

Uncomment (remove the # from) the following line:

password-db = passwd

Ctrl-X to exit and save.

Change the UN(Username) and PW(Password):

sudo nano /home/svn/myproject/conf/passwd

Uncomment one of the example lines under [users], and change to your username and password:

rbrooks = mypassword

Exit and save.

Start SVN Server

Important thing is need to logout or reboot for group permission and modification
take effect

svnserve -d -r /home/svn

Subversion daemon will start in the background and you will be returned to the command prompt. SVN begins listening on default port 3690.


Test from a client machine. We’re going to create a directory in the repository, verify that it exists, then delete it. Change path and username accordingly based on your setup.

Create Directory

svn mkdir -m 'Created Test directory' --username rbrooks svn://hostname/myproject/test

It will ask you for your password. It will be what you placed into the passwd file earlier. If the directory was created successfully, you should see Committed revision 1. Username and password are cached from this point forward. You don’t need to pass the --username param again.


Verify that the folder exists using SVN’s ls command:

svn ls svn://hostname/myproject

SVN should respond with test/.


Test SVN over SSH:

svn ls svn+ssh://hostname/home/svn/myproject

Important: You must use the full path (/home/svn/myproject) to access SVN repository using this access method.

Delete Directory

svn rm -m 'Deleted Test directory' svn+ssh://hostname/home/svn/myproject/test


If you want to expose your repository to the Internet, forward port 3690 to your SVN server. Port forwarding and firewall configuration are beyond the scope of this article.

Filed under Linux

Source :

Step 1: Install Apache

First, clean-up yum:

sudo yum clean all

As a matter of best practice we’ll update our packages:

sudo yum -y update

Installing Apache is as simple as running just one command:

sudo yum -y install httpd

Step 2: Allow Apache Through the Firewall

Allow the default HTTP and HTTPS port, ports 80 and 443, through firewalld:

sudo firewall-cmd --permanent --add-port=80/tcp

sudo firewall-cmd --permanent --add-port=443/tcp

And reload the firewall:

sudo firewall-cmd --reload

Step 3: Configure Apache to Start on Boot

And then start Apache:

sudo systemctl start httpd

Be sure that Apache starts at boot:

sudo systemctl enable httpd

To check the status of Apache:

sudo systemctl status httpd

To stop Apache:

sudo systemctl stop httpd

Step Two — Install MySQL (MariaDB)


sudo yum install mariadb-server mariadb
sudo systemctl start mariadb
sudo mysql_secure_installation
sudo systemctl enable mariadb.service