How to Deploy war file in Tomcat

Description: Here I have explained how to deploy war file in Tomcat

Procedure: There are two ways to deploy war file in tomcat.

  1. Copy war file to webapp folder
  • Open webapp folder and copy sample.war file 
  • After copying file browse URL http://localhost:8080/sample 
  • Once you browse URL folder sample folder will automatically create under webapp folder
    
      2. Upload and Deploy war file remotely. 
  • Open http://localhost:8080/manager
  • Login with admin credentials [define in tomcat-users.xml] 
  • Browse war file and Deploy

403 Access Denied in Tomcat Host-manage webapp

Description: 403 Access Denied in Tomcat in Manager and host-manage webapp

Procedure: Here I have explained how to add user for host-manage and manager webapp

  • Go to /opt/tomcat/webapps/host-manager/META-INF open context.xml comment everything in context tag example:


     <!--Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /-->
   
  • Open /opt/tomcat/conf/tomcat-users.xml and add user details as follow:




  • Restart tomcat service and verify by browse http://IPADDRESS:8080/host-manager
  • Install Tomcat On Centos 7

    Description: Here I have explained how to install Tomcat on Centos 7

    Procedure: 

    • Install JDK: Tomcat 9 require java 8 or later. You can install java using below command.
    # yum install java-1.8.0-openjdk-devel

    • Verify Java Version: 
    # java -version
    openjdk version "1.8.0_242"
    OpenJDK Runtime Environment (build 1.8.0_242-b08)
    OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)
    • Create User For Tomcat:  For security purpose create user with group and home directory for tomcat.
    # useradd -m -U -d /opt/tomcat -s /bin/false tomcat
    • Download Tomcat : We will download latest version of  Tomcat from Tomcat Download Site Navigate to /tmp directory and download using wget command.
    # cd /tmp
    # wget https://downloads.apache.org/tomcat/tomcat-9/v9.0.34/bin/apache-tomcat-9.0.34.tar.gz
    • Extract tar file 
    tar -zxvf apache-tomcat-9.0.34.tar.gz
    • Move folder to opt drive
    # mv apache-tomcat-9.0.34.tar.gz /opt/tomcat/
    • Change User ownership 
    chown -R tomcat: /opt/tomcat
    • Executable File:  Make the scripts inside the bin directory executable by issuing the following chmod command:
    # chmod +x /opt/tomcat/bin/*.sh
    • Create Tomcat Service : Create service to start or stop tomcat and paste below content.
    # vi /etc/systemd/system/tomcat.service
    [Unit]
    Description=Tomcat 9 servlet container

    After=network.target

    [Service]

    Type=forking
    User=tomcat
    Group=tomcat
    Environment="JAVA_HOME=/usr/lib/jvm/jre"
    Environment="JAVA_OPTS=-Djava.security.egd=file:///dev/urandom"
    Environment="CATALINA_BASE=/opt/tomcat"
    Environment="CATALINA_HOME=/opt/tomcat"
    Environment="CATALINA_PID=/opt/tomcat/temp/tomcat.pid"
    Environment="CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC"
    ExecStart=/opt/tomcat/bin/startup.sh
    ExecStop=/opt/tomcat/bin/shutdown.sh

    [Install]
    WantedBy=multi-user.target
    • Save file and notify systemd that we created a new unit file by typing:
    # systemctl daemon-reload
    • Start and Enable Service
    # systemctl enable tomcat
    # systemctl start tomcat
    • Setup firewall and enable tomcat port
    # firewall-cmd --zone=public --permanent --add-port=8080/tcp
    # firewall-cmd --reload

    Virtual Machine Backup in Hyper-V

    Description: Here I have explained how to take backup Virtual Machine Backup using Powershell Script.

    Procedure:

    • Create list of virtual machine and save in vmbackup.txt file as follow.

    vm1
    vm2
    vm3

    • Create blank Power shell file and paste below content ahd save as Hyper-V-Backup.ps1
    <#
    .SYNOPSIS
    Hyper-V Backup Utility - Flexible backup of Hyper-V Virtual Machines.

    .DESCRIPTION
    This script will create a full backup of virtual machines, complete with configuration, snapshots/checkpoints, and VHD files.
    This script should be run on a Hyper-V host and the Hyper-V PowerShell management modules should be installed.

    To send a log file via e-mail using ssl and an SMTP password you must generate an encrypted password file.
    The password file is unique to both the user and machine.
    To create the password file run this command as the user and on the machine that will use the file:

    $creds = Get-Credential
    $creds.Password | ConvertFrom-SecureString | Set-Content c:\foo\ps-script-pwd.txt

    .PARAMETER BackupTo

    The path the virtual machines should be backed up to.
    Each VM will have its own folder inside this location.
    Do not add a trailing backslash.

    .PARAMETER List

    Enter the path to a txt file with a list of Hyper-V VM names to backup.
    If this option is not configured, all running VMs will be backed up.

    .PARAMETER L
    The path to output the log file to.
    The file name will be Hyper-V-Backup_YYYY-MM-dd_HH-mm-ss.log.
    Do not add a trailing \ backslash.

    .PARAMETER Wd
    The path to the working directory to use for the backup before copying it to the final backup directory.
    Use a directory on local fast media to improve performance.

    .PARAMETER NoPerms
    Configures the utility to shut down the running VM(s) to do the file-copy based backup instead of using the Hyper-V export function.
    If no list is specified and multiple VMs are running, the process will run through the VMs alphabetically.

    .PARAMETER Keep
    Instructs the utility to keep a specified number of days’ worth of backups.
    VM backups older than the number of days specified will be deleted.
    Every effort has been taken to only remove backup files or folders generated by this utility.

    .PARAMETER Compress
    This option will create a zip file of each Hyper-V VM backup.
    Available disk space should be considered when using this option.

    .PARAMETER Sz
    Configure the utility to use 7-Zip to compress the VM backups.
    7-Zip must be installed in the default location ($env:ProgramFiles) if it is not found, Windows compression will be used as a fallback.

    .PARAMETER NoBanner
    Use this option to hide the ASCII art title in the console.

    .PARAMETER Subject
    The subject line for the e-mail log. Encapsulate with single or double quotes.
    If no subject is specified, the default of "Hyper-V Backup Utility Log" will be used.

    .PARAMETER SendTo
    The e-mail address the log should be sent to.

    .PARAMETER From
    The e-mail address the log should be sent from.

    .PARAMETER Smtp
    The DNS name or IP address of the SMTP server.

    .PARAMETER User
    The user account to authenticate to the SMTP server.

    .PARAMETER Pwd
    The txt file containing the encrypted password for SMTP authentication.

    .PARAMETER UseSsl
    Configures the utility to connect to the SMTP server using SSL.

    .EXAMPLE
    Hyper-V-Backup.ps1 -BackupTo \\nas\vms -List C:\scripts\vms.txt -Wd E:\temp -NoPerms -Keep 30
    -Compress -Sz -L C:\scripts\logs -Subject 'Server: Hyper-V Backup' -SendTo me@contoso.com
    -From hyperv@contoso.com -Smtp smtp.outlook.com -User user -Pwd C:\foo\pwd.txt -UseSsl

    This will shutdown, one at a time, all the VMs listed in the file located in C:\scripts\vms.txt
    and back up their files to \\nas\vms, using E:\temp as a working directory. A zip file for each
    VM folder will be created, and the folder will be deleted. Any backups older than 30 days will
    also be deleted. The log file will be output to C:\scripts\logs and sent via e-mail with a
    custom subject line.
    #>

    ## Set up command line switches.
    [CmdletBinding()]
    Param(
    [parameter(Mandatory=$True)]
    [alias("BackupTo")]
    $Backup,
    [alias("Keep")]
    $History,
    [alias("List")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $VmList,
    [alias("Wd")]
    [ValidateScript({Test-Path $_ -PathType 'Container'})]
    $WorkDir,
    [alias("L")]
    [ValidateScript({Test-Path $_ -PathType 'Container'})]
    $LogPath,
    [alias("Subject")]
    $MailSubject,
    [alias("SendTo")]
    $MailTo,
    [alias("From")]
    $MailFrom,
    [alias("Smtp")]
    $SmtpServer,
    [alias("User")]
    $SmtpUser,
    [alias("Pwd")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $SmtpPwd,
    [switch]$UseSsl,
    [switch]$NoPerms,
    [switch]$Compress,
    [switch]$Sz,
    [switch]$NoBanner)

    If ($NoBanner -eq $False)
    {
    Write-Host ""
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " _ _ __ __ ____ _ _ _ _ _ _ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | | | | \ \ / / | _ \ | | | | | | | (_) (_) | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | |__| |_ _ _ __ ___ _ _\ \ / / | |_) | __ _ ___| | ___ _ _ __ | | | | |_ _| |_| |_ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | __ | | | | '_ \ / _ \ '__\ \/ / | _ < / _ |/ __| |/ / | | | '_ \ | | | | __| | | | __| | | | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | | | | |_| | |_) | __/ | \ / | |_) | (_| | (__| <| |_| | |_) | | |__| | |_| | | | |_| |_| | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " |_| |_|\__, | .__/ \___|_| \/ |____/ \__,_|\___|_|\_\\__,_| .__/ \____/ \__|_|_|_|\__|\__, | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " __/ | | | | __/ | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " |___/|_| |_| |___/ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " "
    Write-Host ""
    }

    ## If logging is configured, start logging.
    ## If the log file already exists, clear it.
    If ($LogPath)
    {
    $LogFile = ("Hyper-V-Backup_{0:yyyy-MM-dd_HH-mm-ss}.log" -f (Get-Date))
    $Log = "$LogPath\$LogFile"

    $LogT = Test-Path -Path $Log

    If ($LogT)
    {
    Clear-Content -Path $Log
    }

    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log started"
    }

    ## Function to get date in specific format.
    Function Get-DateFormat
    {
    Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    }

    ## Function for logging.
    Function Write-Log($Type, $Event)
    {
    If ($Type -eq "Info")
    {
    If ($Null -ne $LogPath)
    {
    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [INFO] $Event"
    }

    Write-Host "$(Get-DateFormat) [INFO] $Event"
    }

    If ($Type -eq "Succ")
    {
    If ($Null -ne $LogPath)
    {
    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [SUCCESS] $Event"
    }

    Write-Host -ForegroundColor Green "$(Get-DateFormat) [SUCCESS] $Event"
    }

    If ($Type -eq "Err")
    {
    If ($Null -ne $LogPath)
    {
    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [ERROR] $Event"
    }

    Write-Host -ForegroundColor Red -BackgroundColor Black "$(Get-DateFormat) [ERROR] $Event"
    }

    If ($Type -eq "Conf")
    {
    If ($Null -ne $LogPath)
    {
    Add-Content -Path $Log -Encoding ASCII -Value "$Event"
    }

    Write-Host -ForegroundColor Cyan -Object "$Event"
    }
    }

    ## Function for the options post backup.
    Function OptionsRun
    {
    ## If the -keep switch AND the -compress switch are NOT configured.
    If ($Null -eq $History -And $Compress -eq $False)
    {
    ## Remove all previous backup folders, including ones from previous versions of this script.
    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-***-*-*" -Directory | Remove-Item -Recurse -Force

    ## If a working directory is configured by the user, remove all previous backup folders, including
    ## ones from previous versions of this script.
    If ($WorkDir -ne $Backup)
    {
    Get-ChildItem -Path $Backup -Filter "$Vm-*-*-***-*-*" -Directory | Remove-Item -Recurse -Force
    }

    Write-Log -Type Info -Event "Removing previous backups of $Vm"
    }

    ## If the -keep option IS configured AND the -compress option is NOT configured.
    else {
    If ($Compress -eq $False)
    {
    ## Remove previous backup folders older than the configured number of days, including
    ## ones from previous versions of this script.
    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-***-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force

    ## If a working directory is configured by the user, remove previous backup folders
    ## older than the configured number of days remove all previous backup folders,
    ## including ones from previous versions of this script.
    If ($WorkDir -ne $Backup)
    {
    Get-ChildItem -Path $Backup -Filter "$Vm-*-*-***-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
    }

    Write-Log -Type Info -Event "Removing backup folders older than: $History days"
    }
    }

    ## Check to see if the -compress switch IS configured AND if the -keep switch is NOT configured.
    If ($Compress)
    {
    If ($Null -eq $History)
    {
    ## Remove all previous compressed backups, including ones from previous versions of this script.
    Remove-Item "$WorkDir\$Vm-*-*-***-*-*.zip" -Force

    ## If a working directory is configured by the user, remove all previous compressed backups,
    ## including ones from previous versions of this script.
    If ($WorkDir -ne $Backup)
    {
    Remove-Item "$Backup\$Vm-*-*-***-*-*.zip" -Force
    }

    Write-Log -Type Info -Event "Removing previous compressed backups"
    }

    ## If the -compress switch IS configured AND if the -keep switch IS configured.
    else {

    ## Remove previous compressed backups older than the configured number of days, including
    ## ones from previous versions of this script.
    Get-ChildItem -Path "$WorkDir\$Vm-*-*-***-*-*.zip" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Force

    ## If a working directory is configured by the user, remove previous compressed backups older
    ## than the configured number of days, including ones from previous versions of this script.
    If ($WorkDir -ne $Backup)
    {
    Get-ChildItem -Path "$Backup\$Vm-*-*-***-*-*.zip" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Force
    }

    Write-Log -Type Info -Event "Removing compressed backups older than: $History days"
    }

    ## If the -compress switch and the -Sz switch IS configured, test for 7zip being installed.
    ## If it is, compress the backup folder, if it is not use Windows compression.
    If ($Sz -eq $True)
    {
    $7zT = Test-Path "$env:programfiles\7-Zip\7z.exe"
    If ($7zT -eq $True)
    {
    Write-Log -Type Info -Event "Compressing using 7-Zip compression"
    & "$env:programfiles\7-Zip\7z.exe" -bso0 a -tzip ("$WorkDir\$Vm-{0:yyyy-MM-dd_HH-mm-ss}.zip" -f (Get-Date)) "$WorkDir\$Vm\*"
    }

    else {
    Write-Log -Type Info -Event "Compressing using Windows compression"
    Add-Type -AssemblyName "system.io.compression.filesystem"
    [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$Vm-{0:yyyy-MM-dd_HH-mm-ss}.zip" -f (Get-Date)))
    }
    }

    ## If the -compress switch IS configured and the -Sz switch is NOT configured, compress
    ## the backup folder using Windows compression.
    else {
    Write-Log -Type Info -Event "Compressing using Windows compression"
    Add-Type -AssemblyName "system.io.compression.filesystem"
    [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$Vm-{0:yyyy-MM-dd_HH-mm-ss}.zip" -f (Get-Date)))
    }

    ## Test if the compressed file was created.
    $VmZipT = Test-Path "$WorkDir\$Vm-*-*-***-*-*.zip"
    If ($VmZipT -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully created compressed backup of $Vm in $WorkDir"
    }

    else {
    Write-Log -Type Err -Event "There was a problem creating a compressed backup of $Vm in $WorkDir"
    }
    ## End of testing for file creation.

    ## Remove the VMs export folder.
    Get-ChildItem -Path $WorkDir -Filter "$Vm" -Directory | Remove-Item -Recurse -Force

    ## If a working directory has been configured by the user, move the compressed
    ## backup to the backup location and rename to include the date.
    If ($WorkDir -ne $Backup)
    {
    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-*-*-*.zip" | Move-Item -Destination $Backup

    ## Test if the move suceeded.
    $VmMoveT = Test-Path "$Backup\$Vm-*-*-*-*-*.zip"
    If ($VmMoveT -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully moved compressed backup of $Vm to $Backup"
    }

    else {
    Write-Log -Type Err -Event "There was a problem moving compressed backup of $Vm to $Backup"
    }
    ## End of testing for move.
    }
    }

    ## If the -compress switch is NOT configured AND if the -keep switch is NOT configured, rename
    ## the export of each VM to include the date.
    else {
    Get-ChildItem -Path $WorkDir -Filter $Vm -Directory | Rename-Item -NewName ("$WorkDir\$Vm-{0:yyyy-MM-dd_HH-mm-ss}" -f (Get-Date))

    If ($WorkDir -ne $Backup)
    {
    Get-ChildItem -Path $WorkDir -Filter "$Vm-*-*-***-*-*" -Directory | Move-Item -Destination ("$Backup\$Vm-{0:yyyy-MM-dd_HH-mm-ss}" -f (Get-Date))

    ## Test if the move suceeded.
    $VmMoveT = Test-Path "$Backup\$Vm-*-*-***-*-*"
    If ($VmMoveT -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully moved export of $Vm to $Backup"
    }

    else {
    Write-Log -Type Err -Event "There was a problem moving export of $Vm to $Backup"
    }

    ## End of testing.
    }
    }
    }

    ## Set a variable for computer name of the Hyper-V server.
    $Vs = $Env:ComputerName

    ## If a VM list file is configured, get the content of the file.
    ## If a VM list file is not configured, just get the running VMs.
    If ($VmList)
    {
    $Vms = Get-Content $VmList
    }

    else {
    $Vms = Get-VM | Where-Object {$_.State -eq 'Running'} | Select-Object -ExpandProperty Name
    }

    ## Check to see if there are any running VMs.
    ## If there are no VMs, then do nothing.
    If ($Vms.count -ne 0)
    {
    ## If the user has not configured the working directory, set it as the backup directory.
    If ($Null -eq $WorkDir)
    {
    $WorkDir = "$Backup"
    }

    ##
    ## Display the current config and log if configured.
    ##
    Write-Log -Type Conf -Event "************ Running with the following config *************."
    Write-Log -Type Conf -Event "This virtual host is:..$Vs."
    Write-Log -Type Conf -Event "VMs to backup:........."

    ForEach ($Vm in $Vms)
    {
    Write-Log -Type Conf -Event ".......................$Vm"
    }

    Write-Log -Type Conf -Event "Backup directory is:...$Backup."
    Write-Log -Type Conf -Event "Working directory is:..$WorkDir."

    If ($Null -ne $History)
    {
    Write-Log -Type Conf -Event "Backups to keep:.......$History days"
    }

    else {
    Write-Log -Type Conf -Event "Backups to keep:.......No Config"
    }

    If ($Null -ne $LogPath)
    {
    Write-Log -Type Conf -Event "Logs directory:........$LogPath."
    }

    else {
    Write-Log -Type Conf -Event "Logs directory:........No Config"
    }

    If ($MailTo)
    {
    Write-Log -Type Conf -Event "E-mail log to:.........$MailTo."
    }

    else {
    Write-Log -Type Conf -Event "E-mail log to:.........No Config"
    }

    If ($MailFrom)
    {
    Write-Log -Type Conf -Event "E-mail log from:.......$MailFrom."
    }

    else {
    Write-Log -Type Conf -Event "E-mail log from:.......No Config"
    }

    If ($MailSubject)
    {
    Write-Log -Type Conf -Event "E-mail subject:........$MailSubject."
    }

    else {
    Write-Log -Type Conf -Event "E-mail subject:........Default"
    }

    If ($SmtpServer)
    {
    Write-Log -Type Conf -Event "SMTP server is:........$SmtpServer."
    }

    else {
    Write-Log -Type Conf -Event "SMTP server is:........No Config"
    }

    If ($SmtpUser)
    {
    Write-Log -Type Conf -Event "SMTP user is:..........$SmtpUser."
    }

    else {
    Write-Log -Type Conf -Event "SMTP user is:..........No Config"
    }

    If ($SmtpPwd)
    {
    Write-Log -Type Conf -Event "SMTP pwd file:.........$SmtpPwd."
    }

    else {
    Write-Log -Type Conf -Event "SMTP pwd file:.........No Config"
    }

    Write-Log -Type Conf -Event "-UseSSL switch is:.....$UseSsl."
    Write-Log -Type Conf -Event "-NoPerms switch is:....$NoPerms."
    Write-Log -Type Conf -Event "-Compress switch is:...$Compress."
    Write-Log -Type Conf -Event "-Sz switch is:.........$Sz."
    Write-Log -Type Conf -Event "************************************************************"
    Write-Log -Type Info -Event "Process started."
    ##
    ## Display current config ends here.
    ##

    ##
    ## -NoPerms process starts here.
    ##

    ## If the -noperms switch is set, start a custom process to copy all the VM data.
    If ($NoPerms)
    {
    ForEach ($Vm in $Vms)
    {
    $VmInfo = Get-VM -name $Vm

    ## Test for the existence of a previous VM export. If it exists, delete it.
    $VmExportBackupTest = Test-Path "$WorkDir\$Vm"
    If ($VmExportBackupTest -eq $True)
    {
    Remove-Item "$WorkDir\$Vm" -Recurse -Force
    }

    ## Create directories for the VM export.
    New-Item "$WorkDir\$Vm" -ItemType Directory -Force | Out-Null
    New-Item "$WorkDir\$Vm\Virtual Machines" -ItemType Directory -Force | Out-Null
    New-Item "$WorkDir\$Vm\VHD" -ItemType Directory -Force | Out-Null
    New-Item "$WorkDir\$Vm\Snapshots" -ItemType Directory -Force | Out-Null

    ##
    ## Test for the creation of backup folders. If they created sucessfully, report it. If they didn't, also report it.
    ##

    $VmFolderTest = Test-Path "$WorkDir\$Vm\Virtual Machines"
    If ($VmFolderTest -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully created backup folder $WorkDir\$Vm\Virtual Machines"
    }

    else {
    Write-Log -Type Err -Event "There was a problem creating folder $WorkDir\$Vm\Virtual Machines"
    }

    $VmVHDTest = Test-Path "$WorkDir\$Vm\VHD"
    If ($VmVHDTest -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully created backup folder $WorkDir\$Vm\VHD"
    }

    else {
    Write-Log -Type Err -Event "There was a problem creating folder $WorkDir\$Vm\VHD"
    }

    $VmSnapTest = Test-Path "$WorkDir\$Vm\Snapshots"
    If ($VmSnapTest -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully created backup folder $WorkDir\$Vm\Snapshots"
    }

    else {
    Write-Log -Type Err -Event "There was a problem creating folder $WorkDir\$Vm\Snapshots"
    }

    ##
    ## End of folder creation testing.
    ##

    Write-Log -Type Info -Event "Stopping VM: $Vm"
    Stop-VM $Vm

    ##
    ## Copy the VM config files and test for success or failure.
    ##

    Copy-Item "$($VmInfo.ConfigurationLocation)\Virtual Machines\$($VmInfo.id)" "$WorkDir\$Vm\Virtual Machines\" -Recurse -Force
    Copy-Item "$($VmInfo.ConfigurationLocation)\Virtual Machines\$($VmInfo.id).*" "$WorkDir\$Vm\Virtual Machines\" -Recurse -Force

    $VmConfigTest = Test-Path "$WorkDir\$Vm\Virtual Machines\*"
    If ($VmConfigTest -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully copied $Vm configuration to $WorkDir\$Vm\Virtual Machines"
    }

    else {
    Write-Log -Type Err -Event "There was a problem copying the configuration for $Vm"
    }

    ##
    ## End of VM config files.
    ##

    ##
    ## Copy the VHDs and test for success or failure.
    ##

    Copy-Item $VmInfo.HardDrives.Path -Destination "$WorkDir\$Vm\VHD\" -Recurse -Force

    $VmVHDCopyTest = Test-Path "$WorkDir\$Vm\VHD\*"
    If ($VmVHDCopyTest -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully copied $Vm VHDs to $WorkDir\$Vm\VHD"
    }

    else {
    Write-Log -Type Err -Event "There was a problem copying the VHDs for $Vm"
    }

    ##
    ## End of VHDs.
    ##

    ## Get the VM snapshots/checkpoints.
    $Snaps = Get-VMSnapshot $Vm

    ForEach ($Snap in $Snaps)
    {
    ##
    ## Copy the snapshot config files and test for success or failure.
    ##

    Copy-Item "$($VmInfo.ConfigurationLocation)\Snapshots\$($Snap.id)" "$WorkDir\$Vm\Snapshots\" -Recurse -Force
    Copy-Item "$($VmInfo.ConfigurationLocation)\Snapshots\$($Snap.id).*" "$WorkDir\$Vm\Snapshots\" -Recurse -Force

    $VmSnapCopyTest = Test-Path "$WorkDir\$Vm\Snapshots\*"
    If ($VmSnapCopyTest -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully copied checkpoint configuration for $WorkDir\$Vm\Snapshots"
    }

    else {
    Write-Log -Type Err -Event "There was a problem copying the checkpoint configuration for $Vm"
    }

    ##
    ## End of snapshot config.
    ##

    ## Copy the snapshot root VHD.
    Copy-Item $Snap.HardDrives.Path -Destination "$WorkDir\$Vm\VHD\" -Recurse -Force
    Write-Log -Type Succ -Event "Successfully copied checkpoint VHDs for $Vm to $WorkDir\$Vm\VHD"
    }

    Start-VM $Vm
    Write-Log -Type Info -Event "Starting VM: $Vm"
    Start-Sleep -S 60
    OptionsRun
    }
    }

    ##
    ## -NoPerms process ends here.
    ##
    ##
    ##
    ## Standard export process starts here.
    ##

    ## If the -NoPerms switch is NOT set, for each VM check for the existence of a previous export.
    ## If it exists then delete it, otherwise the export will fail.
    else {
    ForEach ($Vm in $Vms)
    {
    $VmExportBackupTest = Test-Path "$WorkDir\$Vm"
    If ($VmExportBackupTest -eq $True)
    {
    Remove-Item "$WorkDir\$Vm" -Recurse -Force
    }

    If ($WorkDir -ne $Backup)
    {
    $VmExportWDT = Test-Path "$Backup\$Vm"
    If ($VmExportWDT -eq $True)
    {
    Remove-Item "$Backup\$Vm" -Recurse -Force
    }
    }
    }

    ## Do a regular export of the VMs.
    $Vms | Export-VM -Path "$WorkDir"

    ## Test if the export suceeded.
    $VmExportTest = Test-Path "$WorkDir\*"
    If ($VmExportTest -eq $True)
    {
    Write-Log -Type Succ -Event "Successfully exported specified VMs to $WorkDir"
    }

    else {
    Write-Log -Type Err -Event "There was a problem exporting the specified VMs to $WorkDir"
    }

    ## Run the configuration options on the above backup files and folders.
    ForEach ($Vm in $Vms)
    {
    OptionsRun
    }
    }
    }

    ## If there are no VMs running, then do nothing.
    else {
    Write-Log -Type Info -Event "There are no VMs running to backup"
    }

    Write-Log -Type Info -Event "Process finished."

    ## If logging is configured then finish the log file.
    If ($LogPath)
    {
    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log finished"

    ## This whole block is for e-mail, if it is configured.
    If ($SmtpServer)
    {
    ## Default e-mail subject if none is configured.
    If ($Null -eq $MailSubject)
    {
    $MailSubject = "Hyper-V Backup Utility Log"
    }

    ## Setting the contents of the log to be the e-mail body.
    $MailBody = Get-Content -Path $Log | Out-String

    ## If an smtp password is configured, get the username and password together for authentication.
    ## If an smtp password is not provided then send the e-mail without authentication and obviously no SSL.
    If ($SmtpPwd)
    {
    $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString
    $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt)

    ## If -ssl switch is used, send the email with SSL.
    ## If it isn't then don't use SSL, but still authenticate with the credentials.
    If ($UseSsl)
    {
    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $SmtpCreds
    }

    else {
    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Credential $SmtpCreds
    }
    }

    else {
    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer
    }
    }
    }

    ## End

    • Open Power Shell Run As Admin and open script path location and run below command. 

    Hyper-V-Backup.ps1 -BackupTo \\nas\vms -List C:\Script\vmbackup.txt 

    AWS [Amazon Web Service]

    Amazon Web Services (AWS) is a comprehensive, evolving cloud computing platform provided by Amazon. It provides a mix of infrastructure as a service (IaaS), platform as a service (PaaS) and packaged software as a service (SaaS) offerings.

    AWS Global Infrastructure:

    • Compute [EC2]
    • Storage [S3]
    • Database [RDS]
    • Migration and Transfer [AWS Snow ball]
    • Network and content Delivery [VPC]
    • Security, Identity and Compliance [IAM]
    Region and Availability zone Difference:
    • AWS Global Infrastructure: 
    • Availability Zone = An availability may be several data centre but because they are close together they counter as 1 Availability Zone, 1 AZ = 1 DC
    • Region: A Region is a geographical area. Each region consists 2 or more Availability Zone
    • Edge Location: It is an endpoints for AWS which are used for cache content. Typically this consists of cloud front Amazon’s content Delivery Network. There are many more edge location than regions. 
    Compute EC2 [Elastic Compute Cloud]
    • Virtual computing environments, known as instances
    • Pre configured templates for your instances, known as Amazon Machine Images (AMIs), that package the bits you need for your server (including the operating system and additional software)
    • Various configurations of CPU, memory, storage, and networking capacity for your instances, known as instance types
    • Secure login information for your instances using key pairs (AWS stores the public key, and you store the private key in a secure place)
    • Storage volumes for temporary data that’s deleted when you stop or terminate your instance, known as instance store volumes
    • Persistent storage volumes for your data using Amazon Elastic Block Store (Amazon EBS), known as Amazon EBS volumes
    • Multiple physical locations for your resources, such as instances and Amazon EBS volumes, known as regions and Availability Zones
    • A firewall that enables you to specify the protocols, ports, and source IP ranges that can reach your instances using security groups
    • Static IPv4 addresses for dynamic cloud computing, known as Elastic IP addresses
    • Metadata, known as tags, that you can create and assign to your Amazon EC2 resources
    • Virtual networks you can create that are logically isolated from the rest of the AWS cloud, and that you can optionally connect to your own network, known as virtual private clouds (VPCs)
    • Four types of EC2 options. On demand, Reserved, Spot and Dedicated Hosts
    S3 [Simple Storage Service]
    • Global service 
    • Name is universal can not be duplicate
    • Upload to Object on bucket receive a HTTP 200 code
    • Three types of S3 storage S3, S3- Infrequent Access and S3 Redundancy storage
    • By default buckets are private and all object store inside them are private
    • Versioning can enable on bucket and it is backup tool it can’t remove but we can suspend it
    • Cross region replication: if you made any change or upload any file it will replicated but If you delete any file or version it will not replicate
    • Version must be enable in both bucket  for cross region replication
    • Lifecycle Management needs to enable on bucket to define old content to different s3 storage version.  Like after in activity for 30 days move to S3 to S3- IA 
    IAM [Identity and Authentication Management 
    • There are 2 users. One user is root and another normal user 
    • Root is user from where you have created account of AWS console.
    • Access key is your username and the secret key is your password. 
    • Normal user can access using Browser that is console 
    • Programmatic user access API and CLI 
    • There are 2 Keys Access and Secret Key
    • IAM Role
    • Centralized control of your AWS account 
    • Shared Access of your AWS account 
    • Granular Permissions 
    • Identity Federation [Incl. Active Directory, Facebook and linkedin]
    • Multifactor Authentication 
    • Provide temporary access for users/devices and services whew necessary
    • Allow you to setup your password rotation 
    • Integrates with many different AWS services
    • Support PCI DSS compliance

    Run Script in Screen Mode on Startup

    Description: Here I have explained, How to run script on Startup

    Procedure: 

    • Create one script as below which will run in screen mode

     #!/bin/sh
    screen -d -m -S SessionName /home/script/run.sh

    • To run script on startup open crontab and define schedule as follow.
     @reboot /bin/sh /home/script/run.sh 

    • After define in schedule restart crontab service and test by restart server.

    Backup Script for Zimbra with Rsync Over SSH

    Description: Here I have uploaded Backup script for Zimbra with Rsync Over SSH

    #!/bin/bash
    # Zimbra Backup Script
    # For Rsync need to configure password less ssh between two Server
    # https://systemadmintalk.blogspot.com/2016/10/password-less-ssh-connection-between.html
    # This script is intended to run from the crontab as root
    # Local Server Directory Path
    DESTLOCAL=/Backup/zimbra_backup
    
    # Remote Server Directory path
    DESTREMOTE="root@10.10.10.10:/home/Zimbra_Server_Backup"
    
    
    
    # Outputs the time the backup started, for log/tracking purposes
    echo Time backup started = $(date +%T)
    before="$(date +%s)"
    # a backup dir on the local machine. This will fill up over time!
    BACKUPDIR=$DESTLOCAL/$(date +%F-%H-%M-%S)
    
    # Now we need to shut down Zimbra to rsync any files that were/are locked
    # whilst backing up when the server was up and running.
    before2="$(date +%s)"
    
    # Stop Zimbra Services
    /etc/init.d/zimbra stop
    #su - zimbra -c"/opt/zimbra/bin/zmcontrol stop"
    #sleep 15
    # Kill any orphaned Zimbra processes
    #kill -9 `ps -u zimbra -o "pid="`
    pkill -9 -u zimbra
    
    
    # Only enable the following command if you need all Zimbra user owned
    # processes to be killed before syncing
    # ps auxww | awk '{print $1" "$2}' | grep zimbra | kill -9 `awk '{print $2}'`
    
    
    # Sync to backup directory
    rsync -avHK --delete --backup --backup-dir=$BACKUPDIR /opt/zimbra/ $DESTLOCAL/zimbra
    
    
    # Restart Zimbra Services
    #su - zimbra -c "/opt/zimbra/bin/zmcontrol start"
    /etc/init.d/zimbra start
    
    
    # Calculates and outputs amount of time the server was down for
    after="$(date +%s)"
    elapsed="$(expr $after - $before2)"
    hours=$(($elapsed / 3600))
    elapsed=$(($elapsed - $hours * 3600))
    minutes=$(($elapsed / 60))
    seconds=$(($elapsed - $minutes * 60))
    echo SERVER WAS DOWN FOR: "$hours hours $minutes minutes $seconds seconds"
    
    # Create a txt file in the backup directory that'll contains the current Zimbra
    # server version. Handy for knowing what version of Zimbra a backup can be restored to.
    # su - zimbra -c "zmcontrol -v > $DESTLOCAL/zimbra/conf/zimbra_version.txt"
    # or examine your /opt/zimbra/.install_history
    
    # Display Zimbra services status
    echo Displaying Zimbra services status...
    su - zimbra -c "/opt/zimbra/bin/zmcontrol status"
    
    # /etc/init.d/zimbra status # seems not to work
    
    # backup the backup dir (but not the backups of the backups) to remote
    
    rsync /opt/zimbra_backup/zimbra/*  -ave  "ssh -c arcfour -p 2255" --recursive --delete-during  root@10.10.10.10:/home/Zimbra_Server_Backup
    
    
    # Outputs the time the backup finished
    echo Time backup finished = $(date +%T)
    
    
    
    # Calculates and outputs total time taken
    
    after="$(date +%s)"
    elapsed="$(expr $after - $before)"
    hours=$(($elapsed / 3600))
    elapsed=$(($elapsed - $hours * 3600))
    minutes=$(($elapsed / 60))
    seconds=$(($elapsed - $minutes * 60))
    echo Time taken: "$hours hours $minutes minutes $seconds seconds" > /tmp/status.txt
    # end