Month: November 2017

How to login to Windows and Run command from Linux

How to login to Windows and Run command from Linux

Introduction –
In many cloud application you need to login to Windows from Linux server and run Windows native command or Powershell command to perform certain task.
There are two options to do this.

1) Winexe (outdated)-
NOTE – You can use it if it works for you!
Winexe remotely executes commands on Windows NT/2000/XP/2003 systems from GNU/Linux

    eg - winexe --user='<USERNAME>' //<HOSTNAME or IPADDRESS> "ipconfig /all"

2) Ruby or Python and WinRM –

* What is Windows Remote Management (WinRM)?
Windows Remote Management (WinRM) is the Microsoft implementation of WS-Management Protocol, a standard Simple Object Access Protocol (SOAP)-based, firewall-friendly protocol that    allows hardware and operating systems, from different vendors, to interoperate. Refere https://msdn.microsoft.com/en-us/library/aa384426.aspx for more information.

* What is PowerShell Remoting Protocol?
PowerShell Remoting allows me to run commands on a remote system as if I was sitting in front of it. It provides a consistent framework for managing computers across a network.
Windows PowerShell Remoting Protocol, which encodes messages prior to sending them over the Web Services Management Protocol Extensions for the Windows.

NOTE- “Enable-PSRemoting” service should be running on Windows server. (Command: Enable-PSRemoting -Force)

* WinRM and the Python library pywinrm (https://github.com/diyan/pywinrm)
   * WinRM and the Ruby library winrm

In this blog, we will use Ruby winrm library and see how we can monitor Windows service. Please find installation steps.

# yum install ruby-devel
# gem install -r winrm

Scripts-

#!/usr/bin/env /usr/bin/ruby

require 'rubygems'
require 'fileutils'
require 'highline/import'
require 'optparse'
require 'winrm'

############
options = {}
args = OptionParser.new do |opts|
  opts.on('-h', '--help', 'Show help') do
     puts opts
     exit
  end

  opts.on('-', /\A-\Z/) do
    puts opts
    exit(1)
  end

  opts.on('-H', '--hostname HOSTNAME', 'Hostname') do |hostname|
    options[:hostname] = hostname
  end

  opts.on('-u', '--username USERNAME', 'Username') do |username|
    options[:username] = username
  end

  opts.on('-s', '--service SERVICE', 'Window Service') do |winsrv|
    options[:winsrv] = winsrv
  end

  opts.on('-f', '--passfile FILE', 'File with Password') do |v|
    options[:passfile] = v
  end
end
args.parse!
args.banner = "\nUsage: #{$PROGRAM_NAME} <options>\n\n"
#puts options

if !options[:hostname].nil? && !options[:username].nil? && !options[:winsrv].nil?
   my_service = options[:winsrv].to_s
   my_user = options[:username].to_s
   my_pass = nil
   if File.exist?(options[:passfile].to_s)
     windata = File.read(options[:passfile].to_s)
     my_pass = windata.chomp.strip
   else
     print 'Enter Password: '
     pass = ask('Password: ') { |q| q.echo = '*' }
     my_pass = pass.chomp
   end

   ## windows code ##
   win_host = File.join('http://', options[:hostname], ':5985/wsman')
   opts = {
     endpoint: win_host.to_s, user: my_user.to_s, password: my_pass.to_s
   }
   conn = WinRM::Connection.new(opts)

   # powershell
   # ps_cmd = "Get-WMIObject Win32_Service -filter \"name = '#{my_service}'\" "
   #shell = conn.shell(:powershell)
   #output = shell.run(ps_cmd)
   ##puts output.stdout.chomp
   #data = output.stdout.gsub(/\s+|\n+/, ' ')
   #data = data.gsub(/\s+:/, ':')
   #if ( data =~ /ExitCode\s+:\s+0/ ) || ( data =~ /ExitCode:\s+0/ )
   # puts "OK - #{data}"
   # exit 0
   #else
   # puts "CRITICAL - #{data}"
   # exit 2
   #end

  # normal shell
   my_cmd = "sc query #{my_service}"
   shell_cmd = conn.shell(:cmd)
   output1 = shell_cmd.run(my_cmd)
   data1 = output1.to_s.chomp
   data1 = output1.stdout.gsub(/\s+|\n+/, ' ')
   data1 = data1.gsub(/\s+:/, ':')
   #puts data1
   if ( data1 =~ /.*STATE\s+:.*RUNNING/ ) || ( data1 =~ /.*STATE:.*RUNNING/ )
     puts "OK - #{data1}"
     exit 0
   else
     puts "CRITICAL - #{data1}"
     exit 2
   end
else
 STDERR.puts args.banner
 STDERR.puts args.summarize
 exit(1)
end

#eof

* How to user Script

root@localhost# ./winservice-monitoring.rb -u ‘XXXXX’ -H <MYHOST> -f /tmp/password.txt  -s xagt
OK – SERVICE_NAME: xagt TYPE: 10 WIN32_OWN_PROCESS STATE: 4 RUNNING (STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN) WIN32_EXIT_CODE: 0 (0x0) SERVICE_EXIT_CODE: 0 (0x0) CHECKPOINT: 0x0 WAIT_HINT: 0x0
root@localhost #

root@localhost # ./winservice-monitoring.rb -u ‘XXXXX’ -H <MYHOST> -f /tmp/password.txt  -s xxx
CRITICAL – [SC] EnumQueryServicesStatus:OpenService FAILED 1060: The specified service does not exist as an installed service.
root@localhost #

Reference:
https://github.com/WinRb/WinRM
https://sourceforge.net/projects/winexe
http://blogs.msdn.com/PowerShell

Thank you,
Arun Bagul

Top 5 Infrastructure as Code (IaC) software

Top 5 Infrastructure as Code (IaC) software

Introduction

World is moving toward hybrid/multi-Cloud solutions and it is important for every Enterprise/Organizations to use different Cloud providers effectively!. Multi-Cloud strategy will help companies to save cost, make infrastructure highly available and businness continuity plan (disaster recovery) etc.

Infrastructure as Code (IaC) is a type of IT infrastructure that operations teams can automatically manage and provision through code, rather than using a manual process. Infrastructure as Code is sometimes referred to as programmable infrastructure. IaC is useful as it supports and make provisioning, deployment and maintenance of It infrastructure easy and simple in multi-Cloud scenario!

Why IaC?

* Manage infrastructure via source control, thus providing a detailed audit trail for changes.
* Apply testing to infrastructure in the form of unit testing, functional testing, and integration testing.
* Automate Your Deployment and Recovery Processes
* Rollback With the Same Tested Processes
* Don’t Repair, Redeploy
* Focus on Mean Time to Recovery
* Use Testing Tools to Verify Your Infrastructure and Hook Your Tests Into Your Monitoring System
* Documentation, since the code itself will document the state of the machine. This is particularly powerful because it means, for the first time, that infrastructure documentation is always up to date
* Enable collaboration around infrastructure configuration and provisioning, most notably between dev and ops.

Tops 5 Infrastructure as code (IaC) Software –

1) Terraform (https://www.terraform.io)
Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions. Terraform provides a flexible abstraction of resources and providers. Terraform is used to create, manage, and manipulate infrastructure resources. Providers generally are an IaaS (e.g. AWS, Google Cloud, Microsoft Azure, OpenStack), PaaS (e.g. Heroku), or SaaS services (e.g. Terraform Enterprise, DNSimple, CloudFlare).
NOTE – Vagrant is another tool from HashiCorp. Refer article for more information – https://www.vagrantup.com/intro/vs/terraform.html

2) Spinnaker (https://www.spinnaker.io)
Spinnaker is an open source, multi-cloud continuous delivery platform for releasing software changes with high velocity and confidence. Deploy across multiple cloud providers including AWS EC2, Kubernetes, Google Compute Engine, Google Kubernetes Engine, Google App Engine, Microsoft Azure, and Openstack.

3) AWS CloudFormation (https://aws.amazon.com/cloudformation)
AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion. You can use AWS CloudFormation’s sample templates or create your own templates to describe the AWS resources, and any associated dependencies or runtime parameters, required to run your application.

4) Google’s Cloud Deployment Manager (https://cloud.google.com/deployment-manager)
Google Cloud Deployment Manager allows you to specify all the resources needed for your application in a declarative format using yaml. You can also use Python or Jinja2 templates to parameterize the configuration and allow reuse of common deployment paradigms such as a load balanced, auto-scaled instance group. Treat your configuration as code and perform repeatable deployments.

5) Azure Automation and Azure Resource Manager(ARM)
Microsoft Azure Automation provides a way for users to automate the manual, long-running, error-prone, and frequently repeated tasks that are commonly performed in a cloud and enterprise environment. It saves time and increases the reliability of regular administrative tasks and even schedules them to be automatically performed at regular intervals. You can automate processes using runbooks or automate configuration management using Desired State Configuration. ARM Templates provides an easy way to create and manage one or more Azure resources consistently and repeatedly in an orderly and predictable manner in a resource group.

 

* Docker Compose (https://docs.docker.com/compose/overview)
NOTE- Docker Compose is mainly for Container technology and is different from above tools.

* Orchestrate containers with docker-compose
The powerful concept of microservices is gradually changing the industry. Large monolithic services are slowly giving way to swarms of small and autonomous microservices that work together. The process is accompanied by another market trend: containerization. Together, they help us build systems of unprecedented resilience. Containerization changes not only the architecture of services, but also the structure of environments used to create them. Now, when software is distributed in containers, developers have full freedom to decide what applications they need.

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. Compose preserves all volumes used by your services. Compose caches the configuration used to create a container. When you restart a service that has not changed, Compose re-uses the existing containers. Re-using containers means that you can make changes to your environment very quickly.

* IaC Tools and DevOps –

When we speak of the DevOps and continuous delivery/integration (CI/CD) toolchain, we’re referring to a superset of tools—many with overlapping capabilities—for helping organizations achieve faster and safer deployment velocity. This encompasses a broad range of solutions: provisioning tools, orchestration tools, testing frameworks, configuration management (CM) and automation platforms, and more. Please refer DevOps – Comparison of different Configuration Management Software for Comparisons between CM. Here we’ll compare different orchestration and management tools for provisioning infrastructures: Terraform and Spinnaker/CloudFormation.

  • CloudFormation is specific to AWS cloud resources, while Terraform/Spinnaker supports all cloud vendors.
  • Terraform allows you to define and manage your infrastructure, but Spinnaker allows you to manage your infrastructure from the perspective of code releases and deployment workflows
  • Infrastructure Lifecycle Management is easy using visualizations such as Terraform graph give developers and operators any easy way to comprehend dependent ordering
  • Docker Compose mainly for containers technology like Docker (https://www.docker.com)
  • Azure Automation is for Azure Cloud using Power-shell scripting

Thank you,
Arun Bagul