Friday, December 7, 2012

Cisco GLBP( Gateway Load Balancing Protocol) config sample

Router 1(  R1 ) with WAN connection, Router 2 (R2) with WAN connection also. We want to setup router hardward redundancy and traffic load balancing with weight on the gateway.
Here is the example.

On R1.
track 1 ip route 0.0.0.0 0.0.0.0 reachability

interface FastEthernet0/0
 mac-address aaaa.aaaa.aaaa
 ip address 208.x.x.254 255.255.255.0
 glbp 100 ip 208.x.x.1
 glbp 100 preempt
 glbp 100 load-balancing weighted
 glbp 100 weighting 200
 glbp 100 weighting track 1 decrement 200


On R2.
track 1 ip route 0.0.0.0 0.0.0.0 reachability

interface FastEthernet0/0
 mac-address cccc.cccc.cccc
 ip address 208.x.x.253 255.255.255.0
 glbp 100 ip 208.x.x.1
 glbp 100 priority 90
 glbp 100 preempt
 glbp 100 load-balancing weighted
 glbp 100 weighting track 1 decrement 100


Monday, November 5, 2012

Backup Cisco Network Equipment Running Configuration through Telnet Automatically

1. Create routerlist.csv file like the following.

Name,IP,Group
TORR-MPLS,172.X.X.X,HQs
HQSWT_LAN-248,172.X.X.X,HQs
HQSWT02-2,172.X.X.X,HQs
HQ-Edge02,172.X.X.X,HQs
NY-Edge01,192.X.X.X,NY
NY-Edge02,192.X.X.X,NY
NJ-Edge01,192.X.X.X,NJ
NJ-Edge02,192.X.X.X,NJ


2. Place the tftpserver.exe program on the subfolder named tftpsrv.


3. Python Script.

'''
Created on Oct 18, 2012

@author: chu
Version 0.1
'''
import os, subprocess, telnetlib, time

print "*********************************************************************"
print "**    This program will backup Network Equipment configuration.    **"
print "**                                                  Version 0.1    **"
print "*********************************************************************"
print ""
#define functions
def makefolder (fdname):
    if not os.path.isdir(os.path.join(os.getcwdu(),'NetEqtConfig',fdname)):
        os.mkdir(os.path.join('NetEqtConfig',fdname))
     
def cp2tftp(hostip,hostname,user,password,tftpsrvip):
    tn = telnetlib.Telnet(hostip)
    tn.read_until("Username: ",10)
    tn.write(user+ "\n")
    tn.read_until("Password: ",10)
    tn.write(password + "\n")
    tn.read_until("#",10)
    tn.write("copy running-config tftp\n")
    tn.read_until("[]?",10)
    tn.write(tftpsrvip + "\n")
    tn.read_until("]?",10)
    tn.write(hostname + "\n")
    tn.read_until("#",10)
    tn.write("exit\n")
    tn.close()

#Read Network Equipment list
eqtlist = []
rfile = open('routerlist.csv','rb')
for line in rfile.readlines():
    tmplist = [s for s in line.rstrip().split(',')]
    eqtlist.append(tmplist)
rfile.close()

#Create Root Folder  
if not os.path.isdir('NetEqtConfig'):
    os.mkdir('NetEqtConfig')
                 
#Create Subfolders
for n in range(1, len(eqtlist)):
    makefolder(eqtlist[n][2])    
 
tftpsrvp = subprocess.Popen([os.path.join(os.getcwd(),'tftpsrv','tftpserver.exe')])
print "TFTP Server is running."

tftpsrvip = "ftfpserver ip address"
user = "routerloginusername"
password = "routerloginpassword"

#Telnet and backup configuration file
print "Downloading Configuration files. Please wait..."
print ""
#for n in range(1, len(eqtlist)):
for n in range(1, len(eqtlist)):
    hostname = eqtlist[n][0]
    hostip = eqtlist[n][1]
    try:
        cp2tftp(hostip,hostname,user,password,tftpsrvip)
        time.sleep(5)
        nfpath = os.path.join(r'.\NetEqtConfig',eqtlist[n][2],hostname+"-"+hostip)
        os.rename(hostname,nfpath)
    except:
        print "Failed to download configuration file from %s!" %hostname
        continue
 
time.sleep(3)
tftpsrvp.kill()
tftpsrvp.wait()
print ""
print "Download finished!"
print "TFTP Server is closed."
nfoldername = 'NetEqtConfig-' + time.strftime("%m%d%Y", time.gmtime())
os.rename('NetEqtConfig',nfoldername)
print ""
print "All network equipment configuration save on %s" %nfoldername

Use Selenium Automates Firefox to Download Reports from Website


#!c:/python27/python
#filename : GetPaetecReport.py
#Version 1.3

'''
Created on Oct 18, 2012
@author: chu
'''

import time, os, getpass, win32com.client
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select, WebDriverWait



def endprg():
    print ""
    raw_input ("Press Enter to close.")
 

 
#Download Reports
def getrept(accounts):
    id = raw_input("Login ID:")
    pw = getpass.getpass()
    filepath=os.path.join(os.getcwd(),'Paetec')
# Setup FirefoxProfile.
    fp = webdriver.FirefoxProfile()
    fp.set_preference("browser.download.folderList",2)
    fp.set_preference("browser.download.manager.showWhenStarting",False)
    fp.set_preference("browser.download.manager.closeWhenDone",True)
    fp.set_preference("browser.helperApps.alwaysAsk.force",False)
    fp.set_preference("browser.download.dir",filepath)
    fp.set_preference("browser.helperApps.neverAsk.saveToDisk","application/vnd.ms-excel")
# use Firefox to download reports
    print ""
    print "Downloading reports from wxxxstreamonline.com....."
    print ""
    driver = webdriver.Firefox(firefox_profile=fp)
    driver.get('https://www.wxxxstreamonline.com/pol/Home.action')
    time.sleep(2)
# Login to website
    driver.find_element_by_id("username").clear()
    driver.find_element_by_id("username").send_keys(id)
    driver.find_element_by_id("password").clear()
    driver.find_element_by_id("password").send_keys(pw)
    driver.find_element_by_id("submitButton").click()
    time.sleep(3)
    driver.find_element_by_link_text('View My Billing Reports').click()
    time.sleep(1)
# Get into different accounts
    for account in accounts:
        Select(driver.find_element_by_name("selectedCustomer")).select_by_visible_text(account)
        time.sleep(1)
        Select(driver.find_element_by_id("reportList")).select_by_visible_text("Usage Billed Outbound")
        driver.find_element_by_id("viewReport").click()
        time.sleep(15)
        for handle in driver.window_handles:
            driver.switch_to_window(handle)
            if driver.title == 'Wxxxstream Online' :
                break
        Select(driver.find_element_by_id("ReportViewer1_ctl01_ctl05_ctl00")).select_by_visible_text("Excel")
        driver.find_element_by_link_text('Export').click()
        time.sleep(10)
        while True:
            if len(driver.window_handles) > 2:
                time.sleep(5)
            else:
                break
        driver.close()
        driver.switch_to_window(driver.window_handles[0])
        time.sleep(8)
#rename downloaded file
        if os.path.exists(os.path.join(filepath,'Billed Usage.xls')):
            filename = account[-7:] + '.xls'
            os.rename(os.path.join(filepath,'Billed Usage.xls'), os.path.join(filepath,filename))
            time.sleep(2)
#Logout from Paeteconline.com      
    driver.find_element_by_partial_link_text('Logout').click()
    time.sleep(1)
    driver.close()



#Generate Excel Report
def genrept(accounts):
    xl=win32com.client.Dispatch('Excel.Application')
    xl.Visible=0
    filepath=os.path.join(os.getcwd(),'Paetec')
    reportname = time.strftime("%Y%m") + "01"
#Copy sheets
    i=1
    for account in accounts:
        filename=os.path.join(filepath,(account[-7:]+'.xls'))
        if account[-7:] == '4xxxx91':
            wb=xl.Workbooks.Open(filename)
            sh=wb.Worksheets(i)
            sh.Name=account[-7:]
        else:
            wbt=xl.Workbooks.Open(filename)
            sht=wbt.Worksheets(1)
            sht.Copy (None,wb.Worksheets(i-1))
            wbt.Close()
            sh=wb.Worksheets(i)
            sh.Name=account[-7:]
        i+=1
    shnew=wb.Worksheets.Add(None,wb.Worksheets(i-1))
    shnew.Name=reportname
#Copy Cells
    for i in range(1,wb.Worksheets.Count):
        sh=wb.Worksheets(i)
        if i==1:
            startrow=5
        else:
            startrow=6
        sh.Range(sh.Cells(startrow,1),sh.Cells(sh.UsedRange.Rows.Count,sh.UsedRange.Columns.Count)).Copy()
        shnew.Paste(shnew.Cells(shnew.UsedRange.Rows.Count+startrow-5,1))
#Adjust new sheet
    shnew.Columns("D:D").Delete()
    shnew.UsedRange.WrapText=False
    shnew.Columns("A:I").AutoFit()
    shnew.Sort.SortFields.Clear()
    shnew.Range(shnew.Cells(2,1),shnew.Cells(shnew.UsedRange.Rows.Count,shnew.UsedRange.Columns.Count)).Sort(Key1=shnew.Range("A2"), Order1=1, Key2=shnew.Range("F2"), Order2=1,Key3=shnew.Range("C2"), Order3=1)
    newreportpath = os.path.join(filepath,(reportname+'.xls'))
    wb.SaveAs(newreportpath)
    wb.Close()
    xl.Application.Quit()
#Print to console
    print ""
    print "New report is saved on %s." %newreportpath
    print ""


print "*******************************************************************"
print "**    This program will download the last month                  **"
print "**    Usage Billed Outbound reports from wxxxxstreamonline.com    **"
print "**    And will generate a new Excel Report.                      **"
print "**                                                Version 1.3    **"
print "*******************************************************************"
print ""

accounts = ["Mxxx - 4xxxx91", "Mxxx - Hoboken, NJ - 4xxxx36", "Mxxx - Kent, WA - 4xxxx11","Mxxx - NY, NY - 4xxxx34"]
goodtogo = 'yes'

try:
    getrept(accounts)
except:
    print "Failed to download reports from wxxxstreamonline.com."
    goodtogo = "no"

if goodtogo == 'yes':
    try:
        genrept(accounts)
    except:
        print "Failed to generate new excel reports."

endprg()

Tuesday, July 17, 2012

Using Python Script to Copy and Merge Excel sheets


Copy C:\temp\Billed\4540991.xls,4563011.xls,4563034.xls,4563036.xls into temp.xls. 
Create a New Sheet named 20120901. Merge all the Other 4 sheets into One. Sort the data.

'''
Created on Jul 12, 2012

@author: Victor
'''
import win32com.client
xl=win32com.client.Dispatch('Excel.Application')
xl.Visible=0

'''Copy sheets'''
filepath='C:\\temp\\Billed\\'
i=1
for file in ['4540991','4563011','4563034','4563036']:
    filename=filepath+file+'.xls'
    if i==1:
        wb=xl.Workbooks.Open("C:\\temp\\Billed\\4540991.xls")
        sh=wb.Worksheets(i)
        sh.Name=file
    else:
        wbt=xl.Workbooks.Open(filename)
        sht=wbt.Worksheets(1)
        sht.Copy (None,wb.Worksheets(i-1))
        wbt.Close()
        sh=wb.Worksheets(i)
        sh.Name=file
    i+=1

shnew=wb.Worksheets.Add(None,wb.Worksheets(i-1))
shnew.Name="20120901"

'''Copy Cells'''
for i in range(1,wb.Worksheets.Count):
    sh=wb.Worksheets(i)
    if i==1:
        startrow=5
    else:
        startrow=6
    sh.Range(sh.Cells(startrow,1),sh.Cells(sh.UsedRange.Rows.Count,sh.UsedRange.Columns.Count)).Copy()
    shnew.Paste(shnew.Cells(shnew.UsedRange.Rows.Count+startrow-5,1))

#shnew.Columns("D:D").Delete()
shnew.UsedRange.WrapText=False
shnew.Columns("A:I").AutoFit()
shnew.Sort.SortFields.Clear()
shnew.Range(shnew.Cells(2,1),shnew.Cells(shnew.UsedRange.Rows.Count,shnew.UsedRange.Columns.Count)).Sort(Key1=shnew.Range("A2"), Order1=1, Key2=shnew.Range("F2"), Order2=1,Key3=shnew.Range("C2"), Order3=1)

wb.SaveAs('C:\\temp\\Billed\\temp.xls')
wb.Close()
xl.Application.Quit()

Tuesday, April 24, 2012

Installation of Dionaea on Ubuntu


1.Set up the repository and install dionaea:
sudo add-apt-repository ppa:honeynet/nightly
sudo apt-get update
sudo apt-get install dionaea



2.Set up directory:
sudo mkdir -p /var/dionaea/wwwroot
sudo mkdir -p /var/dionaea/binaries
sudo mkdir -p /var/dionaea/log
sudo chown -R nobody:nogroup /var/dionaea/



3.Edit config file:
sudo mv /etc/dionaea/dionaea.conf.dist /etc/dionaea/dionaea.conf
sudo sed -i 's/var\/dionaea\///g' /etc/dionaea/dionaea.conf
sudo sed -i 's/log\//\/var\/dionaea\/log\//g' /etc/dionaea/dionaea.conf

4. Create a Dionaea in \etc\init.d:
sudo vi /etc/init.d/dionaea
add the following to the file.

#!/bin/sh
dionaea -c /etc/dionaea/dionaea.conf -w /var/dionaea -u nobody -g nogroup -D


5. Add execute permission to file:
sudo chmod +x /etc/init.d/dionaea



6. Set up dionaes as the startup service:
sudo update-rc.d dionaea defaults



7. Launch dionaea manually at the first time:
sudo /etc/init.d/dionaea
8. Check established connection log:
grep established /var/dionaea/log/dionaea.log | grep connection

Monday, April 23, 2012

Allow Anonymous Relay on an Exchange 2010 Receive Connector

1. Create a New Receive Connector
New-ReceiveConnector -Name "Anonymous Relay" -Usage Custom -PermissionGroups AnonymousUsers -Bindings 10.2.x.xx:25 -RemoteIpRanges 192.168.x.xx 

2. Grant Relay Permission to Anonymous Connections

Get-ReceiveConnector "Anonymous Relay" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "Ms-Exch-SMTP-Accept-Any-Recipient"

Monday, April 16, 2012

PowerShell Script for Monitor SMTP Servers

1. Create a serverstatus.csv file like the following, to list all the SMTP servers that you need to monitor.
 #TYPE System.Management.Automation.PSCustomObject
"Name","IP","LastStatus","CurrentStatus","Updatetime"
"MKxxMX01","208.x.x.x","SUCCESS","SUCCESS","4/16/2012 10:24 AM"
"MKxxMX02","71.x.x.x","SUCCESS","SUCCESS","4/16/2012 10:24 AM"
"MKxxMAL03","192.168.10.x","SUCCESS","SUCCESS","4/16/2012 10:24 AM"
"MKxxMAL04","192.168.10.x","SUCCESS","SUCCESS","4/16/2012 10:24 AM"
"MKxxMAL01","192.168.40.x","SUCCESS","SUCCESS","4/16/2012 10:24 AM"

2.Create a count.txt. Type 0 inside the file.  If it gets errors, it sends our alert, very 15 minutes. If it keeps getting more than 4 errors, it will send out the alert every 1 hour. 
0

3.Create InfoRecipients.txt. List the mail address who will receive the alter.
6264x63xxx@tmomail.net,ts@xxxxxxxx.com,xxxx.techsupport@gmail.com

4.PowerShell Script.
##########################################################
##        Send mail to test the mail server!!           ##
##########################################################
$ErrorActionPreference = "silentlycontinue"
#$ErrorActionPreference = "continue"
[Int]$Count= Get-Content -Path count.txt
$CurrentStatus = "SUCCESS"
$Serverlist = Import-Csv serverstatus.csv
$emailFrom = "SMTPtest@xxxamericaxx.com"
$emailTo = Get-Content -Path testaddress.txt
$subject = "Mail test from Chicago every 15 minutes"
$body = "Mail test from Chicago DataCenter."

foreach ( $Server in $Serverlist)
{
$Server.LASTSTATUS=$Server.CURRENTSTATUS
$smtpServer= $Server.IP
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
$TestStatus=$?
if ($TestStatus)
{
$Server.CurrentStatus= "SUCCESS"
}
ELSE
{
$Server.CURRENTSTATUS= "FAILURE"
$CurrentStatus = "FAILURE"
    }
$Server.UPDATETIME = Get-Date -Format g
}

$Serverlist | Export-Csv serverstatus.csv
If ($CurrentStatus -eq "SUCCESS")
{
$count = 0
}
Else
{
$count += 1
}
Set-Content -Path count.txt -Value $Count
$Modulo = $count % 4
#####################################################
###              Send out SMS!!                   ###
#####################################################
$body=""
$Needtosend="False"
foreach ( $Server in $Serverlist)
{
if (($Server.LastStatus -eq "FAILURE") -or ($Server.CurrentStatus -eq "FAILURE"))
{
$Needtosend="True"
$body=$body+$server.Name+","+$Server.CurrentStatus+","+$server.Updatetime+".  "
}
}
If (($Needtosend -eq "True") -and (($Count -le 1) -or ($Modulo -eq 2 )))
{
$emailTo = get-content -path InfoRecipients.txt
$subject = "Mail Server testing Alert."
$smtpServer = "smtpserver.xxxamericaxx.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
    Set-Content -Path LastResult.txt -Value $body
}

Wednesday, April 11, 2012

WMWare Server 2.0 Restart Guest Dos Script


@echo off

REM power off VM.
vmrun -T server -h https://127.0.0.1:8333/sdk -u vmusername -p Password stop "[standard] GuestVMName\GuestVMName.vmx" soft

REM detect vm is off or not.
:while

vmrun -T server -h https://127.0.0.1:8333/sdk -u vmusername -p Password list | FINDSTR /C:"GuestVMName.vmx"
IF %ERRORLEVEL% EQU 0 (
PING 127.0.0.1 -n 60
GOTO while
) ELSE (
PING 127.0.0.1 -n 15
vmrun -T server -h https://127.0.0.1:8333/sdk -u vmusername -p Password start "[standard] GuestVMName\GuestVMName.vmx"
        PING 127.0.0.1 -n 15
EXIT
)

Tuesday, April 10, 2012

VMWare 2.0 Guest switches


Add the following Switches on the  *.VMX file can improve the Guest OS performance 


sched.mem.pshare.enable = "FALSE"
mainMem.useNamedFile = "FALSE"
prefvmx.minVmMemPct = "100"

MemAllowAutoScaleDown = "FALSE"
MemTrimRate = "0"


Disable the TCP Offload Engine features in the driver on the host to improve guest network performance.
Disable the TCP Offload Engine features on the host:
Go to
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
  1. Create a key named DisableTaskOffload, of type DWORD.
  2. Set the value of the key to 1 .
  3. Close the Registry Editor and restart the computer.

Monday, April 9, 2012

Java Script for LAN Web Proxy Setting

1. Create Java Script.
FileName: wpad.pac
Java Script Content for Wpad.pac

function FindProxyForURL(url, host)
{
  if  (
 (isPlainHostName(host)) ||
 (dnsDomainIs(host,".xxxxxxx.com")) ||
 (dnsDomainIs(host,".aesdirect.gov")) ||
 (dnsDomainIs(host,".adobe.com")) ||
 (dnsDomainIs(host,".symantec.com")) ||
 (dnsDomainIs(host,".symantecliveupdate.com")) ||
 (dnsDomainIs(host,".windowsupdate.com")) ||
 (dnsDomainIs(host,".microsoft.com")) ||
 (dnsDomainIs(host,".smartxxxxx.com")) ||
 (dnsDomainIs(host,".citigroup.com")) ||
 (dnsDomainIs(host,".citibank.com")) ||
 (isInNet(host,"192.168.0.0","255.255.0.0")) ||
 (isInNet(host,"208.xx.xx.0","255.255.255.0")) ||
 (isInNet(host,"127.0.0.1","255.255.255.255")) ||
 (isInNet(host,"172.28.1.0","255.255.255.0")) ||
 (isInNet(host,"172.29.1.0","255.255.255.0")) ||
 (isInNet(host,"172.16.52.0","255.255.255.0"))
 )
 return "DIRECT";
  else return "PROXY proxyservername.xxxxx.com:port#; DIRECT";
}





2. Put the wpad.pac on webserver. 
   The url is http://webservername/wpad.pac





3. Configure AD Group Policy to Apply the proxy setting.
   Go to User Configuration---Windows Settings---Internet Explorer Maintenance---Connection---Automatic Browser Configuration---(1.Enable Automatic Configuration. 2. enter the Automatic proxy URL.).
    Please see the following picture.