Monday, November 26, 2018

How to get network statistics on a VM nic from SSH.


If you need to get the network statistics via SSH on a VM nic, run the commands below.

  1. 'esxcli network vm list' to get VM ID.
  2. 'esxcli network vm port list -w <VM ID>' to get port ID number.
  3. 'esxcli network port stats get -p <port ID number>' to get network statistics.
Output:
Packet statistics for port 50332931
   Packets received: 293182742829
   Packets sent: 90336672427
   Bytes received: 305397539251
   Bytes sent: 11805570153
   Broadcast packets received: 135893129
   Broadcast packets sent: 813717
   Multicast packets received: 386654045
   Multicast packets sent: 334554
   Unicast packets received: 292660195655
   Unicast packets sent: 90335524156
   Receive packets dropped: 0
   Transmit packets dropped: 0


Thursday, November 15, 2018

Get Active Directory User's password expiration date.


Most corporation that uses Microsoft's Active Directory has set some password policies for tighter security.  One of them is probably 'Password Expiration' to force users to change their passwords every x amount of days.  I was in a situation where I needed to find a user account password expiration and the first thing that come to my mind is to use Powershell.  Upon Googling on how to do it with Powershell, I found that it is very cumbersome to do it.  You run a get-aduser command and it will output the accountexpires attribute but its not in datetime format.  You'd have to convert it, which didn't work for me.  Then I find that you can use the basic net user command like below.

c:\net user <username> /domain

That's all.


Friday, November 9, 2018

How to reinventory/register a vm from the CLI.


To re-inventory/register a vm from the CLI, do the following from an ssh prompt.

  • vim-cmd vmsvc/getallvms | grep -i <VM Name>  to get the VM ID.
  • vim-cmd vmsvc/reload <VM ID>

Tested on ESX 5.0.x - 5.5.x

Thursday, November 8, 2018

Run a program as admin from command line.


Ever run into a situation where you need to run a program as admin and Windows is not allowing you because you're in a screenshare with someone and UAC is prompting you but not let you type in your administrator credentials?  Give the following a try!

  1. Open a command prompt.
  2. Type in the following command.  
    • runas /user:Administrator cmd
    • type in your Administrator password
  3. Another command prompt will open up but this time, its run under the Adminstrator account.
  4. Navigate to the executable file you want to run, if its not in the environment path and type in the name and hit enter.
  • Note:  for some reason, you can't open the control panel by running control.exe from this.  If anyone knows why, please let me know.

Thursday, August 30, 2018

APC UPS and Powerchute


Today, while trying to set up a static IP for a production UPS, I mistakenly powered off the UPS taking down a network switch that's running off of.  Normally, to configure an IP on a device, I would normally use a console/serial (here's where the confusion lies for me) cable.  I saw a port marked "Serial" and thinking that was the console port when in fact its a port to configure the Powerchute, which is a power down management software from APC that is in most of their UPS devices.  The issue lies in that serial port.  If anything but a Powerchute serial cable that is plugged into that port marked "Serial" on the UPS, once a unrecognized signal is sent to that serial port, Powerchute will shutdown the entire UPS along with the devices that's plugged into it.  Bad.  Why?  I don't know.

Took me about 10 mins to figure out what had happened and went to power the UPS back on.  There is a port labeled "Console" on the back of the UPS but I didn't think too much of it since there was just a little hole next to it.  The little hole is actually for the real console cable in the form of a 2.5mm jack.  I've never seen a console cable like that until now.

What could APC have done?  Well maybe rename the "Serial" port as "Serial for Powerchute" and maybe have some warning if plugging in a non-Powerchute serial will result in UPS shutdown if any unrecognize signal is passed to it.

I digress.  



Thursday, July 12, 2018

How to clear your variables in Powershell.


After running a Powershell command with a variable, the contents in that variable will stay in memory unless its cleared or overwritten to.  The command below is how to clear it from memory.  This helps when you're writing and testing a script to make sure you get accurate results and not results from stale memory in variables.

Remove-Variable * -ErrorAction SilentlyContinue

Power on a batch of VM's using Powershell


If you have a list of vm's and you need it to be powered on, the script below will help you do that.  To give the storage system air to breathe and not cause a boot storm, it powers on a VM every 2 seconds and waits 5 minutes after ever 50 VM is powered on.

Import-Module vmware.vimautomation.core
Remove-Variable * -ErrorAction SilentlyContinue
$vcenter = "hostname of vCenter or ESX host"
connect-viserver $vcenter
$count = 0
$csvfile = import-csv "Path to csv file"
foreach($vm in $csvfile)
{
    $vm_info = Get-VM -Name $vm.VMName   #VMName refers to column header in the  csv file.
    if ($vm_info.PowerState -eq "PoweredOff")
    {
        Write-Host "Powering on "$vm_info.Name
        $poweron = Get-VM $vm_info.Name | Start-VM -Confirm:$false
        Sleep 2             #power on a vm every 2 seconds.
        $count++
        if($count -eq 50)   #powers on 50 vm's then waits for 5 minutes for  storage to breathe.
        {
            Sleep 300
            $count = 0
        }
    }
}

Tuesday, July 10, 2018

Find a file in linux


To find a file in linux called "myfile", use the command below.
    [root@testbox /]# find / -name "myfile"


Tuesday, July 3, 2018

Power on a batch of virtual machines in a csv file using PowerCLI.

Use the following PowerCLI script to power on a list of Virtual Machines from a CSV file.

import-module vmware.vimautomation.core

$vcenter = <my vCenter server>
connect-viserver $vcenter
$allvms = import-csv RVTools_tabvInfo.csv

foreach ($strNewVMName in $allvms)
{   
        #gets all the VM's properties.  We're interested in the PowerState  Property.
        $vmdata = Get-view -ViewType VirtualMachine -Filter @{"name" =  $strNewVMName.vm}  #vm is the column header name in the csv on the first line.
        #if the PowerState is not PoweredOn, then power it on.
        if ($vmdata.Runtime.PowerState -ne "PoweredOn")
        {
            Write-Host "Powering on "$strNewVMName.vm
            Start-VM -VM $strNewVMName.vm
            Sleep 2
        }
}

Monday, July 2, 2018

Speed test on Google GCP instance.

Spun up a GCP instance today and ran a speed test.   No speed issues there.


Wednesday, June 20, 2018

Change IP from Windows command line using netsh.



Use the following command to change the ip of a network interface in Windows.

netsh interface ipv4 set address name="Ethernet0" static <new ip address> <subnet mask> <gateway>

Saturday, June 9, 2018

Change IP address using Powershell.


  1. Get-NetIPAddress
    1. get the InterfaceIndex number for the nic you want to change the IP address on.
  2. Remove-NetIPAddress -InterfaceIndex X
  3. New-NetIPAddress -InterfaceIndex X -IPAddress x.x.x.x -PrefixLength 23 -DefaultGateway x.x.x.x
  4. Set-DnsClientServerAddress -InterfaceIndex X -ServerAddresses  x.x.x.x, x.x.x.x

Thursday, June 7, 2018

Get regkey value on a batch of computers remotely.


Here's a Powershell script I created to get value in the registry on a batch of computers remotely.  Very handy if you have many computers to check.  Will output 'Offline' if the computer is turned off.

$strMachineName = Get-Content computer_name.txt
foreach ($line in $strMachineName)
{
    try{
            $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $line)
            $regkey = $reg.OpenSubkey("<registry path>")
            $serialkey = $regkey.GetValue("LicenseInformation")
            if ($serialkey -eq ""){
                  write-host $line
           }
     }
    catch{
                write-host $line ----- "Offline"
    }
}

Monday, May 14, 2018

Game Cataloging


With any type of collecting hobby, you need some way to catalog your collection.  I use CLZ games to catalog my games.  It's available as an Android/IOS app, and you can access via the web as well by hitting    .  It is extremely useful and it's one of only 3 apps I've bought on my phone.  The software doesn't limit itself to only games.  Another version of the app does movies, music and books cataloging as well.  Your items automatically get's sync'd to the cloud so you do not need to worry about backing up when switching phones.  It will automatically sync back all your data upon a new installation of the software.  You can add games by scanning the bar code of the box and if its in the CLZ's database, then it will add it with all the information about the game for you.  You can try it out for free.  I think you can add up to 50 items on the free version.




Saturday, May 12, 2018

8 bit nostalgia itch.



Today, I started to dig out my Nintendo games again.  My favorite cart label design is Baseball.  I don't think there is a better artwork on a Nintendo game out there.  Gameplay for Baseball is little to be desired as this was one of the original releases and developers hadn't learn to use the complete capabilities of the NES at that point.  The graphics looks very pixelated even for 8 bit standard compared to games later in the NES' life.  Even so, I like to take this out and play it once in a while.  I am trying to collect all these black box games (I think there are around 30?) and its taken a while to find for a good price.  I've got half of them so far.  Below is what I'm missing.  Any one interested in trading, drop me a note.  


-Clu Clu Land
-Donkey Kong Arcade Classic Series
-Donkey Kong 3
-Donkey Kong Jr.
-Donkey Kong Jr. Math
-Gumshoe
-Ice Climber
-Pinball
-Slalom
-Soccer
-Popeye
-Stack-Up
-Urban Champion
-Volleyball
-Wrecking Crew

Thursday, May 10, 2018

Paso Robles stay over.


On our way back, we had a stay over half way between SD and our home in a city called Paso Robles, CA.  It's better known for its wineries.  We're not into wine so we made sure we had a good hotel since we're going to be staying in there most of the day to get a break from driving.  We stayed in a hotel called La Bellasera Hotel.  It's a 4 star hotel and probably one of the best hotels we've stayed at.  It's got a spa/jacuzzi inside the hotel room.  Check out this hotel if you're planning a stay in Paso Robles.  Next morning, we finished our drive home with a total of 1189 miles logged for the entire (LA/SD) trip.





Tuesday, May 8, 2018

Good bye San Diego.

In a day and a half, we went to LA Jolla, Old Town San Diego and Balboa Park along with a couple of boba tea stores.  We also went to some nice restaurants.  We will check out this morning of our hotel, which by the way was really nice, and head to LA for lunch.  Then it's on to Paso Robles.

  

Saturday, May 5, 2018

San Diego road trip!

Taking a short vacation, 5 days, and driving down to San Diego with a stop in Los Angeles. 
Not looking forward for the LA traffic however.




Wednesday, May 2, 2018

APC PDU Communication Status error.


Running APC's AP8641 model pdu's and we have several of them that is popping up with the following errors.  When this happens, it does not report any power loads.  I've tried to replace the LCD/Management module with a new one but the error exists.  I know that this issue is not model specific as I've had others models happen.   APC support recommended doing a factory reset (you will lose all settings) and upgrading the firmware to the latest, both of which I've tried.  Wondering if anyone has run into this issue before.



Change Network Failover Detection Policy on vSwitches and portgroups.



Need to change the NetworkFailoverDetectionPolicy for all your vSwithes and portgroups?  The following script traverses all clusters and host to check the NetworkFailoverDetectionPolicy for Beacon Probing.  If its Beacon Probing, change it to Link Status.

#import-module VMware.VimAutomation.Core
#Connect-VIServer -Server vcenter_hostname
#uncomment for testing
#$vmhosts = "hostname1","hostname2"
 
#uncomment for live run
#get the hostnames of all the hosts in every cluster
$vmhosts = get-cluster | get-vmhost | select name
foreach($vmhost in $vmhosts)
{
    #Gets all the vSwitch names that has beacon probing set on the host.
    $switch_policy = Get-VirtualSwitch -VMHost $vmhost.Name | where {$_.Name -ne "vSwitchiDRACvusb"} | Get-NicTeamingPolicy | Where-Object {$_.NetworkFailoverDetectionPolicy -eq "BeaconProbing"} | select -ExpandProperty VirtualSwitch # | select VirtualSwitch | format-wide
    if ($switch_policy)
    {
        foreach ($switch in $switch_policy)
        {
            $vs = Get-VirtualSwitch -VMHost $vmhost.Name -Name $switch
            Get-NicTeamingPolicy -VirtualSwitch $vs | Set-NicTeamingPolicy -NetworkFailoverDetectionPolicy LinkStatus
        }
    }
 
    #Gets all the port group names that has beacon probing set on the host.
    $portgroup_policy = Get-VirtualPortGroup -VMHost $vmhost | Get-NicTeamingPolicy | Where-Object {$_.NetworkFailoverDetectionPolicy -eq "BeaconProbing"} | select -ExpandProperty VirtualPortGroup
    if ($portgroup_policy)
    {
        foreach ($p in $portgroup_policy)
        {
            #Sets the nicteamingpolicy from the host and its portgroup.
            $vpg = Get-VirtualPortGroup -VMHost $vmhost.Name -Name $p
            Get-NicTeamingPolicy -VirtualPortGroup $vpg | Set-NicTeamingPolicy -NetworkFailoverDetectionPolicy LinkStatus
        }
    }
}

Find overcommited compute resources in VMWare.



The following commands requires PowerCLI to run.

Get-MemoryOvercommit -Cluster "Cluster Name"
Get-CPUOvercommit -Cluster "Cluster Name"



Get space utilization of all disk from a computer


[CmdletBinding ()]
param(
        [Parameter(Mandatory =$True, ValueFromPipeline=$True )]
        [string[]] $ComputerName
    )
ForEach ( $Name in $ComputerName ) {
    write-host "Drive info for " $Name
    Get-WmiObject -Class win32_logicaldisk -ComputerName $Name |
ft DeviceID , @{Name= "Free Disk Space (GB)";e= {$_.FreeSpace /1GB }}, @{Name ="Total Disk Size (GB)";e ={$_ .Size / 1GB}} -AutoSize

Tuesday, April 17, 2018

VMWare vSphere 6.7 is out.

Some new features of vSphere 6.7
-HTML 5 Client
        More features enabled such as vSAN and core storage.
-UNMAP Enhancements
        Able to adjust reclaim rate.  6.5 has a rate of 25MBps.  6.7 can go to 2GBps.
-vSAN 6.7
        QOS Resyncing of data.
        On-Disk Format 6
                -No more actual data moves or evacuation to upgrade a disk format.  Going forward, it will just be meta-data upgrades.
        FIPS 140-2 Encryption.
        

Thursday, February 8, 2018

Setting up iSCSI initiator to connect to iSCSI target in Linux.

  1. Install open-iscsi
    • # sudo apt-get install open-iscsi
    • # sudo apt-get install open-iscsi-utils
  2. Configure the iscsid.conf file with your login credentials.
    • vi /etc/iscsi/iscsid.conf
    • edit the line 'node.session.auth.username='
    • edit the line 'node.session.auth.password='
    • enable CHAP authentication
    • uncomment the line 'node.session.auth.authmethod = CHAP'
  1. Restart open-iscsi service
    • /etc/init.d/open-iscsi restart
  2. Discover your iSCSI targets
    • # iscsiadm -m discovery -t sendtargets -p <ip address of the iscsi target>:3260
  3. List your iSCSI nodes
    • # iscsiadmin -m node
  4. Restart open-iscsi service
    • /etc/init.d/open-iscsi restart
  5. Find the disk
    • # dmesg | tail
  6. Mount the disk
    • # mount /dev/sdb1 /mnt/iscsi

Thursday, January 18, 2018

Decrypt Files from QNAP with OpenSSL

To decrypt files that was encrypted on a QNAP, use the following command.

From the Linux terminal:

    Decrypt one file
        openssl enc -d -aes-256-cbc -k <decrypt password> -in filename.jpg -out filename.jpg

    Decrypt multiple files in a folder.
        for f in * ; do [ -f $f ] && openssl enc -d -aes-256-cbc -k <decrypt password> -in $f -out _$f;


Export a Sharepoint list to a csv using C#.

Below is the code to export a Sharepoint List to a CSV file using C#.NET

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.IO;

namespace export_sharepoint
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "<Site URL>" ;

            using (SPSite oSite = new SPSite(url))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists["<List Name>" ];

                    foreach (SPListItem oItem in oList.Items)
                    {
                         FileStream fs = new FileStream ( "C:\\Documents and Settings\\administrator.domain\\Desktop\\sites.txt", FileMode.Append, FileAccess.Write, FileShare .Read);
                         StreamWriter writer = new StreamWriter(fs);
                        // Access each item in the list... 
                        writer.Write(oItem[ "Site ID"]);
                        writer.Write( ",");
                        writer.Write(oItem[ "Column Name"]);
                        writer.Write( ",");

                        writer.Close();
                        fs.Close();
                    }

                }
            } 
        }
    }

Create a CIFS share on a Netapp from the command line.


cifs shares -add "SHARE NAME" "/vol/fw_volume1/share location/"
cifs access "AD GROUP" "ROLE_ETC" "Full Control"
cifs access -delete "Everyone"

Saturday, January 13, 2018

Finally got a Sega Saturn. Derby Stallion edition!

Sold a Neo Geo Cyberlip and a Nintendo Game and Watch to buy this console.  Wanted this console for a long time so I thought why not go for the Derby Stallion edition!  This console is awesome looking.  It's looks brand spanking new too.  The game inside is Battle Garegga!


Thursday, January 11, 2018

Reset Local Administrator Password

Here's a way to reset the local Administrator password in Windows 2008.

  1. Boot up a WIndows installer CD.
  2. Press F8 at the Local Deployment Wizard
  3. Type in 
    1. move d:\windows\system32\utilman.exe d:\
    2. copy d:\windows\system32\cmd.exe d:\windows\system32\utilman.exe
  4. Boot to normal Window.  At the log in, click on "Ease of Access" button at the bottom left.
  5. Type in:
    1. net user administrator /active:yes
    2. net user administrator <new password>



Tuesday, January 9, 2018

Add local printer via powershell

add-printerport -name 'printer_name' -printerhostaddress '192.168.0.1'
add-printerdriver -Name 'HP LaserJet 4200/4300 PCL6 Class Driver'
add-printer -Name 'printer_name' -DriverName 'HP LaserJet 4200/4300 PCL6 Class Driver' -PortName 'printer_name'



Disable SSL check on GIT

When you connect to a GIT repository, it may fail due to
Start GIT Bash
Run the following command.
     git config --global http.sslVerify false


Monday, January 8, 2018

Setting up Redhat Enterprise Virtualization Manager (RHEVM)

Steps to set up Redhat Enterprise Virtualization Manager.

1.  Install Redhat Enterprise Linux 

2.  Register to the Redhat Network
          #>Subscription-manager register
                    Type in your rhn account info.

3.  Attach all the subscriptions available to the version of Redhat Linux you're running.
          #>Subscription-manager attach --auto

4.  Install yum-config-manager utility
          #>yum install yum-utils

5.  Run yum-config-manager to add Redhat Enterprise Virtualization Manager package to the subscription.
          #>yum-config-manager --enable rhel-6-server-rhevm-3.4-rpms

6.  Run yum-config-manager to add JBoss package to the subscription.
          #>yum-config-manager --enable jb-eap-6-for-rhel-6-server-rpms

7.  Install JBoss
          #>yum install jbossas-standalone

8.  Downgrade sos package (not sure why this is required but it was complaining about the sos version is too new)
          #>yum remove sos-3.2-28.el6.noarch
          #>yum install sos-2.2-68.el6.noarch

9.  Install rhevm
          #>yum install rhevm

10. Install rhevm reporting
          #>yum install rhevm-reports

11. Run the setup wizard.
          #>engine-setup

12. Create ISO domain (Use to store .iso files so you can build the vm)

13. Upload to the ISO domain
          #>rhevm-iso-uploader --iso-domain=<ISO domain name> upload myfile.iso --insecure

14.  To be able to mount the windows drivers in the vm, run the following.
          #>yum install virtio-win
          #>yum install libvirt-devel
          #>yum install libvirt
          #>yum install virt-install




Disable SSL on VMWare Converter.

Disabling SSL on VMWare converter can result in faster conversion speeds.

Go to 
C:\ProgramData\VMware\VMware vCenter Converter Standalone\converter-worker.xml
Change   
     <useSsl>true</useSsl>
to
     <useSsl>false</useSsl>



Amazon S3 storage used calculation.

From the reports exported from Amazon S3, the value is in "TimedStorage-BytesHrs"  It's not very useful if you're doing cost analysis.  
Below is the formula to convert it to a usable GB-Months format.

TimedStorage-BytesHrs * 30 * (1 GB/ 1,073,741,824) * (1 Month/744) = GB-Months.

GB-Months x .03 = Total Cost per month.

vCenter database queries

Log into SQL where the vCenter database is on and run the following query:

How many VMs have been deployed.

    select CREATE_TIME,VM_NAME from VPX_EVENT where EVENT_TYPE='vim.event.VMBeingDeployedEvent' and CREATE_TIME>='2012-01-01' and CREATE_TIME<='2013-01-01' and VM_NAME     like 'searchname%' and VM_NAME not like 'vm_name%' and VM_NAME not like 'vm_name%'and VM_NAME not like 'vm_name%' and VM_NAME not like 'vm_name%'    select CREATE_TIME, VM_NAME from VPX_EVENT where EVENT_TYPE= 'vim.event.VMRemovedEvent' and CREATE_TIME >= '2012-01-01' and CREATE_TIME <= '2013-01-01'    select CREATE_TIME, VM_NAME from VPX_EVENT where EVENT_TYPE= 'vim.event.VMCreatedEvent' and CREATE_TIME >= '2012-01-01' and CREATE_TIME <= '2013-01-01'

Memory usage for the year.

    select sample_time, stat_name, stat_value from VPXV_HIST_STAT_YEARLY where stat_group='mem' and stat_name='usage'

Restore bare metal with SCDPM

Bare Metal Recovery with System Center Data Protection Manager.

     - Boot from Windows DVD
     - Click on "Repair Your Computer" (instead of the "Install Now" link)
     - Click on the "Windows Complete PC Restore" option
     - Click "Restore a Different Backup option"
     - Enter the path to the second share
     - Select the backup from the list and click Next
     - Select Windows format and repartition disk.


Mount CIFS share in Linux

mount -t cifs //netbiosname/sharename /media/sharename -o username=username,password=password,uid=linuxusername,iocharset=utf8,umask=664,rw

Friday, January 5, 2018

Reset vmware ESX evaluation license.

VMWare ESXi license expires in 60 days.  You can reset that 60 days by doing the following.

-ssh into the ESXi host.
-rm -f /etc/vmware/vmware.lic /etc/vmware/license.cfg
-reboot

SQL does not allow modifying of table.

If you've dealt with MS SQL before, by default, it does not allow you to modify a table without you dropping it and recreating it. It's kind of annoying.   Here's a way to get around it.  Do this at your own risk of corrupting your database.

-Go to the Tools menu -> Options
-Click on "Designers" on the left menu tree
-Uncheck "Prevent saving changes that require table re-creation"



VMWare - Power ON a vm from the command line

To power on a virtual machine from the command line:

-List the inventory ID of the virtual machine with the command:
               vim-cmd vmsvc/getallvms |grep <vm name>
               Note: The first column of the output shows the vmid.

-Check the power state of the virtual machine with the command:
               vim-cmd vmsvc/power.getstate <vmid>

-Power-on the virtual machine with the command:
               vim-cmd vmsvc/power.on <vmid>

How to use ImageX

imagex /capture <source disk> <destination disk>:\<wim filename> "description"
imagex /capture d: z:\c.wim "wimtest"

DISKPART>list disk
DISKPART>select disk (id)
DISKPART>online disk (if the disk is not online)
DISKPART>clean
DISKPART>convert mbr (or gpt)
DISKPART>create partition primary
DISKPART>select part 1
DISKPART>active (if this is the boot partition)
DISKPART>format fs=ntfs label=(name) quick
DISKPART>assign letter c:
DISKPART>list volume
DISKPART>exit

X:\Tools>net use n: \\server\share /user:Domain\username "password"
X:\Tools>imagex /apply <source disk>:\<wim filename> "samedescription" c:
X:\bcdboot c:\windows
chkdsk c: /f /v /x

1.  go to windows aik tools directory and run "copype.cmd x86 c:\winpe" to create winpe structure to c:\winpe.

2.  mount the wim file on c:\winpe\winpe.
                      "imagex /mountrw d:\boot.wim 1 d:\image.mount"

3.  edit image........
4.  unmount the wim file and commit changes.
                      "imagex /umount /commit d:\image.mount"

5.  copy the wim file to winpe structure created in step 1.  c:\winpe\ISO\sources

6.  create an iso from image.
                      "oscdimg -n -bc:\winpe\iso\boot\etfsboot.com c:\winpe\iso d:\ghost.iso"

Get formatted date in a batch file.

SET mm=%DATE:~4,2%   -  This moves 4 positions and gets the next 2 positions.
SET dd=%DATE:~7,2%     -  This moves 7 positions and gets the next 2 positions.
SET yyyy=%DATE:~10,4% -  This moves 10 positions and gets the next 4 positions.

Output it in a script
%yyyy%.%mm%.%dd%

VSS Error while running system state/bare metal restore backup using SCDPM.

When running a system state/bare metal restore backup using SCDPM, you may encounter a VSS error leading to a protection point inconsistency.  This is due to automounter being disabled and the system restore partition being offline in disk management.  The cause of this may be a third party snapshot tool that leverages VSS such as Netapp's SnapDrive.  In order to get SCDPM to do a system state/bare metal restore, you will need to do the following steps.  Note: this works for VMWare converter as well if you're getting

System Partition is offline.  No drive letters

1.  log into the server you want to protect.
2.  open a command prompt
3.  type "diskpart"
4.  type "automount" to display the current state of automount.  If its disabled, open another command prompt and run "diskpart> automount enable" to enable it.
5.  in diskpart, get a list of volumes by typing "list volume".
6.  find the system restore partition and note down the volume number.
7.  type "select volume (x)" where x is the volume number of the system restore partition.
8.  type "online volume" to bring the volume online.
9.  rerun the SCDPM consistency check and it should be successful.

Before

After (Notice "System Reserved" volume is labeled)

Get network info from vmnic using esxcli


Display driver info for network adapter
    esxcli network nic get -n vmnicX

Display network statistics (bytes transferred, errors, packets transferred)
    esxcli network nic stats get -n vmnicX

GIT usage

git clone http://ift.tt/2CJipdp


  • Get the newest stuff from gitlab repository (sync your local repo with the “origin”):
    • git pull
  • Add it to “staging” in the local repo
    • git add "filename"
  • Commit the change in the local repo
    • git commit -m “whatever was changed”
  • Push changes “up” to gitlab server
    • git push origin master
  • Verify commit shows up in the web interface of the gitlab server
  

ESXTOP quick troubleshooting overview


vSAN 6.x cluster shut down and power on procedures

Shutting down the vSAN 6.x cluster

To shut down the vSAN cluster:
  1. Shut down all virtual machines running on the vSAN Cluster.

    Note:The vCenter Server virtual machine must be shut down at the end.

  2. Note the host that your vCenter Server virtual machine resides on. 

    Note: VMware recommends to migrate the vCenter Server virtual machine to the first ESXi host, so you can easily find the virtual machine when powering on your vSAN cluster again.

  3. Ensure that there are no vSAN components currently resynching. For more information, see the Monitor the Resynchronization Tasks in the Virtual SAN Cluster section in the Administering VMware Virtual SAN.
  4. Shut down the vCenter Server virtual machine. This makes the vSphere Web Client unavailable.
  5. Connect to the ESXi host shell. For more information, see  Using ESXi Shell in ESXi 5.x and 6.0 (2004746).
  6. Place all ESXi hosts into Maintenance Mode. This operation must be done using one of the CLI methods that supports setting the vSAN mode when entering Maintenance Mode. You can either do this by logging directly in to the ESXi Shell and running the ESXCLI command locally or you can invoke this operation on a remote system using ESXCLI.
  7. Run this ESXCLI command and ensure that the No Action option is selected when you enter Maintenance Mode:

    # esxcli system maintenanceMode set -e true -m noAction

  8. Shut down all ESXi hosts. You can log in to each ESXi hosts using either the vSphere Client or the ESXi shell. You can also perform this operation remotely using a vSphere API, such as PowerCLI.




Powering on the vSAN 6.x cluster

To power on your vSAN cluster:
  1. Boot up the ESXi hosts through remote console session or physically.
  2. Connect to the shell of each ESXi host and run this command to exit maintenance mode:

    # esxcli system maintenanceMode set -e false

  3. Locate your vCenter virtual machine and power it on using a vSphere client connection directly to the host.
  4. Using the vSphere Client, connect to the ESXi host that contains your vCenter virtual machine. Power on your vCenter Server

    Note: This should be on the first ESXi host, If you moved this virtual machine to that host in step 2 of the shut down procedure.

  5. Connect to your vCenter Server using the vSphere Web Client.

    Note: It may take a few minutes for vCenter Server to become available again

  6. Do a quick health check on the vSAN cluster. Check for network partitions and resyncing components. For more information, see the Monitoring Virtual SAN section of the Administering VMware Virtual SAN.
  7. Power on the remaining virtual machines in the vSAN cluster.


Power off a Virtual SAN Cluster

Power off a Virtual SAN Cluster

Prerequisites
If the vCenter Server VM is running on the Virtual SAN cluster, migrate the VM to the first host, or record the host where it is currently running.
Procedure

1
Power off all virtual machines that are running on the Virtual SAN cluster.
The vCenter Server virtual machine must be powered off last.
2
Place all ESXi hosts that compose the cluster in maintenance mode.
Run the esxcli command to set the Virtual SAN mode for entering the maintenance state.
esxcli system maintenanceMode set -e true -m noAction
3
Power off the ESXi hosts.


Bare metal recovery for Windows 2012 from a Windows Server Backup image.

Bare metal recovery for Windows 2012 from a Windows Server Backup image.

  1. Create an ISO of the backup image and mount it to VM.
  2. Install a fresh OS
  3. Install vmware tools.
  4. Reboot into Windows install ISO.
  5. Select System Image Recovery
  6. Select the command prompt.
  7. Type in "start /w wpeinit"  to enable the network and get an ip.
  8. Exit the command prompt.
  9. Select System Image Recovery.
  10. Select the Operating System.
  11. Select the "Select a system image" radio button and next.
  12. Click on the "Advanced.." button.
  13. Click on "Search for a system image on the network"
  14. Type in the path of the backup.  Make sure its the path that has the "WindowsImageBackup" folder or it will not detect an available image.
  15. Type in your credentials.
  16. Select the backup from the list and click Next.


Update user home directory with Powershell

Import-Module ActiveDirectory
$users = Get-ADUser -SearchBase "<Path to Organizational Unit" -Filter * -Properties *

ForEach ($user in $users)
{
$sam = $user. SamAccountName
Set-ADuser -Identity $sam -HomeDirectory "\\server\users$\ $sam"

To find a VM with a particular snapshot name

Get-Snapshot -VM VM -Name '<snapshot name>'


Power on/off VM via command line.


Power on a VM
To power on a virtual machine from the command line:
  1. List the inventory ID of the virtual machine with the command:

    vim-cmd vmsvc/getallvms |grep <vm name>

    Note: The first column of the output shows the vmid.

  2. Check the power state of the virtual machine with the command:

    vim-cmd vmsvc/power.getstate <vmid>

  3. Power-on the virtual machine with the command:

    vim-cmd vmsvc/power.on <vmid>

Get all vm's with connected CD rom drives

This is a powercli command to get all the vm's with connected cdrom drive.  

get-cluster | where {$_.Name -eq "SFColo Test & Dev"} | get-vm | where { $_ | get-cddrive | where { $_.ConnectionState.Connected -eq "true" } } | select Name


Get VMX and VMWare tools version and export to CSV

To get the VMware tools versions and export it to a csv called vmtools.csv

get-vm | where {$_.powerstate -ne "PoweredOff" } | where {$_.Guest.ToolsVersionStatus -ne "guestToolsCurrent"} | % { get-view $_.id } | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}}, @{ Name="ToolStatus"; Expression={$_.Guest.ToolsVersionStatus}} | Export-Csv -NoTypeInformation -UseCulture -Path d:\vmtools.csv

VMWare - VCBMounter Command

VCBMounter Command

to mount full vm.
vcbmounter.exe -h vcenter_hostname -u fwvcb -p <password> -r d:\vmbackups\<name> -a name:name_of_vm -t fullvm -m nbd

to umount full vm.
vcbmounter.exe -h vcenter_hostname -u fwvcb -p <password> -U d:\vmbackups\<name>

Disable IPv6 via commands in Windows

get-netadapterbinding
set-NetAdapterBinding -Name “Network Adapter Name” –ComponentID ms_tcpip6 –Enabled $False

new-itemproperty -Path HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters -Name DisabledComponents -PropertyType DWord -Value ffffffff

Reset a slot in Cisco UCS.

- Reset a slot (equivalent to remove power from the blade and reapplying):
     #reset slot x/y (where x = chassis and y = blade or server #)

Powershell: Check if a registry key exist.

This script traverse through an OU and get all the computer names and check to see if "CryptoLocker_0388" key exists.
If it does, then that machine has been infected by the CryptoLocker virus.

$ou=[ADSI]"LDAP://path_to_organizational_unit"

foreach($childin$ou.psbase.Children)
{
   if($child.ObjectCategory-like'*computer*')
    {
          $line=$child.Name

       try
             {
               # Test-Connection -ComputerName $line -Count 1
               $reg=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser',$line)
               $regkey=$reg.OpenSubkey("SOFTWARE\\CryptoLocker_0388")
               if(!$regkey)
                            {
                  write-host$line-----"Key Not Found"
                }
               else
                          {
                  write-host$line-----"Key Found"
                }
        }
       catch
             {
               write-host$line-----"Offline"
        }
    }
}

Tarball an entire Linux system

#!/bin/bash
#Version: 1.0
#Description:  Checks for a destination mount directory.  Mounts it if it does not exist, the backs up the server to the mount directory.

mountdir="<mount directory>"
servername="<servername>"
exclusions="--exclude=/mnt --exclude=/proc --exclude=/lost+found --exclude=/tmp --exclude=/media --exclude=/sys --exclude=/dev --exclude=/run --exclude=/var/cache"

if [ -d $mountdir ]; then
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
else
     sudo mount -t cifs -o username=moatisuser,password=moatisuser,rw \\\\fw24\\ata_1 /mnt/fw24
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
fi

Enable SNMP on ESXi

  1. ssh into the esxi host.
  2. esxcli system snmp set --communities="string name"
  3. esxcli system snmp set --targets="<monitoring server>"@161/"string name","<monitoring server>"@161/"string name"
  4. esxcli system snmp set --enable true
  5. esxcli system snmp test
  6. log into vi client.
  7. find the server and go to the configuration tab.
  8. select Security Profile under Software
  9. select Properties under Firewall
  10. find SNMP server and click on the Options button.
  11. start the service.


esxcli system snmp set --communities="MRTG"
esxcli system snmp set --targets="fwprd-slw-ape1"@161/"MRTG","fwprd-slw-ape2"@161/"MRTG","fwprd-slw-core"@161/"MRTG"
esxcli system snmp set --enable true
esxcli system snmp test


Set up Gnome in Arch Linux

1.  check what type of video card
         lspci | grep VGA
2.  install video driver
         pacman -Syu xf86-video-intel (for intel graphics card), xf86-video-ati (for ati), xf86-video-nv (for nvidia)
3.  install touchpad driver
         pacman -Syu xf86-input-synaptics
4.  install xorg
         pacman -Syu xorg-server
5.  install xorg-xinit
         pacman -Syu xorg-xinit
6.  install gnome and gdm
         pacman -Syu gnome
         pacman -Syu gdm
7.  enable gdm on startup
         systemctl enable gdm

         pacman -Syu gnome-panel
         pacman -Syu gnome-tweak-tool
         pacman -Syu gnome-themes-extras

Setup iptables in Linux

Ubuntu does come with iptables preset like in Fedora. Here's the base set up for iptables.

Add iptable rules.

Block Null Packets
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

Reject Syn-Flood Attack

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

Reject XMAS/recon packets

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

Allow custom ports
<here>

Accept Established Connections

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A INPUT -j REJECT iptables -A FORWARD -j REJECT

iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -j REJECT

iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

Use iptables-save to save it to a file.
iptables-save > /etc/iptables.rules

Edit rc.local to import iptables rules during boot up.
iptables-restore < /etc/iptables.rules

Write to a file in CSharp

Quick and dirty way to write to a file in C#.

StreamWriter log = new StreamWriter(@c:\log.txt);
log.WriteLine(ErrorMessage);
log.WriteLine();
log.Close();

test test

Base server build with Arch Linux

From usb stick(sdb) to hard drive(sda)

1. boot from usb stick.

2. run cfdisk to partition hard drive (sda)

        a. cfdisk /dev/sda

b. create a root (/) partition - sda1

c. create a swap (swap) partition - sda2

3. format disk to ext4

a. mkfs.ext4 /dev/sda1

b. mkfs.ext4 /dev/sda2

4. make swap

a. mkswap /dev/sda2

5. turn swap on

a. swapon /dev/sda2

6. mount the hard disk.

a. mount /dev/sda1 /mnt

7. install arch linux base

a. pacstrap -i /mnt base

8. generate fstab

a. genfstab -U -p /mnt >> /mnt/etc/fstab

9. chroot into /mnt

a. arch-chroot /mnt

10. set location

a. vi /etc/locale.gen

b. uncomment en_US.UTF-8 UTF-8

11. set hostname

a. echo myservername > /etc/hostname

12. set up network

a. cp /etc/network.d/examples/ethernet-static to /etc/network.d

b. ls /sys/class/net to get the list of interfaces.

c. vi ethernet-static and edit ip/gw info. Change the interface to the correct interface.

d. vi /etc/conf.d/netcfg and point NETWORKS=(ethernet-static)

For DHCP:

a. systemctl enable dhcpcd@eth0

b. systemctl start dhcpcd@eth0

13. enable netcfg service

a. systemctl enable netcfg.service

14. change password

a. passwd

15. Install grub bootloader

a. pacman -S syslinux

b. syslinux-install_update -i -a -m

c. vi /boot/syslinux/syslinux.cfg and change APPEND root-/dev/sda3 ro to the correct boot partition.

d. pacman -S grub-bios

e. grub-install --recheck /dev/sda1

16. exit chroot

17. unmount /mnt

18. reboot and remove the usb stick.

Get Last Backup Field in vCenter with Powershell.

#This is a little Powershell script that gets the last time a vm in the Cluster that it has been backed up.  Emails out if it has not been backed up in 14days.

$daystoalert = 14
$vCenter = "vCenter server name"

add-pssnapin vmware.vimautomation.core
connect-viserver $vCenter
$today_date = get-date

$all_vms = get-cluster "Cluster Name" | get-vm | Sort-Object Name

foreach($vm in $all_vms)
{
    #check $vm for null?
    Try {
        $last_backup_date = $vm. CustomFields.Get_Item( "Last Backup")
        $last_backup_converted = get-date $last_backup_date
        $days_with_no_backups = New-TimeSpan -Start $last_backup_converted .DateTime -End $today_date. DateTime
        if ($days_with_no_backups .Days -gt $daystoalert)
        {
            Write-output " $($vm. Name),$( $days_with_no_backups.Days) "
        }
    }
    Catch {
        # VM was never backed up gets caught in this exception.
        Write-output " $($vm. Name), Never backed up"
    }

Delete files in a folder and subfolders of files based on last access time

Get-ChildItem -path "D:\ftp.archived.logs" -Recurse | Where-Object{$_.LastAccessTime -lt (get-date).AddDays(-90)} | remove-item 

add -whatif at the end of remove-item to show what will get removed.



Enable/Disable SMBv1,2,3 in Windows


Disable form repost on browser refresh

Here's a trick I found to prevent a form repost on browser refresh


        protected void Page_PreRender(object sender, EventArgs e)
        {
                     ViewState["Check_Page_Refresh"] = Session["Check_Page_Refresh"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["Check_Page_Refresh"] = DateTime.Now.ToString();
            }
        }

protected void btn_Click(object sender, EventArgs e)
{
if (ViewState["Check_Page_Refresh"].ToString() == Session["Check_Page_Refresh"].ToString())
{
     <your main code you want to execute once on button click here>
}
}

Active Directory authentication using C#

bool authenticated;
using(PrincipalContext pc =newPrincipalContext(ContextType.Domain, domain.ToString()))
{
     authenticated = pc.ValidateCredentials(<user name>,<password>,ContextOptions.Negotiate);
}
if (authenticated)
{

}

Reset vmware ESX evaluation license.

VMWare ESXi license expires in 60 days.  You can reset that 60 days by doing the following.

-ssh into the ESXi host.
-rm -f /etc/vmware/vmware.lic /etc/vmware/license.cfg
-reboot

SQL does not allow modifying of table.

If you've dealt with MS SQL before, by default, it does not allow you to modify a table without you dropping it and recreating it. It's kind of annoying.   Here's a way to get around it.  Do this at your own risk of corrupting your database.

-Go to the Tools menu -> Options
-Click on "Designers" on the left menu tree
-Uncheck "Prevent saving changes that require table re-creation"



VMWare - Power ON a vm from the command line

To power on a virtual machine from the command line:

-List the inventory ID of the virtual machine with the command:
               vim-cmd vmsvc/getallvms |grep <vm name>
               Note: The first column of the output shows the vmid.

-Check the power state of the virtual machine with the command:
               vim-cmd vmsvc/power.getstate <vmid>

-Power-on the virtual machine with the command:
               vim-cmd vmsvc/power.on <vmid>

VSS Error while running system state/bare metal restore backup using SCDPM.

When running a system state/bare metal restore backup using SCDPM, you may encounter a VSS error leading to a protection point inconsistency.  This is due to automounter being disabled and the system restore partition being offline in disk management.  The cause of this may be a third party snapshot tool that leverages VSS such as Netapp's SnapDrive.  In order to get SCDPM to do a system state/bare metal restore, you will need to do the following steps.  Note: this works for VMWare converter as well if you're getting

System Partition is offline.  No drive letters

1.  log into the server you want to protect.
2.  open a command prompt
3.  type "diskpart"
4.  type "automount" to display the current state of automount.  If its disabled, open another command prompt and run "diskpart> automount enable" to enable it.
5.  in diskpart, get a list of volumes by typing "list volume".
6.  find the system restore partition and note down the volume number.
7.  type "select volume (x)" where x is the volume number of the system restore partition.
8.  type "online volume" to bring the volume online.
9.  rerun the SCDPM consistency check and it should be successful.

Before

After (Notice "System Reserved" volume is labeled)

ESXTOP quick troubleshooting overview


Bare metal recovery for Windows 2012 from a Windows Server Backup image.

Bare metal recovery for Windows 2012 from a Windows Server Backup image.

  1. Create an ISO of the backup image and mount it to VM.
  2. Install a fresh OS
  3. Install vmware tools.
  4. Reboot into Windows install ISO.
  5. Select System Image Recovery
  6. Select the command prompt.
  7. Type in "start /w wpeinit"  to enable the network and get an ip.
  8. Exit the command prompt.
  9. Select System Image Recovery.
  10. Select the Operating System.
  11. Select the "Select a system image" radio button and next.
  12. Click on the "Advanced.." button.
  13. Click on "Search for a system image on the network"
  14. Type in the path of the backup.  Make sure its the path that has the "WindowsImageBackup" folder or it will not detect an available image.
  15. Type in your credentials.
  16. Select the backup from the list and click Next.


To find a VM with a particular snapshot name

Get-Snapshot -VM VM -Name '<snapshot name>'


Power on/off VM via command line.


Power on a VM
To power on a virtual machine from the command line:
  1. List the inventory ID of the virtual machine with the command:

    vim-cmd vmsvc/getallvms |grep <vm name>

    Note: The first column of the output shows the vmid.

  2. Check the power state of the virtual machine with the command:

    vim-cmd vmsvc/power.getstate <vmid>

  3. Power-on the virtual machine with the command:

    vim-cmd vmsvc/power.on <vmid>

Get all vm's with connected CD rom drives

This is a powercli command to get all the vm's with connected cdrom drive.  

get-cluster | where {$_.Name -eq "SFColo Test & Dev"} | get-vm | where { $_ | get-cddrive | where { $_.ConnectionState.Connected -eq "true" } } | select Name


Get VMX and VMWare tools version and export to CSV

To get the VMware tools versions and export it to a csv called vmtools.csv

get-vm | where {$_.powerstate -ne "PoweredOff" } | where {$_.Guest.ToolsVersionStatus -ne "guestToolsCurrent"} | % { get-view $_.id } | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}}, @{ Name="ToolStatus"; Expression={$_.Guest.ToolsVersionStatus}} | Export-Csv -NoTypeInformation -UseCulture -Path d:\vmtools.csv

Disable IPv6 via commands in Windows

get-netadapterbinding
set-NetAdapterBinding -Name “Network Adapter Name” –ComponentID ms_tcpip6 –Enabled $False

new-itemproperty -Path HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters -Name DisabledComponents -PropertyType DWord -Value ffffffff

Reset a slot in Cisco UCS.

- Reset a slot (equivalent to remove power from the blade and reapplying):
     #reset slot x/y (where x = chassis and y = blade or server #)

Tarball an entire Linux system

#!/bin/bash
#Version: 1.0
#Description:  Checks for a destination mount directory.  Mounts it if it does not exist, the backs up the server to the mount directory.

mountdir="<mount directory>"
servername="<servername>"
exclusions="--exclude=/mnt --exclude=/proc --exclude=/lost+found --exclude=/tmp --exclude=/media --exclude=/sys --exclude=/dev --exclude=/run --exclude=/var/cache"

if [ -d $mountdir ]; then
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
else
     sudo mount -t cifs -o username=moatisuser,password=moatisuser,rw \\\\fw24\\ata_1 /mnt/fw24
     cd $mountdir
     tar -zcpf $servername-full-backup-`date '+%d-%B-%Y'`.tar.gz / $exclusions
fi

Setup iptables in Linux

Ubuntu does come with iptables preset like in Fedora. Here's the base set up for iptables.

Add iptable rules.

Block Null Packets
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

Reject Syn-Flood Attack

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

Reject XMAS/recon packets

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

Allow custom ports
<here>

Accept Established Connections

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A INPUT -j REJECT iptables -A FORWARD -j REJECT

iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -j REJECT

iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

Use iptables-save to save it to a file.
iptables-save > /etc/iptables.rules

Edit rc.local to import iptables rules during boot up.
iptables-restore < /etc/iptables.rules