Solved

how to execute cmd commands using asp.net

Posted on 2010-11-10
13
873 Views
Last Modified: 2012-08-13
hi i need to execute the dnscmd command on the webserver, i have impersonate set to login as windows user that have the permissions set  too.

ii also tryed this 2 way:

1)
        'Dim myprocess As System.Diagnostics.Process = New System.Diagnostics.Process()
        'myprocess.StartInfo.FileName = "dnscmd.exe"
        'myprocess.StartInfo.RedirectStandardOutput = True
        'myprocess.StartInfo.UseShellExecute = False
        'myprocess.StartInfo.CreateNoWindow = True
        'myprocess.StartInfo.Arguments = " /zoneadd aaaaa.com /primary /file aaaaa.com.dns"
        'myprocess.Start()

2)
        'Dim startInfo As New ProcessStartInfo("C:\Windows\System32\dnscmd.exe")
        'startInfo.Arguments = "/zoneadd aaaaa.com /primary /file aaaaa.com.dns"
        'Process.Start(startInfo)

none of those are working. the syntax is right i check it. i did myself on the cmd this syntax and created the dns record. but using the command on the asp.net code is not working.
0
Comment
Question by:rafaelrgl
  • 10
  • 3
13 Comments
 
LVL 51

Accepted Solution

by:
HainKurt earned 500 total points
ID: 34108563
do you have this file?

        'Dim startInfo As New ProcessStartInfo("C:\Windows\System32\dnscmd.exe")

try something else like

"dir c:/ > c:\dir.txt"

and see if it writes a text file on c:\
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34108583
no, it did not writes the text file on c:\

0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34108591
i forgot to answer you,

yes i have the file on C:\Windows\System32\dnscmd.exe
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 34108754
do you get any error when you start the process?
0
 
LVL 51

Assisted Solution

by:HainKurt
HainKurt earned 500 total points
ID: 34108784
check this forum

http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx

it discusses running cmd.exe and sending commands to it...
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34108843
well, this will not work for me hainkurt,

i need to execute this class attached, and there is an function like this:

        Private Sub Execute(ByVal argument As String)
            If DEBUG Then
                Console.WriteLine(DNS_CMD + " " + serverName + argument)
            Else
                Dim dnsCmd As Process = GetDnsProcess()

                dnsCmd.StartInfo.Arguments = serverName + argument
                dnsCmd.Start()

                dnsCmd.WaitForExit()
            End If
        End Sub


like the one i posted above, it uses the process. but this also is not working. that's why i need to resolve the above function.

Imports Microsoft.VisualBasic
Imports System
Imports System.Diagnostics

Namespace DnsCmdWrapper
    Public Class DnsCmd
        Private Const DNS_CMD As String = "dnscmd"
        Public Shared DEBUG As Boolean = False
        Public serverName As String = "."
        Public ttl As Integer = 172800

        Public Sub New(ByVal serverName As String)
            Me.serverName = serverName
        End Sub

        Public Function ZoneExists(ByVal zone As String) As Boolean
            If DEBUG Then
                Return True
            End If

            Dim dnsCmd As Process = GetDnsProcess()

            dnsCmd.StartInfo.Arguments = serverName + "/ZoneInfo " + zone
            dnsCmd.Start()

            Dim output As String = dnsCmd.StandardOutput.ReadToEnd()

            dnsCmd.WaitForExit()

            Return Not (output.IndexOf("DNS_ERROR_ZONE_DOES_NOT_EXIST") > -1)
        End Function
        Public Sub CreatePrimaryZone(ByVal zone As String)
            Execute(" /ZoneAdd " + zone + " /Primary /file " + zone + ".dns")
        End Sub

        Public Sub CreateSecondaryZone(ByVal zone As String, ByVal masterIpAddress As String)
            If masterIpAddress Is Nothing OrElse masterIpAddress.Length = 0 Then
                Throw New ApplicationException("masterIpAddress can NOT be null.")
            End If

            Execute(" /ZoneAdd " + zone + " /Secondary " + masterIpAddress)
        End Sub
        Public Sub DeleteZone(ByVal zone As String)
            Execute(" /ZoneDelete " + zone + " /f")
        End Sub
        Public Sub CreateRecord(ByVal zone As String, ByVal record As RRecord)
            Dim argument As String = Nothing

            Select Case record.recordType
                Case RecordTypes.A
                    Dim a As ARecord = DirectCast(record, ARecord)
                    argument = [String].Format(" /RecordAdd {0} {1} {2} A {3}", zone, a.NodeName, ttl.ToString(), a.IpAddress)
                    Exit Select
                Case RecordTypes.NS
                    Dim ns As NSRecord = DirectCast(record, NSRecord)
                    argument = [String].Format(" /RecordAdd {0}  {1} {2} NS {3}", zone, ns.NodeName, ttl.ToString(), ns.HostName)
                    Exit Select
                Case RecordTypes.MX
                    Dim mx As MXRecord = DirectCast(record, MXRecord)
                    argument = [String].Format(" /RecordAdd {0}  {1} {2} MX {3} {4}", zone, mx.NodeName, ttl.ToString(), mx.Preference, mx.ServerName)
                    Exit Select
                Case RecordTypes.SOA
                    Dim soa As SOARecord = DirectCast(record, SOARecord)
                    argument = [String].Format(" /RecordAdd {0} {1} {2} SOA {3} {4} {5} {6} {7} {8} {9}", zone, soa.NodeName, ttl, soa.PrimaryServer, soa.AdminEmail, _
                     soa.Serial, soa.Refresh, soa.Retry, soa.Expire, soa.MinTtl)
                    Exit Select
            End Select

            If argument IsNot Nothing Then
                Execute(argument)
            End If

        End Sub
        Public Sub DeleteRecord(ByVal zone As String, ByVal record As RRecord)
            Dim argument As String = Nothing

            Select Case record.recordType
                Case RecordTypes.A
                    Dim a As ARecord = DirectCast(record, ARecord)
                    argument = [String].Format(" /RecordDelete {0} {1} {2} A {3} /f", zone, a.NodeName, ttl.ToString(), a.IpAddress)
                    Exit Select
                Case RecordTypes.NS
                    Dim ns As NSRecord = DirectCast(record, NSRecord)
                    argument = [String].Format(" /RecordDelete {0}  {1} {2} NS {3} /f", zone, ns.NodeName, ttl.ToString(), ns.HostName)
                    Exit Select
                Case RecordTypes.MX
                    Dim mx As MXRecord = DirectCast(record, MXRecord)
                    argument = [String].Format(" /RecordDelete {0}  {1} {2} MX {3} {4} /f", zone, mx.NodeName, ttl.ToString(), mx.Preference, mx.ServerName)
                    Exit Select
            End Select

            If argument IsNot Nothing Then
                Execute(argument)
            End If

        End Sub

        ''' <summary>
        '''	Resets the IP addresses for secondary DNS Servers in the zone.
        ''' </summary>
        ''' <param name="zone">domain name</param>
        ''' <param name="secondaryIPAddress">List of ip addesses separated by space</param>
        Public Sub ResetSecondaries(ByVal zone As String, ByVal secondaryIPAddress As String)
            Execute(" /ZoneResetSecondaries " + zone + " /SecureList " + secondaryIPAddress)
        End Sub
        Private Sub Execute(ByVal argument As String)
            If DEBUG Then
                Console.WriteLine(DNS_CMD + " " + serverName + argument)
            Else
                Dim dnsCmd As Process = GetDnsProcess()

                dnsCmd.StartInfo.Arguments = serverName + argument
                dnsCmd.Start()

                dnsCmd.WaitForExit()
            End If
        End Sub
        Private Function GetDnsProcess() As Process
            Dim proc As New Process()

            proc.EnableRaisingEvents = False

            proc.StartInfo.CreateNoWindow = True
            proc.StartInfo.UseShellExecute = False
            proc.StartInfo.RedirectStandardOutput = True

            proc.StartInfo.FileName = DNS_CMD

            Return proc
        End Function
        '
        '		private string ZoneTypeToString(ZoneTypes zoneType)
        '		{
        '			switch(zoneType)
        '			{
        '				case ZoneTypes.Primary  : return "Primary" ;
        '				case ZoneTypes.Secondary: return "Secondary";
        '			}
        '			return string.Empty ;
        '		}
        '
    End Class

    Public Enum ZoneTypes
        Primary
        Secondary
    End Enum
    Public Enum RecordTypes
        A
        MX
        NS
        SOA
    End Enum
    Public MustInherit Class RRecord
        Public recordType As RecordTypes

        Public Sub New(ByVal recordType As RecordTypes)
            Me.recordType = recordType
        End Sub
    End Class
    Public Class ARecord
        Inherits RRecord
        Public ReadOnly Property NodeName() As String
            Get
                Return m_nodeName
            End Get
        End Property

        Public ReadOnly Property IpAddress() As String
            Get
                Return m_ipAddress
            End Get
        End Property

        Private m_nodeName As String, m_ipAddress As String

        Public Sub New(ByVal nodeName As String, ByVal ipAddress As String)
            MyBase.New(RecordTypes.A)
            Me.m_nodeName = nodeName
            Me.m_ipAddress = ipAddress
        End Sub
    End Class
    Public Class NSRecord
        Inherits RRecord
        Public ReadOnly Property HostName() As String
            Get
                Return m_hostName
            End Get
        End Property

        Private m_hostName As String

        Public ReadOnly Property NodeName() As String
            Get
                Return m_nodeName
            End Get
        End Property

        Private m_nodeName As String

        Public Sub New(ByVal nodeName As String, ByVal hostName As String)
            MyBase.New(RecordTypes.NS)
            Me.m_nodeName = nodeName
            Me.m_hostName = hostName
        End Sub
    End Class
    Public Class MXRecord
        Inherits RRecord
        Public ReadOnly Property NodeName() As String
            Get
                Return m_nodeName
            End Get
        End Property

        Public ReadOnly Property Preference() As Integer
            Get
                Return m_preference
            End Get
        End Property

        Public ReadOnly Property ServerName() As String
            Get
                Return m_serverName
            End Get
        End Property

        Private m_nodeName As String
        Private m_preference As Integer
        Private m_serverName As String

        Public Sub New(ByVal nodeName As String, ByVal preference As Integer, ByVal serverName As String)
            MyBase.New(RecordTypes.MX)
            Me.m_nodeName = nodeName
            Me.m_preference = preference
            Me.m_serverName = serverName
        End Sub
    End Class
    Public Class SOARecord
        Inherits RRecord
        Public ReadOnly Property NodeName() As String
            Get
                Return m_nodeName
            End Get
        End Property

        Public ReadOnly Property PrimaryServer() As String
            Get
                Return m_primaryServer
            End Get
        End Property

        Public ReadOnly Property AdminEmail() As String
            Get
                Return m_adminEmail
            End Get
        End Property

        Public ReadOnly Property Refresh() As Integer
            Get
                Return m_refresh
            End Get
        End Property

        Public ReadOnly Property Retry() As Integer
            Get
                Return m_retry
            End Get
        End Property

        Public ReadOnly Property Expire() As Integer
            Get
                Return m_expire
            End Get
        End Property

        Public ReadOnly Property MinTtl() As Integer
            Get
                Return m_minTTL
            End Get
        End Property

        Private m_nodeName As String
        Private m_primaryServer As String
        Private m_adminEmail As String
        Private m_refresh As Integer
        Private m_retry As Integer
        Private m_expire As Integer
        Private m_minTTL As Integer
        Private m_serial As String

        Public Sub New(ByVal nodeName As String, ByVal primaryServer As String, ByVal serial As String, ByVal adminEmail As String, ByVal refresh As Integer, ByVal retry As Integer, _
         ByVal expire As Integer, ByVal minTTL As Integer)
            MyBase.New(RecordTypes.SOA)
            Me.m_nodeName = nodeName
            Me.m_primaryServer = primaryServer
            Me.m_adminEmail = adminEmail
            Me.m_refresh = refresh
            Me.m_retry = retry
            Me.m_expire = expire
            Me.m_minTTL = minTTL
            Me.m_serial = serial
        End Sub

        Public ReadOnly Property Serial() As String
            Get
                Return m_serial
            End Get
        End Property
    End Class
End Namespace

Open in new window

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:rafaelrgl
ID: 34117437
any idea HainKurt?
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34124817
find something on the web, and i tryed but it gives an error saying access denied.

but i have the permission set to this user.

here is what i did:


      Dim SecurePassword As New System.Security.SecureString
        Dim SPassword As String = "samplepassword"
        For Each c As Char In SPassword.ToCharArray
            SecurePassword.AppendChar(c)
        Next
       Process.Start("C:\Windows\System32\cmd.exe", "dir c:/ > c:\dir.txt", SecurePassword, "machinename\myusername").Start()


i can't make this process to start. help hainkurt.
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34142419
ok, i am almost giving up. but i had an crazy idea, that may will work.

build an dll that handle the creation of the dns recodrs, than make an web reference to it.

but i have no idea how to create this dll resorce with the functions inside. is that an regullar dll?
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34151159
it does not matter, test done with the dll. i give up. pls help.
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34154247
i check the process open, it was open as network service not as administrator user as i did with the impersontation,


here is the code i use to test it.

        Dim psi As New ProcessStartInfo("cmd.exe")
        psi.UseShellExecute = False
        psi.RedirectStandardOutput = True
        psi.RedirectStandardInput = True
        psi.RedirectStandardError = True

        Dim Proc As Process = Process.Start(psi)
        Dim sw As StreamWriter = Proc.StandardInput
        sw.WriteLine("dnscmd /zoneadd aaaaa.com /primary /file aaaaa.com.dns")
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 34154270
i did different now, then i got an error:
           Server Error in '/' Application.
           Access is denied
           Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
           Exception Details: System.ComponentModel.Win32Exception: Access is denied


        Dim SecurePassword As New System.Security.SecureString
        Dim SPassword As String = "mypassword"
        For Each c As Char In SPassword.ToCharArray
            SecurePassword.AppendChar(c)
        Next
       Dim psi As New ProcessStartInfo("cmd.exe")
        psi.UseShellExecute = False
        psi.RedirectStandardOutput = True
        psi.RedirectStandardInput = True
        psi.RedirectStandardError = True
        psi.UserName = "adminuser"
        psi.Password = SecurePassword
        Dim Proc As Process = Process.Start(psi)
        Dim sw As StreamWriter = Proc.StandardInput
        sw.WriteLine("dnscmd /zoneadd aaaaa.com /primary /file aaaaa.com.dns")
0
 
LVL 1

Author Closing Comment

by:rafaelrgl
ID: 34325070
thanks
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

I was supporting a handful of Windows 2008 (non-R2) 2 node clusters with shared quorum disks. Some had SQL 2008 installed and some were just a vendor application that we supported. For the purposes of this article it doesn’t really matter which so w…
Lync server 2013 Backup Service Error ID 4049 – After File Share Migration
This tutorial will walk an individual through locating and launching the BEUtility application to properly change the service account username and\or password in situation where it may be necessary or where the password has been inadvertently change…
This tutorial will walk an individual through setting the global and backup job media overwrite and protection periods in Backup Exec 2012. Log onto the Backup Exec Central Administration Server. Examine the services. If all or most of them are stop…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now