Friday, November 15, 2013

C# Program web based password try.

Scenario: I just work for a new company. I want to get into some network switch and check the configuration to draw the network diagram and backup the switch configuration. But nobody knows the password in our IT team, and no document mention that. It is bad. :(.
I can reset the switches, but we will lost the configuration. And nobody know what is the current switch setting. The switch provide web console. So I use the C#, Selenium, Chrome web driver, and the password dictionary file to find out the password.

Here is the C# code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
using System.Threading;
using System.IO;
namespace myFirstSelenium
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "PwDict.txt";
            string url = "http://192.168.1.20/";
            string userName = "admin";
            string password = "";
            string returnValue = "";
            StreamReader fileReader = new StreamReader(filePath);
            try
            {
                password = fileReader.ReadLine();
               
                while (password != null)
                {
                    Console.WriteLine();
                    Console.WriteLine("Trying {0} with username: {1} and password: {2}...",url,userName,password);
                    returnValue = Web.Access(url, userName, password);
                    if (returnValue == "Sucessfull")
                    {
                        break;
                    }
                    password = fileReader.ReadLine();
                }

                if (password == null)
                {
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("***Can not find any password!****");
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("***Congratulation***");
                    Console.WriteLine("We found username: {0} ,and password: {1} for {2}!", userName, password, url);
                }
            }
            finally
            {
                fileReader.Close();
            }
        }

       
    }

    class Web
    {
        #region Access Web Site
        public static string Access (string url, string loginname, string password)
        {
            ChromeOptions options = new ChromeOptions();
            //ChromeOptions options = new ChromeOptions();
            options.AddArguments("--no-proxy-server");
            ChromeDriverService service = ChromeDriverService.CreateDefaultService();
            service.SuppressInitialDiagnosticInformation = true;
         
           
            IWebDriver driver = new ChromeDriver(service, options);
           
            //driver.Navigate().GoToUrl("http://192.168.1.20/");
            driver.Navigate().GoToUrl(url);
            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(10));

            while (true)
            {
                try
                {
                    driver.SwitchTo().Frame("main");
                    break;
                }
                catch (Exception)
                {
                    int milliseconds = 1000;
                    Thread.Sleep(milliseconds);
                }
            }

            while (true)
            {
                try
                {
                    driver.FindElement(By.Name("Password")).Clear();
                    break;
                }
                catch (Exception)
                {
                    int milliseconds = 1000;
                    Thread.Sleep(milliseconds);
                }
            }

            //driver.SwitchTo().Frame("main");
            driver.FindElement(By.Name("Username")).Clear();
            driver.FindElement(By.Name("Username")).SendKeys(loginname);
            driver.FindElement(By.Name("Password")).Clear();
            driver.FindElement(By.Name("Password")).SendKeys(password);
            driver.FindElement(By.LinkText("OK")).Click();
           
            string page = driver.PageSource;

            if (page.Contains("<title>Error</title>"))
            {
                driver.Close();
                return "Failed";
            }
            else
            {
                return "Sucessfull";
            }
           
        }
        #endregion
    }
}

Wednesday, August 14, 2013

Improve iSCSI Performance

This article copy from http://blogs.microsoft.co.il/blogs/yuval14/archive/2011/07/15/how-to-improve-iscsi-performance.aspx
If you want to know more detail, please go the above link to see.

The following post cover a few tips and tricks that can improve you iSCSI performance.

General
1. Use the latest Microsoft operating System.
2. Update the current ISCSI initiator to the latest version.
3. If it applicable, use a HBA (Host Bus Adapter) with iSCSI accelerator.
4. In some scenarios, you may need to use the latest DSM (Device-Specific Module) software module, that can be obtained from the storage/HBA vendor.
5. ISCSI usually supported in 1 GB or higher infrastructure. Using 10/100 MB infrastructure can lead to low performance/data corruption.
6. Please use a dedicated network adapter/s (or HBA) for iSCSI connection. Combining regular network traffic and iSCSI traffic can lead to performance and security issues.
7. The network switch/s that planed to be used for the iSCSI infrastructure should be certificate for ISCSI traffic.
Note: Not all the common network switches officially support iSCSI.
9. Use the latest driver for the network adapter/HBA card/s.
10. For backup LUN by using direct SAN technology, its recommended to allow the backup server to have a Read only privilege to the required LUN.
11. Although iSCSI support block level transfer over TCP/IP, a regular network issues can lead to performance issues. To avoid performance issues, its recommended to implemented a full network design that includes redundant and optimize Spanning Tree Protocol (STP) implementation.
12. Consider to use Jumbo frame on the iSCSI network (Its specially recommended to environments that planed to be use for large file transfer).

Network Performance
1. Review the current network settings by using the command:
netsh interface tcp show global

2. Consider to optimize the autotuninglevel level by implement one of the following settings:
netsh interface tcp set global autotuninglevel=disabled    
 
3. Consider to disable Chimney Offload State support:
netsh int tcp set global chimney=disabled

4. Consider to disable Receive Side Scaling (RSS) support:
netsh int tcp set global rss=disabled

5. Although its usually supported, don’t use any firewall/routing device in the ISCSI network.

6. Consider to disable EnableICMPRedirect support:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters
Value DWORD 32bits: EnableICMPRedirect set to "0"

7. To implement a high availably and high performance solution, consider to implement MPIO (Microsoft® Multipath I/O):
Understanding MPIO Features and Components

8. Integrating iSCSI, FCIP, and iFCP technologies required a special care. For start, please review: Mr. Jane Shurtleff article:
IP storage: A review of iSCSI, FCIP, iFCP

Note3:Its recommended to reboot the server after applying this changes.                                    


Thursday, June 6, 2013

VBScript Mount PST File on Outlook

Mount the PST files from list on Outlook.
PST Files list save in pstlist.txt
File Name openpst.vbe

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("pstlist.txt")
set objOutlook = createObject("Outlook.Application")
set objMAPI = objOutlook.GetNamespace("MAPI")
do while not objFile.AtEndOfStream
    fPath =  objFile.ReadLine()
    objMAPI.AddStore fPath
loop

VBScript get Outlook PST files list

Get Outlook mounted PST Files list. And save file list to pstlist.txt.

File name: getpstlist.vbe

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("pstlist.txt", True)
set objOutlook = createObject("Outlook.Application")
set objMAPI = objOutlook.GetNamespace("MAPI")
for each PSTFolder In objMAPI.Folders
  pstPath = GetPath(PSTFolder.StoreID)
  if pstPath <> "" then
    objFile.WriteLine pstPath
  end if
next
function GetPath(input)
  for i = 1 To Len(input) Step 2
    strSubString = Mid(input,i,2)
    if Not strSubString = "00" Then
       strPath = strPath & ChrW("&H" & strSubString)
    end If
  next
  select Case True
  case InStr(strPath,":\") > 0
    GetPath = Mid(strPath,InStr(strPath,":\")-1)
  case InStr(strPath,"\\") > 0
    GetPath = Mid(strPath,InStr(strPath,"\\"))
  end Select
end Function

Friday, January 18, 2013

Monitor Hosts and Generate Command Line to Update DNS A Recorders

Scenario:

We have tow exchange 2010 servers with HAG. When one is offline, the another one will take all the server roles automatically.
But we do not have network load balancer.
We setup mail.xxxxx.com always point to xxmail01 IP address 192.168.x.25 in our LAN. We also setup mail.xxxxx.com alwasy point to xxmail01 NAT public IP address 208.1.x.25.
If xxmail01 offline, we have to change DNS mail.xxxxx.com record point to xxmail01 IP address ( LAN IP 192.168.x.35, WAN IP 208.1.x.35) manually.

The LAN DNS server is intDNS01, WAN DNS server is extDNS01.
Setup Schedule Task on Both DNS servers to run the command line to update DNS A records, if exchange server is offline. After run the cmd scritps successfully, delete them each time.
The DNS update command file store on share folder  \\intDNS01\taskscript\updateintdns.bat
\\extDNS01\taskscript\updateextdns.bat.


Prepare

List the monitor Hosts in file name testRecordList.txt like the following format.

#please the test informantion

#If have internal and external DNS Servers, one record point to one internal and one external IP, please use the following format.
#Int_dns_servername,Ext_dns_servername;full_test_DNS_name;First_Int_IP_Address,Frist_Ext_IP_Address;Second_Int_IP_Address,Second_Ext_IP_Address
intDNS01,extDNS01;mail.xxxxx.com;192.168.x.25,208.1.x.25;192.168.x.35,208.1.x.35

#If one has internal DNS Servers, please use the following format.
#Int_dns_servername;full_test_DNS_name;First_Int_IP_Address;Second_Int_IP_Address


Python Script

File Name:  gendnsupdatecmd.py

'''
Created on Jan 10, 2013

@author: chu
'''
import os, time


#Run nslookup to check if the A Record is list on the DNS server or not.
def getARecordIp(aName):
    os.popen("ipconfig /flushdns")
    nslookupcmd = "nslookup " + aName
    nslookupReturn = os.popen(nslookupcmd).readlines()
    if len(nslookupReturn) < 4:
        return "Failed"
    elif aName in nslookupReturn[3]:
        return nslookupReturn[4].split(' ')[2:]
    else:
        return "Failed"    
        

#Run Ping to check the A Record Host is alive or not. 
def pingTest(ip):
    pingcmd = "ping -n 1 -i 5 " + ip
    testResult = os.popen(pingcmd).readlines()
    if len(testResult) < 2:
        result = False
        return result
    if 'Request timed out.' in testResult[3]:
        result = False
        return result
    else:
        result = True
        return result
   

#Generate delete A Record command line.
def delRecord(record,intip):
    intdelRecordcmd = ''
    extdelRecordcmd = ''
    for i in range(2,len(record)):
        if intip in record[i].split(',')[0]:            
            hostname = record[1].split('.')[0]
            domainName = record[1].split('.')[1] + '.' + record[1].split('.')[2].strip(' ')
            intDnsServer = record[0].split(',')[0]            
            intdelRecordcmd = 'dnscmd ' + intDnsServer +' /RecordDelete ' + domainName + ' ' + hostname + ' 900 A ' + intip +' /f'
            if len(record[0].split(',')) == 2:
                extip = record[i].split(',')[1]
                extDnsServer = record[0].split(',')[1]
                extdelRecordcmd = 'dnscmd ' + extDnsServer +' /RecordDelete ' + domainName + ' ' + hostname + ' 900 A ' + extip +' /f'
    delRecordcmd = [intdelRecordcmd, extdelRecordcmd]
    return delRecordcmd
    

#Generate Add A Record command line.    
def addRecord(record):
    intaddRecordcmd = ''
    extaddRecordcmd = ''
    #ping Hostname
    pingResult = pingTest(record[1])
    if pingResult:
        addRecordcmd = [intaddRecordcmd, extaddRecordcmd]
        return addRecordcmd
    time.sleep(10)
    if pingResult:
        addRecordcmd = [intaddRecordcmd, extaddRecordcmd]
        return addRecordcmd
    for i in range(2,len(record)):
        #Ping IP address
        pingResult = pingTest(record[i].split(',')[0])
        if pingResult:
            hostname = record[1].split('.')[0]
            domainName = record[1].split('.')[1] + '.' + record[1].split('.')[2].strip(' ')
            intIp = record[i].split(',')[0]            
            intDnsServer = record[0].split(',')[0]            
            intaddRecordcmd = 'dnscmd ' + intDnsServer + ' /RecordAdd ' + domainName + ' ' + hostname + ' 900 A ' + intIp
            if len(record[0].split(',')) == 2:                
                extIp =  record[i].split(',')[1]
                extDnsServer = record[0].split(',')[1]
                extaddRecordcmd = 'dnscmd ' + extDnsServer + ' /RecordAdd ' + domainName + ' ' + hostname + ' 900 A ' + extIp
            addRecordcmd = [intaddRecordcmd, extaddRecordcmd]
            return addRecordcmd
      

def main():
    intcmdLines = []
    extcmdLines = []
    try:
        recordFile = open('testRecordList.txt','r')
        recordLines = recordFile.readlines()        
    finally:
        recordFile.close()
    for recordLine in recordLines:
        if recordLine.startswith('#'):
            continue
        if len(recordLine.strip(' ').strip('\n'))== 0:
            continue        
        record = recordLine.strip('\n').split(';')
        currentAIp = getARecordIp(record[1])
        if currentAIp == 'Failed':
            time.sleep(10)
            currentAIp = getARecordIp(record[1])
        if currentAIp == 'Failed':
            addRecordcmd = addRecord(record)            
            if addRecordcmd[0]:
                intcmdLines.append(addRecordcmd[0])
            if addRecordcmd[1]:
                extcmdLines.append(addRecordcmd[1])
            continue
        pingResult = pingTest(record[1])
        if pingResult:
            continue
        time.sleep(10)
        if pingResult:
            continue
        delRecordcmd = delRecord(record,currentAIp[0].strip('\n'))
        if delRecordcmd[0]:
            intcmdLines.append(delRecordcmd[0])
        if delRecordcmd[1]:
            extcmdLines.append(delRecordcmd[1])
        addRecordcmd = addRecord(record)
        if addRecordcmd[0]:
            intcmdLines.append(addRecordcmd[0])
        if addRecordcmd[1]:
            extcmdLines.append(addRecordcmd[1])
    if intcmdLines:
        try:
            logFile = open("changeintdnslog.txt","a")
            cmdFile = open("updateintdns.bat","w")
            for line in intcmdLines:
                cmdFile.write(line+'\n')
                logFile.write(time.strftime("%m-%d-%Y %H:%M:%S",time.localtime()) + '\n')
                logFile.write(line+'\n\n')
        finally:
            logFile.close()
            cmdFile.close()
        intDnsServer = intcmdLines[0].split(' ')[1].strip(' ')
        cpCmd = r"copy /V /Y updateintdns.bat \\" + intDnsServer + r"\taskscript"
        os.popen(cpCmd)
        
    if extcmdLines:
        try:
            logFile = open("changeextdnslog.txt","a")
            cmdFile = open("updateextdns.bat","w")
            for line in extcmdLines:
                cmdFile.write(line+'\n')
                logFile.write(time.strftime("%m-%d-%Y %H:%M:%S",time.localtime()) + '\n')
                logFile.write(line+'\n\n')
        finally:
            logFile.close()
            cmdFile.close()
        extDnsServer = extcmdLines[0].split(' ')[1].strip(' ')
        cpCmd = r"copy /V /Y updateextdns.bat \\" + extDnsServer + r"\taskscript"
        os.popen(cpCmd)

    
if __name__ == "__main__":      
    main()