Tuesday, April 19, 2016

Groovy LDAP access

Groovy script to access and modify LDAP or Active Directory using groovy ldap library.

Need following library:
groovy-ldap.jar

Class loading:
this.getClass().classLoader.rootLoader.addURL(new File("lib/groovy-ldap.jar").toURL()); import org.apache.directory.groovyldap.*;

Connecting LDAP:
LDAP = Class.forName("org.apache.directory.groovyldap.LDAP"); SearchScope = Class.forName("org.apache.directory.groovyldap.SearchScope"); host = "<ldap_host_addr>"; ad_user = "<ldap_priv_userid>"; ad_password = "<password>"; ldap = LDAP.newInstance(host, ad_user, ad_password); println "Connected to AD => $host";

Reading an entry:
search_str = "uid=<uid_info>*"; //* regex match entries = ldap.search(search_str, "<ldap_ou_path>", SearchScope.ONE); print "${entries.size} entries are found\n\n"; for (entry in entries) { print """ DN: ${entry.dn} Common name: ${entry.cn} uid: ${entry.uid} Object classes: ${entry.objectclass} """ }

Modify an entry:
//user dn is needed; it wont modify cn dn = "<dn_of_entry_to_be_modified>"; mods = [ ["REPLACE", [<field_name_1>: "<new_value_1>"]], ["REPLACE", [<field_name_2>: "<new_value_2>"]], ["ADD", [<new_field>: "<new_value>"]] ] ldap.modify(dn, mods); print "LDAP entry modified\n";


Groovy OIM Access

Groovy script to access Oracle Identity Management using OIM Client library.
Need following libraries:
spring.jar
oimclient.jar
wlfullclient.jar
authwl.conf file content:
xellerate{ weblogic.security.auth.login.UsernamePasswordLoginModule required debug=true; };

Class loading:
#!/usr/bin/env groovy this.getClass().classLoader.rootLoader.addURL(new File("lib/spring.jar").toURL()); this.getClass().classLoader.rootLoader.addURL(new File("lib/oimclient.jar").toURL()); this.getClass().classLoader.rootLoader.addURL(new File("lib/wlfullclient.jar").toURL()); import oracle.iam.platform.*; import oracle.iam.identity.usermgmt.api.*;

Connecting OIM:
String oimUrl = "<server_url>"; String oimAdmin = "<privileged_user>"; String oimPasswd = "<password>"; String authwlFileName = "authwl.conf"; String authwl = getClass().getClassLoader().getResource(authwlFileName).toString(); System.setProperty("java.security.auth.login.config", authwl); System.setProperty("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); System.setProperty("java.naming.provider.url", oimUrl); System.setProperty("OIM.AppServerType", "wls"); System.setProperty("APPSERVER_TYPE", "wls"); def OIMClient = Class.forName("oracle.iam.platform.OIMClient").newInstance(); Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); env.put("java.naming.provider.url", oimUrl); OIMClient.login(oimAdmin, oimPasswd.toCharArray(), env); println "Connected to OIM => ${oimUrl}\n";

Read an entry:
usrMgr = OIMClient.getService(Class.forName("oracle.iam.identity.usermgmt.api.UserManager")); //Parameters to be read from OIM. Add additional fields based on need usrAttrs = new HashSet<String>(); usrAttrs.add("Common Name"); usrAttrs.add("Display Name"); usrAttrs.add("Email"); usrAttrs.add("First Name"); usrAttrs.add("Initials"); usrAttrs.add("Last Name"); usrAttrs.add("User Login"); user = usrMgr.getDetails("User Login", "<user_login_unique_value>", usrAttrs); //Print usrAttrs.each { println "$it \t\t=> ${user.getAttribute(it)}"; }

Modify an entry:
usrMgr = OIMClient.getService(Class.forName("oracle.iam.identity.usermgmt.api.UserManager")); //collect entityid HashSet<String> retAttrs = new HashSet<String>(); user = usrMgr.getDetails("User Login", "<user_login>", retAttrs); entityId = user.getEntityId(); //create user entry using entityid updateUser = Class.forName("oracle.iam.identity.usermgmt.vo.User").newInstance(entityId); //update the user updateUser.setAttribute("<field_name>", "<new_value>"); //refer OIM form mappings for attribute name usrMgr.modify(updateUser); println "User modified";

Friday, October 23, 2015

YAML Loader - Ruby

Sample YAML Loader:


Assume your yaml file 'email_credential.yml' exists in same directory and in the format below:

email:
  smtp_server: smtp.gmail.com
  smtp_port: 587


Here is the simple snippet to load YAML and collect data:

begin
  yml = YAML.load_file("email_credentials.yml")
  
  email = yml['email']['smtp_server']
  eport = yml['email']['smtp_port']
  
rescue Exception => e
  puts "Email credential YAML loading issue \n" + e.to_s
end

Website Monitor - Ruby Script

Simple Ruby Script file to check the web site and post an email using gmail service.

This script contains 2 main parts

  1. Checking website - for response OK and content
  2. Email to admin on failure [using gmail]

Checking Website:

    url = URI.parse(web_url)
  net_conn = Net::HTTP.new(url.host, url.port)
  net_conn.use_ssl = url.scheme == "https"
  res = net_conn.get('/')

   We can check res.code == 200 and verify res.body includes the content we wanted to see.

Email [Using gmail]

  NOTE: Gmail needs TLS encryption; so enable it before start sending msg
   
    smtp = Net::SMTP.new("smtp.gmail.com", 587)
    smtp.enable_starttls #gmail needs this encryption
    smtp.start("DOMAIN_FILLER", <gmail_acc>, <gmail_pwd>, :logindo |s| 
      s.send_message(<msg>, <gmail_acc>, <to>)
    end  

  Sample GMAIL Msg format:
   msg = [
    "From: WebMonitor <from_addr>",
    "To: Admin <to_addr>",
    "Subject: <subject>",
    "",
    "Hi,",
    "!!MORE DETAILED MSG!!"
  ].join("\r\n");


Gist: https://gist.github.com/sivajankan/8278d75c39bc5a8260ae

The script can be added to crontab to do automated testing

Thursday, August 20, 2015

Selenium - IE remote browser setup

Setup Selenium -  IE remote browser


  1. Install Java. If you are setting up from a base level testing VM, you may need to first install Java.
  2. Download following files from https://code.google.com/p/selenium/downloads/list into your windows machine (This page mostly has latest versions. Pick them)
    • a. selenium-server-standalone-2.39.0.jar
    • b. IEDriverServer _Win32_2.39.0.zip (There is version for 64 bit; pick appropriate version)
  3. Place the jar file and extracted exe file from zip, into C:\SeleniumServer folder
  4. In Command Prompt and navigate to 'C:\SeleniumServer'
  5. Run the command to start the standalone selenium server
java -jar selenium-server-standalone-2.35.0.jar -Djava.util.logging.Level=OFF -Dwebdriver.ie.driver="C:\SeleniumServer\IEDriverServer.exe"

Monday, July 6, 2015

Cap Deploy [Capistrano]

Capistrano

Ref:
http://capistranorb.com/
https://github.com/capistrano/ # Shows list of all capistrano repos
https://github.com/capistrano/capistrano
https://github.com/capistrano/rails
https://github.com/capistrano/passenger



Gemfile


gem 'capistrano'
gem 'capistrano-rails'
gem 'capistrano-passenger'
gem 'capistrano-rvm'  #if your preference is RVM



$> bundle install
$> bundle exec cap install #Make sure files are created
$> bundle exec cap install STAGES=production  #add additional env seperated by ','

Limited gem installation [selected env]
$> bundle install --without development test


Capfile


require 'capistrano/rails'

#or
require 'capistrano/rvm'
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano/passenger'

#For rbenv
require 'capistrano/rbenv'
require 'capistrano/chruby'



Ref: http://capistranorb.com/documentation/getting-started/configuration/

config/deploy.rb


set :application, '<app_name>'
set :repo_url, 'git@.... <git repo>'

set :linked_files, fetch(:linked_files, []).push('config/database.yml')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')

set :keep_releases, 5



config/deploy/production.rb

server '<dest_server>', user: '<dest_server_user>', roles: %w{web db app}
set :deploy_to, "/var/www/html/<dir>"

set :passenger_restart_command, 'passenger-config restart-app'

set :passenger_restart_options, -> { "#{deploy_to} --ignore-app-not-running" }

Adding tasks

Ref: http://capistranorb.com/documentation/getting-started/cold-start/

in create lib/capistrano/tasks/access_check.rake file, and add

  namespace :check do
    desc "Check that we can access everything"
    task :write_permissions do
      on roles(:all) do |host|
        if test("[ -w #{fetch(:deploy_to)} ]")
          info "#{fetch(:deploy_to)} is writable on #{host}"
        else
          error "#{fetch(:deploy_to)} is not writable on #{host}"
        end
      end
    end
  end

$> bundle exec cap -T #to check the task existence
$> bundle exec cap production check:write_permissions #to verify the write permission


[Still working on Cap Scripting]

Basic Commands

cap production deploy:check
cap production deploy 
cap production deploy:rollback



Advance Comments [from capistrano Git page]


# list all available tasks
$ bundle exec cap -T

# deploy to the staging environment
$ bundle exec cap staging deploy

# deploy to the production environment
$ bundle exec cap production deploy

# simulate deploying to the production environment
# does not actually do anything
$ bundle exec cap production deploy --dry-run

# list task dependencies
$ bundle exec cap production deploy --prereqs

# trace through task invocations

$ bundle exec cap production deploy --trace


Advance Learning

https://github.com/capistrano/sshkit


Deploy issue with git

When you get: git stdout: permission denied (publickey).

$> eval $(ssh-agent)
$> ssh-add



Rails Life

Ruby Self Help Steps

Installation required Ruby setups!

http://code.tutsplus.com/tutorials/how-to-install-ruby-on-a-mac--net-21664
https://gorails.com/setup/osx/10.10-yosemite
http://railsapps.github.io/installrubyonrails-mac.html

Xcode installation if mac
RVM installation
Ruby installation
git installation
PostgreSQL or SQLite3


RVM Ruby version Preparation

rvm current #shows current default
rvm list #lists local installation

rvm get stable #get latest stable version
rvm reload # reload rvm
rvm list remote #all available to install
rvm install 2.2.5
rvm reinstall 2.2.0 --disable-binary

rvm --default use 2.1.5 #to make 2.1.5 as default

gem setup
$ echo 'gem: --no-document' >> ~/.gemrc

To create gemset
$ rvm use 2.2.1@gemset-2.2.1 --create

Install rails before the next step
$ gem install rails

Good start for first project
Ref: https://github.com/RailsApps/rails-composer/

#sudo gem install rails
rails new myapp -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb



#Standard way
$rails new <project_name>

use .ruby-version  file to specify ruby version for the project
Example: 2.2.1@gemset_2_2_1

rspec
https://relishapp.com/rspec/rspec-rails/docs/gettingstarted

in Gemfile, development and test section
gem "rspec-rails"

bundle install
rails generate rspec:install

Remember: rake db:test:prepare

rake spec #to run tests


Cucumber
in Gemfile - development 

gem 'cucumber-rails', :require => false
gem 'database_cleaner'

  
bundle install
rails generate cucumber:install


Haml

add
gem "haml-rails", "~> 0.9" #Check version from https://github.com/indirect/haml-rails


rails generate haml:application_layout convert

rake haml:erb2haml # to convert existing erb files to haml



Devise
Add gem "devise" in Gemfile 
bundle install

rails generate devise:install
Follow suggestions


Registeration Email issue

Google account access blocking
SMTPAuthenticationError

http://stackoverflow.com/questions/18124878/netsmtpauthenticationerror-when-sending-email-from-rails-app-on-staging-envir

Add gem 'sass-rails' in Gemfile





Pry
http://pryrepl.org/


pry -r ./config/environment.rb