AWS AMI Backup shell script

Prerequisites:
=============

Step: 1. Install Java :

# yum -y install java-1.7.0-openjdk
# export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
# java -version

Step: 2. Download & Unzip Amazon EC2 CLI Tools :

# yum -y install wget zip unzip
# cd /tmp
# wget http://s3.amazonaws.com/ec2-downloads/ec2-api-tools.zip
# unzip ec2-api-tools.zip

Step: 3. Install the Amazon EC2 CLI Tools :

# mkdir /usr/local/ec2
# mv ec2-api-tools-1.7.5.0 /usr/local/ec2/apitools/

Step: 4. Set variables :

# export EC2_HOME=/usr/local/ec2/apitools
# export PATH=$PATH:$EC2_HOME/bin

Step: 5. Add variables to Startup Script :

# cd etc/profile.d/
# vi aws.sh

export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
export EC2_HOME=/usr/local/ec2/apitools
export PATH=$PATH:$EC2_HOME/bin

-- Save & Quit (:wq)

# chmod +x aws.sh
# sounce aws.sh

Step: 6. Logged in into AWS Web Panel.

Step: 7. Go to IAM Panel.

-- Click on Users (tab)
-- Create New Users.
-- Give User Name.
-- Click on Create.
-- Download the Credential.
-- Close.
-- Click on Newly Created User.
-- Permission (tab)
-- Click on Attach Policy.
-- Search (AmazonEC2FullAccess) & Select it.
-- Attach Policy.

Access Key ID:  Provide your Access Key Id
Secret Access Key:  Provide your Secret Access Key

Step: 8. Finally Create AMI Auto Backup Script :

# vi /backups/scripts/aws-ami-backup.sh

#!/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/ec2/apitools/bin

# Please use env | grep EC2_HOME to find out your system's setting
EC2_HOME=/usr/local/ec2/apitools

# Please use env | grep JAVA_HOME to find out your system's setting
JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
date=`date +%d-%m-%Y_%H-%M-%S`
export EC2_HOME JAVA_HOME
export AWS_ACCESS_KEY=Provide your Access Key Id
export AWS_SECRET_KEY=Provide your Secret Access Key

# Regions reference: http://docs.aws.amazon.com/general/latest/gr/rande.html
region="ap-southeast-1"

# You can find your instance ID at AWS Manage Console
instanceID="i-c706e305"

# Your prefer AMI Name prefix
amiNamePrefix="SOUMYA-SOUMYATEST-AMI_$date"

# Your prefer AMI Description

amiDescription="Daily AMI backup"

# If you want to keep 7 days AMI backups, please set routine true otherwise set it false
routine=true

if [ $routine = true ]; then
    # Setup AMI Name
    amiName=$amiNamePrefix

    # Get AMI ID
    amiIDs=$(ec2-describe-images --region $region | grep 'ami-[a-z0-9]' | grep "$amiName" |cut -f 2)

    # Get Snapshot ID
    if [[ ! -z $amiIDs ]]; then
        snapshotIDs=$(ec2-describe-snapshots --region $region | grep $amiIDs | cut -f 2)
    fi
else
    # Setup AMI Name
    amiName=$amiNamePrefix

    # Get AMI ID
    amiIDs=$(ec2-describe-images --region $region | grep 'ami-[a-z0-9]' | cut -f 2)

    # Get Snapshot ID
    if [[ ! -z $amiIDs ]]; then
        snapshotIDs=$(ec2-describe-snapshots --region $region | cut -f 2)
    fi
fi

if [[ ! -z $amiIDs ]]; then
    # Deregister AMI
    for amiID in $amiIDs
    do
        ec2-deregister --region $region $amiID
    done

    # Delete snapshot
    for snapshotID in $snapshotIDs
    do
        ec2-delete-snapshot --region $region $snapshotID
    done
fi

# Create AMI
ec2-create-image $instanceID --region $region --name "$amiName" -d "$amiDescription" --no-reboot > /tmp/AMIBackup.txt

# Name Tag
amiid=`cat /tmp/AMIBackup.txt | cut -f2`
ec2addtag $amiid --tag Name=$amiName --region $region

-- Save & Quit (:wq)

# chmod 755 /backups/scripts/aws-ami-backup.sh

Step: 9. Schedule in Crontab :

# crontab -e

0 0 * * * /backups/scripts/aws-ami-backup.sh

-- Save & Quit (:wq)

Step: 10. Retstart the Cron Service :

# service crond restart

Done...!!!




Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.

Migrating SQL Users from one SQL Server To Another SQL Server Instance

Migraing SQL Users from one SQL Server To Another SQL Server Instance
=============================================================

Here i am Migrating User "soumya" from one SQL Server to Another SQL Server.

On Source Database:

-- Logged in as sa/system User
-- Expand Databases
-- Expand System Databases
-- Right click on master database
-- New Query.
-- Paste the below lines & Click Execute.

USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
  DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
  DECLARE @tempint int
  DECLARE @firstint int
  DECLARE @secondint int
  SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
  SELECT @firstint = FLOOR(@tempint/16)
  SELECT @secondint = @tempint - (@firstint*16)
  SELECT @charvalue = @charvalue +
    SUBSTRING(@hexstring, @firstint+1, 1) +
    SUBSTRING(@hexstring, @secondint+1, 1)
  SELECT @i = @i + 1
END

SELECT @hexvalue = @charvalue
GO

IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
  DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)

DECLARE @defaultdb sysname

IF (@login_name IS NULL)
  DECLARE login_curs CURSOR FOR

      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
  DECLARE login_curs CURSOR FOR


      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs

FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
  PRINT 'No login(s) found.'
  CLOSE login_curs
  DEALLOCATE login_curs
  RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
  IF (@@fetch_status <> -2)
  BEGIN
    PRINT ''
    SET @tmpstr = '-- Login: ' + @name
    PRINT @tmpstr
    IF (@type IN ( 'G', 'U'))
    BEGIN -- NT authenticated account/group

      SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
    END
    ELSE BEGIN -- SQL Server authentication
        -- obtain password and sid
            SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
        EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
        EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT

        -- obtain password policy state
        SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
        SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name

            SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'

        IF ( @is_policy_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
        END
        IF ( @is_expiration_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
        END
    END
    IF (@denylogin = 1)
    BEGIN -- login is denied access
      SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
    END
    ELSE IF (@hasaccess = 0)
    BEGIN -- login exists but does not have access
      SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
    END
    IF (@is_disabled = 1)
    BEGIN -- login is disabled
      SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
    END
    PRINT @tmpstr
  END

  FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
   END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO

-- After Successfully Executed the Command.
-- Expand master database.
-- Expand Programmability.
-- Expand Stored Procedures.
-- Click New Query.
-- Drag & Drop "dbo.sp_help_revlogin" on New Query Box.
-- Finally Click on Execute.
-- Copy the User Information.
-- Go To Another SQL Server Instance.
-- Expand Databases.
-- Expand System Databases.
-- Right click on master database.
-- New Query.
-- Paste the User Information & Click on Execute.

-- Login: soumya
CREATE LOGIN [soumya] WITH PASSWORD = 0x0100C0256FC7444529ADF74C8E7275968871444D6C1CE4ACA9CE HASHED, SID = 0x895CC8F6C6C9FE4D9188EF23B80E625B, DEFAULT_DATABASE = [master], CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF

Now in Destination server:-

Copy and Paste the above user creation tsql command to create the "soumya" user with its password:

CREATE LOGIN [soumya] WITH PASSWORD = 0x0100C0256FC7444529ADF74C8E7275968871444D6C1CE4ACA9CE HASHED, SID = 0x895CC8F6C6C9FE4D9188EF23B80E625B, DEFAULT_DATABASE = [master], CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF

Done...!!!





Please share your ideas and opinions about this topic.

If you like this post, then please share with others.
Please subscribe on email for every updates on mail.