Saturday, February 12, 2011

Asp.net: Run Batch from Asp as Specific User

Repost:


Imports System.Diagnostics
Imports System.IO
Partial Class RunBatchFile
    Inherits System.Web.UI.Page
    Dim _password As New System.Security.SecureString
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim password As String
        'Read from any Registry or Encrypted config file if you like for added security.
        password = "YOUR___PASSWORD"  
        For Each c As Char In password
            _password.AppendChar(c)
        Next
        Dim strFilePath As String = "c:\\temp\\test.bat"
        Dim psiMyProcess As ProcessStartInfo = New ProcessStartInfo("cmd.exe")
        psiMyProcess.LoadUserProfile = True
        psiMyProcess.UserName = "Administrator"
        psiMyProcess.Password = _password
        psiMyProcess.UseShellExecute = False
        psiMyProcess.CreateNoWindow = True
        psiMyProcess.RedirectStandardOutput = True
        psiMyProcess.RedirectStandardInput = True
        psiMyProcess.RedirectStandardError = True
        psiMyProcess.WorkingDirectory = "c:\\temp\\"
        Dim prcProcess As Process = Process.Start(psiMyProcess)
        Dim strm As StreamReader = File.OpenText(strFilePath)
        Dim strOut As StreamReader = prcProcess.StandardOutput
        Dim strIn As StreamWriter = prcProcess.StandardInput
        Do While strm.Peek() <> -1
            strIn.WriteLine(strm.ReadLine())
        Loop
        strm.Close()
        strIn.WriteLine(String.Format("# {0} ran successfully. Exiting now!", strFilePath))
        strIn.WriteLine("Exit")
        prcProcess.Close()
        Dim strOutput As String = strOut.ReadToEnd().Trim()
        strIn.Close()
        strOut.Close()
        Response.Write(String.Format("<font face=courier size=0>{0}</font>", _
                strOutput.Replace(System.Environment.NewLine, "<br>")))
    End Sub
End Class

Reference:
http://dotnetscraps.com/dotnetscraps/post/Run-a-batch-file-as-a-specific-User-(or-Administrator)-from-ASPNET.aspx

No comments: