Link to home
Start Free TrialLog in
Avatar of rafaelrgl
rafaelrgl

asked on

how to execute cmd commands using asp.net

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.
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rafaelrgl
rafaelrgl

ASKER

no, it did not writes the text file on c:\

i forgot to answer you,

yes i have the file on C:\Windows\System32\dnscmd.exe
do you get any error when you start the process?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

any idea HainKurt?
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.
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?
it does not matter, test done with the dll. i give up. pls help.
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")
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")
thanks