Run a batch file as a specific User (or Administrator) from ASP.NET...
...well first of all, I am NOT recommending it, but sometimes it could be necessary! Now, let's proceed to the code...
1. Create a page called RunBatchFile.vb and paste the following...
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
2. The batch file that I have is a one liner (and a no-brainer)... [Here, one and two are folders containing a few files]
xcopy one\*.* two /y
3. If everything is in place, you should get something like this as output...
Hope this helps,
Rahul
Quote of the day:
The human race has one really effective weapon, and that is laughter. - Mark Twain
Comments
Anonymous
July 12, 2008
PingBack from http://blog.a-foton.ru/2008/07/run-a-batch-file-as-a-specific-user-or-administrator-from-aspnet/Anonymous
February 01, 2009
Thank you very very much, I tried everything but this is the best solution for me thanxxxxxxxxxxxxxxxxxxAnonymous
July 05, 2009
Thank you, it solved my problem