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

by Rahul 7/13/2008 3:32:21 PM

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

Rahul Soni

Rahul Soni  Twitter

 LinkedIn

 Facebook

 Email me



Vivek Kumbhar

Vivek Kumbhar  Twitter

 LinkedIn

 Facebook

 Email me


Stack Exchange

profile for Vivek at Server Fault, Q&A for system administrators and IT professionals

profile for Rahul Soni at Stack Overflow, Q&A for professional and enthusiast programmers

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

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 2012, Rahul Soni

Powered by BlogEngine.NET 1.4.5.0