Run a batch file as a specific User (or Administrator) from ASP.NET...

by Rahul 7/13/2008 8:20:21 AM

...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...

 image

Hope this helps, Smile
Rahul


Quote of the day:
The human race has one really effective weapon, and that is laughter. - Mark Twain


blog comments powered by Disqus

Comments

Search


Tags



Categories

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

All Items
Sign in

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Rahul Soni

Powered by BlogEngine.NET 1.4.5.0