2019/02/28

AWS ALB redirect HTTP to HTTPS configuration in command line

CURRENT CONFIGURATION: AWS Application Load Balancer created by Elastic Beanstalk
OBJECTIVE: redirect HTTP to HTTPS on port 80 by default by command line
ISSUE: lack of clear example.
SOLUTION:
aws elbv2 modify-listener --listener-arn <$ebs_alb_listener_http> --default-actions '[{"Type": "redirect", "RedirectConfig": {"Protocol": "HTTPS", "Port": "443", "Host": "#{host}", "Query": "#{query}", "Path": "/#{path}", "StatusCode": "HTTP_301"}}]' --region <$my_aws_region>

LINKS: Elastic Load Balancing Announces Support for Redirects and Fixed Responses for Application Load Balancer
AWS cli elbv2 modify-listener

2018/10/25

Setup EKS Kubernetes with 2 Autoscaling groups in private and public subnets

CURRENT CONFIGURATION: AWS, EKS Kubernetes 1.10.3.
OBJECTIVE: Setup EKS Kubernetes with 2 Autoscaling groups in private and public subnets. One nodes group stack should have 3-10 nodes in private subnets. Second nodes group stack should have 2-4 nodes in public subnets.
ISSUE: AWS IAM Authenticator configuration map unregister from EKS cluster different nodes group.
SOLUTION:
Create AWS IAM Authenticator configuration map with both nodes groups:
  cat > ./aws-auth-cm-all.yaml <
apiVersion: v1
kind: ConfigMap
metadata:
  name: aws-auth
  namespace: kube-system
data:
  mapRoles: |
    - rolearn: ${EKS_INSTANCE_ROLE_PUBLIC}
      username: system:node:{{EC2PrivateDNSName}}
      groups:
        - system:bootstrappers
        - system:nodes
    - rolearn: ${EKS_INSTANCE_ROLE_PRIVATE}
      username: system:node:{{EC2PrivateDNSName}}
      groups:
        - system:bootstrappers
        - system:nodes
EOF
  cat ./aws-auth-cm-all.yaml
  kubectl apply -f ./aws-auth-cm-all.yaml
LINKS:
https://docs.aws.amazon.com/eks/latest/userguide/launch-workers.html
P.S. I have to change Blog to different, code friendly.

2018/07/30

Jenkins pipeline example short

ОКРУЖЕНИЕ: Jenkins 2.121.2 on Ubuntu 16.04.4 LTS
ЦЕЛЬ: Сконфигурировать Jenkins pipeline.
РЕШЕНИЕ:
Jenkinsfile-pipeline-example-short.groovy
// Jenkins pipeline example short. Jenkins 2.121.2 on Ubuntu 16.04.4 LTS
// Jenkinsfile-pipeline-example-short.groovy
pipeline {
   agent any

   environment {
      MY_DOCKER_DIR = 'docker-images'
      MY_DOCKER_EXPORT_DIR = '/tmp'
      MY_DOCKER_IMPORT_DIR = '/mnt/data/jenkins/jenkins-agent'
      MY_DEST_SERVER = 'server-01'
   }

   stages {

      stage('Clone repository on master') {
         agent { label 'master' }
         steps {
            echo 'Clone repository on master'
            REPLACE_ME
         }
      }

      stage('Stop QA env') {
         agent { label 'master' }
         steps {
            timeout(50) {
               echo 'Shutdown docker containers'
               REPLACE_ME
            }
         }
      }

      stage('Clone repository on agent') {
         agent { label 'MY_qa_deploy' }
         steps {
            echo 'Clone repository on agent'
            REPLACE_ME
         }
      }

      stage('Run docker images and test') {
         agent { label 'master' }
         steps {
            echo 'Run docker images and test'
            timeout(30) {
            REPLACE_ME
            }
            script {
               REPLACE_ME
            }
         }
      }

      stage('Build docker images') {
         agent { label 'master' }
         steps {
            echo 'Build docker images'
            REPLACE_ME
         }
      }

      stage('Export docker images') {
         agent { label 'master' }
         steps {
            timeout(20) {
            echo 'Export docker images'
            REPLACE_ME
            }
         }
      }

      stage('Copy to destination server') {
         agent { label 'master' }
         steps {
            sh 'echo "Copy to destination server env.MY_DEST_SERVER: \${MY_DEST_SERVER}"'
            REPLACE_ME
         }
      }

      stage('Import on destination server') {
         agent { label 'MY_qa_deploy' }
         steps {
            timeout(20) {
               sh 'echo "env.MY_DOCKER_IMPORT_DIR: \${MY_DOCKER_IMPORT_DIR}; env.MY_DOCKER_DIR: \${MY_DOCKER_DIR};"'
               REPLACE_ME
            }
         }
      }

      stage('Start on destination server') {
         agent { label 'MY_qa_deploy' }
         steps {
            timeout(25) {
               echo 'Start on destination server'
               REPLACE_ME
            }
         }
      }
      
      stage('Test QA from build') {
         steps {
            script {
               REPLACE_ME
            }
         }
      }
   }

   post {
      always {
         echo 'INFO: Post: always'
         script {
            mail to: 'my-build-notification-always@example.com', subject: 'jenkins bot', body: 'test always', mimeType: "text/html"
         }
      }
      success {
         echo 'INFO: Post: success'
         script {
            mail to: 'my-build-notification-success@example.com', subject: 'Build success', body: 'Build success', mimeType: "text/html"
         }
      }
      failure {
         echo 'INFO: Post: failure, failed'
         script {
            mail to: 'my-build-notification-failure@example.com', subject: 'Build failed', body: 'Build failed', mimeType: "text/html"
         }
      }
   }
}

2015/10/30

Unifi Access Point freezes as provisioning in Unifi on Ubuntu 14.04

ОКРУЖЕНИЕ: UniFi AP-AC v2, Unifi 4.7.5, Ubuntu 14.04.3 LTS на Amazon AWS t2.micro, Site-to-Site VPN соединение.
ЦЕЛЬ: Конифигурация Ubiquiti Wi-Fi Access Point UniFi AP-AC в офисе через Uniti в облаке.
ПРОБЛЕМА: 
Ubiquiti Wi-Fi Access Point зависает в статусе provisioning (provisioning looping) .
РЕШЕНИЕ:
Обновить Java.
apt-get purge -y openjdk-6-*
apt-get install -y openjdk-7-jdk
update-alternatives --config java
reboot

2015/10/14

perl: warning: Please check that your locale settings

ОКРУЖЕНИЕ: Ubuntu 14.04.3 LTS
ЦЕЛЬ: Запускать команды без неисправленных предупреждений.
ПРОБЛЕМА: 
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
        LANGUAGE = (unset),
        LC_ALL = (unset),
        LC_PAPER = "en_IE.UTF-8",
        LC_ADDRESS = "en_IE.UTF-8",
        LC_MONETARY = "en_IE.UTF-8",
        LC_NUMERIC = "en_IE.UTF-8",
        LC_TELEPHONE = "en_IE.UTF-8",
        LC_IDENTIFICATION = "en_IE.UTF-8",
        LC_MEASUREMENT = "en_IE.UTF-8",
        LC_TIME = "en_IE.UTF-8",
        LC_NAME = "en_IE.UTF-8",
        LANG = "en_US.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
РЕШЕНИЕ:
apt-get install language-pack-en

Запустить команду.

2015/02/04

VirtualBox USB Issue with Windows 7 Guest

ОКРУЖЕНИЕ: Ubuntu 14.04.1 LTS; KDE 4.13.3; Oracle VN VirtualBox 4.3.20 + Extension Pack
ЦЕЛЬ: Использовать USB устройства на виртуальной Windows 7 внутри VirtualBox.
ПРОБЛЕМА: Пустой лист USB устройств в VirtualBox.
РЕШЕНИЕ:
Добавить действующего пользователя в группу vboxusers
sudo usermod -a -G vboxusers MyUserName
Перестартовать Ubuntu.

2014/12/03

Postgresql init file for RHEL cluster with multi services on one node

ОКРУЖЕНИЕ: Redhat 6.4; Postgresql 9.2, 9.3
ЦЕЛЬ: Запускать несколько Postgresql ДБ сервисов на одной ноде Redhat кластера И/ИЛИ  Запускать Postgresql датабаза сервис на каждой ноде Redhat кластера 
ПРОБЛЕМА: Наличие только одного Postgresql init файла. Несовместимая конфигурация по умолчанию Postgresql.
РЕШЕНИЕ:
Создать индивидульную директорию для каждого Postgresql сервиса.
/var/lib/pgsql/9.2/ --> /var/lib/pgsql/mydb01/9.2/ и  /var/lib/pgsql/mydb02/9.2/
Создать индивидульный init скрипт для каждого Postgresql сервиса.
/etc/init.d/postgresql  -->  /etc/init.d/postgresql-mydb01 и /etc/init.d/postgresql-mydb02
init скрипт можно скачать отсюда. По примеру заменяем MM_CHANGE_TO_CURRENT_DB_DIR на mydb01
ССЫЛКИ: Postgresql init file

2014/12/02

ansible - SSH encountered an unknown error during the connection

ОКРУЖЕНИЕ: Fedora 20, ansible 1.7.2-1.fc20
ЦЕЛЬ: использовать ansible через ssh соединение
ПРОБЛЕМА: ansible myenvironment -m ping выдаёт ошибки:
eudub-myserver1 | FAILED => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue
Команда ssh eudub-myserver1 выполняется без проблем
ansible myenvironment -m ping -vvvv выдаёт ошибки:
debug1: Control socket "/home/myuser/.ssh/tmp/eudub-myserver1_22_myuser" does not existdebug3: muxserver_listen: temporary control path /home/myuser/.ssh/tmp/eudub-myserver1_22_myuser.zMuh7FrM1b2EsXTqmuxserver_listen bind(): No such file or directoryeudubs-prdsrv-who02 | FAILED => SSH encountered an unknown error. The output was:OpenSSH_6.4, OpenSSL 1.0.1e-fips 11 Feb 2013
~/.ssh/config содержит
#ControlMaster auto
ControlPath /home/myuser/.ssh/tmp/%h_%p_%r
РЕШЕНИЕ: 
mkdir -p ~/.ssh/tmp/

2013/11/15

Ruby installation issue - Protected multilib versions

CURRENT CONFIGURATION:
RHEL 6.4 x64 on Amazon AWS VPC

OBJECTIVE:
Install Ruby 2.0.0

ISSUE:
Error running 'requirements_centos_libs_install gcc-c++ readline-devel zlib-devel libyaml-devel libffi-devel openssl-devel autoconf automake libtool bison',
please read /usr/local/rvm/log/1384535887_ruby-2.0.0-p247/package_install_gcc-c++_readline-devel_zlib-devel_libyaml-devel_libffi-devel_openssl-devel_autoconf_automake_libtool_bison.log
Requirements installation failed with status: 1.
Log file:
Error: Multilib version problems found. This often means that the root
cause is something else and multilib version checking is just
pointing out that there is a problem. Eg.:
1. You have an upgrade for libyaml which is missing some
dependency that another package requires. Yum is trying to
solve this by installing an older version of libyaml of the
different architecture. If you exclude the bad architecture
yum will tell you what the root cause is (which package
requires what). You can try redoing the upgrade with
--exclude libyaml.otherarch ... this should give you an error
message showing the root cause of the problem.
2. You have multiple architectures of libyaml installed, but
yum can only see an upgrade for one of those arcitectures.
If you don't want/need both architectures anymore then you
can remove the one with the missing update and everything
will work.
3. You have duplicate versions of libyaml installed already.
You can use "yum check" to get yum show these errors.
...you can also use --setopt=protected_multilib=false to remove
this checking, however this is almost never the correct thing to
do as something else is very likely to go wrong (often causing
much more problems).
Protected multilib versions: libyaml-0.1.3-1.el6.i686 != libyaml-0.1.3-1.1.el6.x86_64
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest

SOLUTION:
Try installation command first time.
curl -L https://get.rvm.io | bash -s stable --ruby=2.0.0
Receive the error message.
Continue installation with commands:
yum downgrade -y libyaml
yum install -y --setopt=protected_multilib=false libyaml-devel
curl -L https://get.rvm.io | bash -s stable --ruby=2.0.0

LINKS:
Ruby Version Manager (RVM)

2013/07/07

Копирование Fedora, CentOS, RedHat на VMware

ОКРУЖЕНИЕ: VMware ESXi 5.1, CentOS 6, RedHat 6, Fedora 19
ЦЕЛЬ: Подготовить виртуальную машину для копирования или клонирования с VMware ESXi на VMware ESXi .
ПРОБЛЕМА: Не работает сеть после копирования или клонирования
РЕШЕНИЕ:
# Выполняется от пользователя root
# Скопировать конфигурционные файлы в домашнюю директорию
yes | cp -f /etc/udev/rules.d/70-persistent-net.rules ~/.
yes | cp -f /etc/sysconfig/network-scripts/ifcfg-eth0 ~/.
# Изменить конфигурционные файлы
sed -i 's/^SUBSYSTEM/#SUBSYSTEM/g' /etc/udev/rules.d/70-persistent-net.rules
sed -i 's/^UUID/#UUID/g' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i 's/^MACADDR/#MACADDR/g' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i 's/^HWADDR/#HWADDR/g' /etc/sysconfig/network-scripts/ifcfg-eth0
# Почистить перед копированием
rm -rf $(find /tmp -type f)
rm -rf $(find /var/log -type f)
rm -rf $(find /home -type f -name ".bash_history")
rm -fr ~/.bash_history
# Выключить виртуальную машину
poweroff
Скоприровать или экспортировать виртуальную машину.
Восстановить конфигурционные файлы на мастере (если нужно):
yes | cp -f ~/70-persistent-net.rules /etc/udev/rules.d/
yes | cp -f ~/ifcfg-eth0 /etc/sysconfig/network-scripts/
СКАЧАТЬ:

2012/08/09

Check on Nagios the latest files in folder with NSClient++ 0.3.9

CURRENT CONFIGURATION: Linux OpenSuSe, Nagios 3.2.3, NRPE; Windows 2003R2 x64 server, NSClient++ 0.3.9.330 2011-09-02
OBJECTIVE: Monitor MSSQL backup, IIS logs replication with Nagios. Check FOLDER with files (MSSQL backup, IIS logs, S3 logs, etc.). Send WARNING if files are older than some hours.
SOLUTION:
NRPE has to work on Nagios server and on Windows client computer with NSClient++.
Nagios server command.cfg file:
define command{
  command_name    check_nrpe_files_written
  command_line    $USER1$/check_nrpe -H $HOSTADDRESS$ -c CheckFiles -a "path=$ARG1$" "pattern=$ARG2$" "filter=written gt -$ARG3$" truncate=4096 "master-syntax=files: %total%" max-dir-depth=$ARG4$ MinWarn=0
}

define command{
  command_name    check_nrpe_files_creation
  command_line    $USER1$/check_nrpe -H $HOSTADDRESS$ -c CheckFiles -a "path=$ARG1$" "pattern=$ARG2$" "filter=creation gt -$ARG3$" truncate=4096 "master-syntax=files: %total%" max-dir-depth=$ARG4$ MinWarn=0
}

Nagios server somename.cfg file examples:


define service{
...
  check_command           check_nrpe_files_creation!F:\\Backup\\SERVER01\\mssql\\backup\\default\\full!*.bkz!30h!0
  normal_check_interval   720
}
define service{
...
  check_command           check_nrpe_files_creation!F:\\Backup\\SERVER06\\ServiceDesk\\backup!*.data!30h!0
  normal_check_interval   720
}
define service{
...
  check_command           check_nrpe_files_creation!F:\\backup\\SERVER01!*-exchange_1_storage_group.bkf!8d!0
  normal_check_interval   1440
}
define service{
...
  check_command           check_nrpe_files_written!D:\\Logs\\IISLogs!*WEB01*.log!6h!4
  normal_check_interval   180
}
define service{
...
  check_command           check_nrpe_files_written!D:\\Replica\\UploadCopy\\s3!LastReplication.log!30h!0
  normal_check_interval   720
}

NSClient++ NSC.ini file:

[modules]
NRPEListener.dll
[NRPE]
allow_arguments=1
allow_nasty_meta_chars=1
Big thanks to NSClient++ author for program and excellent support.

2012/06/11

Amazon AWS windows instance w32time service issue

CURRENT CONFIGURATION:  Windows 2008R2 SP1 instance on Amazon AWS VPC
OBJECTIVE: Time synchronise
ISSUE:
C:\>sc start w32time
[SC] StartService FAILED 1290:
The service start failed since one or more services in the same process have anincompatible service SID type setting. A service with restricted service SID type can only coexist in the same process with other services with a restricted SID type. If the service SID type for this service was just configured, the hosting process must be restarted in order to start this service.
C:\>sc start Ec2Config
[SC] StartService FAILED 1068:
The dependency service or group failed to start.
SOLUTION:
Uninstall Ec2ConfigService. Delete all in c:\Program Files\Amazon\Ec2ConfigService\ except  config files in c:\Program Files\Amazon\Ec2ConfigService\Settings\ .
Uninstall w32time by command
w32tm /unregister
Reboot server.
Install and start w32time service by command
w32tm /register
@ping localhost -n 5 >; nul
sc start w32time
Configure w32time service. Example:
w32tm /config /update /manualpeerlist:0.ie.pool.ntp.org,0.europe.pool.ntp.org,3.europe.pool.ntp.org /syncfromflags:MANUAL
@ping localhost -n 2 >; nul
w32tm /monitor /computers:0.ie.pool.ntp.org
w32tm /resync
Reboot the server ant test w32time service. Example
w32tm /monitor /computers:0.ie.pool.ntp.org
w32tm /resync
w32tm /query /peers
w32tm /query /configuration
If w32time service works as you expected download and install Ec2ConfigService
Reboot the server.
LINKS: Reinstall ec2config

2011/10/21

Cannot open default admin shares on Windows 2008R2

CURRENT CONFIGURATION: Windows 2008 R2 SP1 (In workgroup), Windows 7

ISSUE: Cannot open default admin shares on Windows 2008R2 (C$, etc.) with account credentials in local Administrators group but the account is not Administrator. I could connect to non standard shares with the same credentials

C:\>net use \\MyServerName\c$ /user:MyServerName\MyAdminUser MyPassword

System error 5 has occurred.

Access is denied.

SOLUTION:

Please open regedit, navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

Create new DWORD (32-bit) Value "LocalAccountTokenFilterPolicy"

Change in data 0 to 1

Please open Start –> Administrative Tools –> Server Manager –> Roles –> File Services –> Share and Storage Management

Right click on C$ –> Stop sharing

Open Command Promt as administrator

C:\>sc stop LanmanServer

C:\>sc start LanmanServer

DOWNLOAD: Download md5: 8062a4edaf664c0f742500c61293153c HKLM_W2008R2_Access_to_admin_shares_fix.zip

LINKS: kb947232

 

2011/05/24

WSUS issue: directory permissions and shares disappeared

CURRENT CONFIGURATION: Windows 2003 R2 x64 SP2, WSUS 3.0 SP1 and remote MS SQL 2005 server
OBJECTIVE: Fix issue with WSUS directory permissions and shares.
ISSUE: WSUS folder content was restored to the same location D:\WSUS but with folder and share permissions issue. WSUS shares were disappeared after server restart. 
Server Event ID: 10012 The permissions on directory D:\ are incorrect. 
Clients logs:
80070005    AutomaticUpdates    Failure    Content Download    Error: Download failed.
SOLUTION: 
Use \Program Files\Update Services\Tools\wsusutil.exe
Create new empty folder WSUS2
Run next commands.
"C:\Program Files\Update Services\Tools\wsusutil.exe" movecontent D:\WSUS2 d:\move.log -skipcopy
"C:\Program Files\Update Services\Tools\wsusutil.exe" movecontent D:\WSUS d:\move2.log -skipcopy
It would takes a while.
move2.log:
Successfully stopped WsusService.
Beginning content file location change to D:\WSUS
Did not copy files due to -skipcopy flag.
Successfully changed WUS configuration.
Successfully changed IIS virtual directory path.
Successfully removed existing local content network shares.
Successfully created local content network shares.
Successfully changed registry value for content store directory.
Successfully changed content file location.
Successfully started WsusService.
Content integrity check and repair...
Initiated content integrity check and repair.
Check WSUS status
"C:\Program Files\Update Services\Tools\wsusutil.exe" checkhealth
Done. Please check event log for events with source "Windows Server Update Services".

2011/04/04

Shutdown all guests on Vmware virtual host

CURRENT CONFIGURATION: VMware 4.1.0 Build 260247
OBJECTIVE: Shutdown all guests on Vmware virtual host from APC Power Shute client.
SOLUTION: 
Please enable SSH on VMware host. vSphere Client -> Configuration -> Security Profile -> Properties -> SSH -> Start automatically.
Please download putty and run next command on Windows workstation or server.
@START c:\MyFolder\putty\plink.exe -ssh -pw MyPassword root@10.1.1.1 "/sbin/shutdown.sh -r now; /sbin/poweroff"

2011/01/10

Copy virtual machine on VmWare - network card issue

CURRENT CONFIGURATION: VMware ESXi 4, Ubuntu server 10.04
OBJECTIVE: Copy virtual machine on VMware
ISSUE: Network Card does not work after Linux virtual machine copy on VMware ESXi
 # /etc/init.d/networking restart
 * Reconfiguring network interfaces...
SIOCSIFADDR: No such device
eth0: ERROR while getting interface flags: No such device
SIOCSIFNETMASK: No such device
eth0: ERROR while getting interface flags: No such device
Failed to bring up eth0.
stop: Unknown instance:
# ifconfig -a
eth0_rename Link encap:Ethernet  HWaddr 00:00:xx:00:xx:00
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
All NIC are installed. Check command is
# lshw -C network
SOLUTION: 
to comment all lines in /etc/udev/rules.d/70-persistent-net.rules
# vi /etc/udev/rules.d/70-persistent-net.rules
Example:
# PCI device 0x8086:0x100f (e1000)
# SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:00:00:00:xx:01", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
# PCI device 0x8086:0x100f (e1000)
# SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:00:xx:00:00:02", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
Please reboot the Ubuntu server on VMware ESXi.

For Ubuntu server clone (image) creation (moving preparation) use next command on master clone (Source server) before final poweroff (shutdown).
sed -i 's/SUBSYSTEM/#SUBSYSTEM/g' /etc/udev/rules.d/70-persistent-net.rules

upgrade to VMvare ESXi 4.1 Perl VIRuntime.pm issue

CURRENT CONFIGURATION: VMware ESXi 4.0
OBJECTIVE: upgrade to VMvare ESXi 4.1
ISSUE:
1. VMware vSphere Host Update Utility 4.0 can not update ESXi 4.0 to 4.1
2. Command(1) C:\Program Files\VMware\VMware vSphere CLI> vihostupdate.pl --server myESXserver_name_orIP -i -b k:\Downloads\VMWare\VMWare_ESXi\ESXi4.1\upgrade-from-ESXi4.0-to-4.1.0-0.0.260247-release.zip -B ESXi410-GA
returns next error message
Can't locate VMware/VIRuntime.pm in @INC (@INC contains: C:/My_different_perl_version_installation/Perl/site/lib C
:My_different_perl_version_installation/Perl/lib .) at C:\Program Files\VMware\VMware vSphere CLI\bin\vihostupdat
e.pl line 13.
BEGIN failed--compilation aborted at C:\Program Files\VMware\VMware vSphere CLI\
bin\vihostupdate.pl line 13.
 3. When you had renamed previously installed Perl Folder command(1) would return next window
4. When you added Perl with full patch to command(1) command(2) would return next error message:
Can't open perl script "vihostupdate.pl": No such file or directory
SOLUTION:
1. Download  and install VMware vSphere
2. If you have previously installed Perl please rename Perl installation directory temporary. Example: From  C:/My_different_perl_version_installation/ to C:/__My_different_perl_version_installation/
3. Add Perl with full patch to command(1). Would be command(2)  
C:\Program Files\VMware\VMware vSphere CLI> "c:\Program Files\VMware\VMware vSphere CLI\Perl\bin\perl.exe" vihostupdate.pl --server myESXserver_name_orIP -i -b k:\Downloads\VMWare\VMWare_ESXi\ESXi4.1\upgrade-from-ESXi4.0-to-4.1.0-0.0.260247-release.zip -B ESXi410-GA
4. Use full path for Perl and vihostupdate.pl. Would be command(3)
C:\Program Files\VMware\VMware vSphere CLI> "c:\Program Files\VMware\VMware vSphere CLI\Perl\bin\perl.exe" "c:\Program Files\VMware\VMware vSphere CLI\bin\vihostupdate.pl" --server myESXserver_name_orIP -i -b k:\Downloads\VMWare\VMWare_ESXi\ESXi4.1\upgrade-from-ESXi4.0-to-4.1.0-0.0.260247-release.zip -B ESXi410-GA
SOLUTION BOTTOM LINE:
If you have previously installed Perl please rename Perl installation directory temporary.
Use full path for Perl and vihostupdate.pl. Would be command
C:\Program Files\VMware\VMware vSphere CLI> "c:\Program Files\VMware\VMware vSphere CLI\Perl\bin\perl.exe" "c:\Program Files\VMware\VMware vSphere CLI\bin\vihostupdate.pl" --server myESXserver_name_orIP -i -b k:\Downloads\VMWare\VMWare_ESXi\ESXi4.1\upgrade-from-ESXi4.0-to-4.1.0-0.0.260247-release.zip -B ESXi410-GA

To VMware: Thanks for nice exercise.

2010/11/16

Nagios: Restart a Windows Failed Services (cmd)

CURRENT CONFIGURATION: Linux OpenSuSe, Nagios 3.0.2, NRPE; Windows 2003 x64 server, NSClient++ 0.3.8.76

OBJECTIVE: Building a Self-Healing Network

ISSUE: Need some script to Restart failed Windows Services by Nagios Client

SOLUTION:
I created and tested win_service_restart.cmd batch file on Microsoft Windows 2003 servers.

--- Start of code ---

@echo off
:: *****************************************************************************
:: File:    win_service_restart.cmd
:: Author:  Vadims Zenins http://vadimszenins.blogspot.com
:: Version: 1.07
:: Date:    16/11/2010 12:28:45
:: Windows Failed Service restart batch file for Nagios Event Handler
::
::  Copy win_service_restart.cmd to \NSClient++\scripts\ folder.
::
:: Nagios commands.cfg:
:: define command{
::        command_name    win_service_restart
::        command_line    $USER1$/check_nrpe -H $HOSTADDRESS$ -p 5666 -c win_service_restart -a "$SERVICEDESC$" $SERVICESTATE$ $SERVICESTATETYPE$ $SERVICEATTEMPT$
::        }
::
:: Nagios template-services_common-win.cfg
:: define service{
::         name                    generic-service-win-wuauserv
::         service_description     wuauserv
::         display_name            Automatic Updates
::         event_handler           win_service_restart
::         event_handler_enabled   1
::         check_command           check_nt!SERVICESTATE!-d SHOWALL -l $SERVICEDESC$
::         }
::
:: NSCLIENT++ version 0.3.8 NSC.ini:
::   [Settings]
::   allowed_hosts=192.168.1.1/32  ; your Nagios server IP
::   [NRPE]
::   allow_arguments=1
::   allow_nasty_meta_chars=1
::   [Script Wrappings]
::   cmd=scripts\%SCRIPT% %ARGS%
::   [External Script]
::   allow_arguments=1
::   allow_nasty_meta_chars=1
::   [External Scripts]
::   command[win_service_restart]=scripts\win_service_restart.cmd "$ARG1$" $ARG2$ $ARG3$ $ARG4$
::
::
:: Additional examples on http://vadimszenins.blogspot.com/2008/12/nagios-restart-windows-failed-services.html
::
:: Tested platform:
:: Windows 2003 R2 x64 SP2, Nagios 3.2.0, NSClient++ 0.3.8.76
::
:: Version 1.07 revision:
:: Description is changed for NSCLIENT++ version 0.3.8 NSC.ini
:: Version 1.06 revision:
:: Description is changed for NSCLIENT++ version 0.3.8 NSC.ini
:: Version 1.05 revision:
:: Logging changes, stop and start services commands nave changed. Logs examples added.
:: Version 1.04 revision:
:: Double restart of the servise is fixed
:: Version 1.03 revision:
:: Description is changed
:: Version 1.02 revision:
:: @NET changed to @SC
:: Version 1.01 revision:
:: Service name's with spase problem is fixed
::
:: This code is made available as is, without warranty of any kind. The entire
:: risk of the use or the results from the use of this code remains with the user.
:: *****************************************************************************

::echo 1: %1    2: %2    3: %3    4: %4

@SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
:: Grab a file name and extension only
SET SCRIPTNAME=%~nx0
:: Replace "
SET SCRIPTNAME=%SCRIPTNAME:"=%
SET LOGDIR=C:\tools\logs
SET SERVICENAME=%1
:: Replace "
SET SERVICENAME1=%SERVICENAME:"=%
SET LOGFILE=%1
SET LOGFILE=%LOGFILE:"=%
:: Replace space by _
SET LOGFILE=%LOGFILE: =_%
SET LOGFILE=%LOGDIR%\%LOGFILE%.log

if "%SERVICENAME1%"=="" SET LOGFILE=%LOGDIR%\NO_SERVICENAME.log
::@echo servicename:  %SERVICENAME%
::@echo logfile: %LOGFILE%
::@echo SERVICENAME1: %SERVICENAME1%

:: =============================================================================

if not exist %LOGDIR% md %LOGDIR%
echo. >>%LOGFILE%
echo =============================================================================  >>%LOGFILE%
echo %DATE% %TIME% %SCRIPTNAME% has started >>%LOGFILE%
echo =============================================================================  >>%LOGFILE%

@if "%SERVICENAME1%"=="" goto usage
@if "%SERVICENAME1%"=="/?" goto usage
@if "%SERVICENAME1%"=="-?" goto usage

@echo Variables 1: %1   2: %2   3: %3   4: %4 >>%LOGFILE%

@SC query %SERVICENAME% >>%LOGFILE%

@SC query %SERVICENAME% | FIND /I "RUNNING" >>%LOGFILE%
if .%ERRORLEVEL%.==.0. (
    SET RETURN=Service %SERVICENAME% is running
    goto END
)

:RESTART
@echo %DATE% %TIME% Restarting %SERVICENAME% services... >>%LOGFILE%
@SC stop %SERVICENAME% >>%LOGFILE% 2>&1
@sleep 2
SET RETURN=Service %SERVICENAME% start pending
@SC start %SERVICENAME% | FIND /I "FAILED"
if .%ERRORLEVEL%.==.0. (
    SET RETURN=Start Service %SERVICENAME% FAILED
    @SC start %SERVICENAME% >>%LOGFILE% 2>&1
    goto END
)
@sleep 5
@SC query %SERVICENAME% | FIND /I "RUNNING"
if .%ERRORLEVEL%.==.0. (
    SET RETURN=Service %SERVICENAME% has started
    @SC query %SERVICENAME% >>%LOGFILE%
    goto END
)
@goto end

:USAGE
@echo Usage: >>%LOGFILE%
@echo  win_service_restart "^" ^ ^ ^ >>%LOGFILE%
@echo  ^ is "Service name", do not mix with "Display name" >>%LOGFILE%
@echo  ^, ^ and ^ are optional >>%LOGFILE%
::exit 128

:END
echo %DATE% %TIME% %SCRIPTNAME% has finished with code >>%LOGFILE%
echo %RETURN% >>%LOGFILE%
@echo %SCRIPTNAME%: %RETURN%
exit 0

--- End of code ---

Additional examples:

template-services_common-win.cfg
define service{
name generic-service-win-backup-agent
service_description BackupExecAgentAccelerator
display_name Backup Exec Remote Agent
event_handler win_service_restart
event_handler_enabled 1
check_command check_nt!SERVICESTATE!-d SHOWALL -l $SERVICEDESC$
register 0
}

services_common-win.cfg
define service{
use generic-service-win-backup-agent,generic-service-office
hostgroup_name winsrv-office ; Assign group of servers
host_name !SERVER11,!SERVER12 ; use this to exclude some servers or delete this row
}

group_windows.cfg
define hostgroup{
hostgroup_name winsrv-office ; The name of the hostgroup
alias Office Servers
}

host-server01.cfg
define host{
use windows-server ; Inherit default values from a template
host_name server01 ; The name we're giving to this host
alias server 01 ; A longer name associated with the host
hostgroups winsrv-office ; Group of servers
address 192.168.1.1 ; IP address of the host
}


DOWNLOADS:
Download the script from exchange.nagios.org
Download the script latest version from mirror.
 
md5: dbf0663a9e6648886eb8015cee8c9ce0 *win_service_restart.zip

Download the script previous version 1.05 from mirror. md5: 8b90ba7654227f1bf07c694368843b9

Download the script previous version 1.04 from mirror. md5: fd00753533e5fb655d824c3bf1d36d4

2010/03/30

Exchange 2007 vs Google Mail Premier Edition

CURRENT CONFIGURATION: Company has Exchange 2007 and Blackberry Servers

OBJECTIVE: Compare technical possibilities with Google Email (gmail) Premier Edition for small and middle business, especial from email administration point of view.

Read a document.

SOLUTION: If you have Microsoft Exchange implemented, stay where you are. 
If I have either to upgrade Microsoft Exchange or implement email solution from scratch I will discuss with manager email confidentiality and requirements. If confidentiality does not have the highest mark and company does not have branch in China I will suggest go with Google Apps Premier Edition.

2010/03/09

MSSQL 2005 procedure a file move rename

CURRENT CONFIGURATION: MSSQL server 2005

OBJECTIVE: Move or rename a file from MSSQL

SOLUTION:
I wrote SQL procedure. You can change destination database to whatever you want.
USE master
GO

-- set required options
EXEC sp_configure 'show advanced options',1
RECONFIGURE
GO
EXEC sp_configure 'Ole Automation Procedures',1
RECONFIGURE
GO

USE [sysman]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dba_file_move_rename]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[dba_file_move_rename]
GO

CREATE PROCEDURE [dbo].[dba_file_move_rename]
    @OldFilePath    nvarchar(512),
    @NewFilePath    nvarchar(512),
    @send_email_proc  nvarchar(256),
    @log int = 2
AS
-- *****************************************************************************
-- Author:  Vadim Zenin http://vadimszenins.blogspot.com
-- Version:    1.00
-- Date:      10/12/2009 18:37:34
-- Procedure for file move or rename
--
-- Usage:
-- In batch file: sqlcmd -E -dsysman -Q"EXEC sysman..dba_file_move_rename 'C:\temp\oldfile.txt', 'C:\temp\newile.txt', 'send_email', 1" >>%LOGFILE%
--
-- Parametrs:
-- @OldFilePath example: 'C:\temp\oldfile.txt'
-- @NewFilePath example: 'C:\temp\newile.txt'
-- @send_email_proc example: 'send_email'
-- @log (0 - none, 1 - minimum, 2 - standard(default), 4 - debug) optinal
--
-- Tested platform:
-- MS SQL 2005
--
-- Version 1.00 revision:
--
--
-- This code is made available as is, without warranty of any kind. The entire
-- risk of the use or the results from the use of this code remains with the user.
-- *****************************************************************************

DECLARE
    @procname        nvarchar(256),
    @fso            int,
    @hr              int,
    @sqlcmd            nvarchar(600),
    @email_subj        nvarchar(255),
    @email_body        nvarchar(3000)

-- Get current stored procedure name
SELECT @procname = OBJECT_NAME(@@PROCID)
IF @log > 1
begin
    PRINT RTRIM(CAST(GETDATE() AS NVARCHAR(30))) + ' ' + @procname + ' procedure has started';
    PRINT N'The Database Engine instance ' + RTRIM(@@SERVERNAME) + N' is running SQL Server build '
    + RTRIM(CAST(SERVERPROPERTY(N'ProductVersion ') AS NVARCHAR(128)));
end
IF @log > 2
BEGIN
  PRINT 'Parametr 1: ' + @OldFilePath;
  PRINT 'Parametr 2: ' + @NewFilePath;
  PRINT 'Parametr 3: ' + @send_email_proc;
  PRINT 'Parametr 4: ' + RTRIM(@log);
END

-- Check requrements
If not exists (Select * from dbo.sysobjects where xtype='p' and name=@send_email_proc)
BEGIN
    SELECT @email_body = N'!? Stored procedure sysman..' + @send_email_proc + ' does not exist'
    IF @log >= 0
    PRINT @email_body
    RAISERROR (@email_body,16,1) with log
END

--------------------------------------------------------------------------------
-- Main procedure
--------------------------------------------------------------------------------

SET @hr = 0

-- Creating File System Object
EXEC @hr=sp_OACreate 'Scripting.FileSystemObject',@fso OUT
IF @hr <> 0
BEGIN
    EXEC sp_OAGetErrorInfo @fso
    SELECT    @email_subj = N' Error creating File System Object.'+ @procname
  SELECT    @email_body = 'Error creating File System Object. Procedure name: ' + @procname
  IF @log >= 0
  BEGIN
      PRINT N' Sending failure email notification with subject: '
      PRINT @email_subj
    END
    SELECT @sqlcmd = '[sysman]..[' + @send_email_proc + ']'
    IF @log > 2
    PRINT    '- Command: ' + @sqlcmd;
  EXEC @sqlcmd @email_subject = @email_subj,@email_msg = @email_body
  RAISERROR (@email_body,16,1) with log
END

EXECUTE @hr=sp_OAMethod @fso, 'MoveFile', null, @OldFilePath, @NewFilePath
IF @hr <> 0
BEGIN
    EXEC sp_OAGetErrorInfo @fso
    SELECT    @email_subj = N' Error moving or renaming File.' + @procname
  SELECT    @email_body = ' Error moving or renaming File from ' + @OldFilePath +
      ' to ' + @NewFilePath + ' Procedure name: ' + @procname
  IF @log >= 0
  BEGIN
      Print N' Sending failure email notification with subject: '
      Print @email_subj
  END
    SELECT @sqlcmd = '[sysman]..[' + @send_email_proc + ']'
    IF @log > 2
    PRINT    '- Command: ' + @sqlcmd;
  EXEC @sqlcmd @email_subject = @email_subj,@email_msg = @email_body
  RAISERROR (@email_body,16,1) with log
END
else
begin
    IF @log > 0
      Print N'Moving or renaming File from ' + @OldFilePath + ' to ' + @NewFilePath + ' by procedure ' + @procname
end

-- Destroying File System Object
EXEC @hr=sp_OADestroy @fso
IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso

IF @log > 1
    PRINT RTRIM(CAST(GETDATE() AS NVARCHAR(30))) + ' ' + @procname + ' procedure has finished';
Download md5: 60853e73c93a656f7f373809ce3f997b