Thursday, December 14, 2017

Excel vba code to execute Unix/Linux commands from windows machine via plink

'' Excel vba code to execute any of the unix/linux commands from windows environment via plink & capture the output in a csv file.

'' To use this module you need to download the plink.exe file from google & then execute the below script.

Global uName, Pwd, cmdTxt, cmd, sName
Global pLink, OutfPath, ScriptPath, wshShell, oExec, sRow, sCol, i

Sub Execute_UnixScript()
 
    pLink = "C:\Users\desktop\plink.exe"                                        '' edit the plink file path
    'ScriptPath = "C:\Users\desktop\script.sh"                                 '' edit the script file path
    OutfPath = "C:\Users\desktop\cmdOut.csv"                               '' edit the output file path
 
    Kill OutfPath
 
    Application.SheetsInNewWorkbook = 1
    Workbooks.Add
    ActiveWorkbook.SaveAs OutfPath, xlCSV
 
    sName = "1.1.12.13"                                                     '' edit the unix server name
    uName = "username"                                                   '' edit the user name 
    Pwd = "pwd"                                           '' edit the password
 
    If pLink = "" Or OutfPath = "" Or ScriptPath = "" Then Exit Sub

    'cmd = Chr(34) & pLink & Chr(34) & " -t -ssh " & uName & "@" & sName & " -pw " & Pwd & " -m " & Chr(34) & ScriptPath & Chr(34) ''' use this if you want to execute a unix/linux script file

     cmd = Chr(34) & pLink & Chr(34) & " -t -ssh " & uName & "@" & sName & " -pw " & Pwd & " sudo pvs -o pv_name,pv_size,pv_free --separator , --noheading"
     
    '' shell object created for executing the command
    Set wshShell = CreateObject("WScript.Shell")
 
    '' command has been executed
    Set oExec = wshShell.Exec(cmd)
         
    sRow = 2
    sCol = 2

    With Workbooks("cmdout.csv").ActiveSheet
        .Cells(1, 1) = "Server IP"
        .Cells(1, 2) = "PV"
        .Cells(1, 3) = "PSize"
        .Cells(1, 4) = "PFree"
        .Cells(1, 5) = "Date"

        ''' Read all command output line by line
        While Not oExec.StdOut.AtEndOfStream
            cmdTxt = Split(oExec.StdOut.ReadLine, ",")
            .Cells(sRow, 1) = sName
                For i = 0 To UBound(cmdTxt)
                    .Cells(sRow, sCol) = Trim(cmdTxt(i))
                    sCol = sCol + 1
                Next
            .Cells(sRow, 5) = Format(Date, "yyyy-mm-dd")
            sCol = 2
            sRow = sRow + 1
        Wend
    End With
    Workbooks("cmdout.csv").Close True
 
    Set wshShell = Nothing
    Set oExec = Nothing
End Sub

No comments:

Post a Comment

Excel VBA to send email from excel with HTML table in a email body

'' Excel vba script to send email from outlook & email body in HTML table format. ''Write down email body in HTML tags...