2008-12-09 10 views
6

Ich habe einen Befehlszeilenprozess, den ich in C# automatisieren und erfassen möchte.Capture nslookup Shell-Ausgabe mit C#

in der Befehlszeile, I-Typ:

nslookup 

Dieses eine Shell startet, die mir eine> prompt gibt. An der Eingabeaufforderung gibt Sie mich dann:

ls -a mydomain.local 

Dies gibt eine Liste des lokalen CNAMEs von meinem primären DNS-Server und den physikalischen Maschinen, die sie gebunden sind.

Was ich tun möchte, ist diesen Prozess von C# zu automatisieren. Wenn dies ein einfacher Befehl wäre, würde ich einfach Process.StartInfo.RedirectStandardOutput = true verwenden, aber die Anforderung eines zweiten Schritts stolpert mich.

Antwort

7
ProcessStartInfo si = new ProcessStartInfo("nslookup"); 
si.RedirectStandardInput = true; 
si.RedirectStandardOutput = true; 
Process nslookup = new Process(si); 
nslookup.Start(); 
nslookup.StandardInput.WriteLine("ls -a mydomain.local"); 
nslookup.StandardInput.Flush(); 
// use nslookup.StandardOutput stream to read the result. 
+0

Das hat mich definitiv in die richtige Richtung. Ich endete damit, asynchrone Lesevorgänge und Ereignisse zu verwenden, damit dies wie angekündigt funktionierte, da StandardOutput.ReadToEnd() jedes Mal eingefroren wurde, wie auch .WaitForExit(). –

+0

Ja, definitiv war dieser Teil ein wenig schwierig. Ich habe es dir überlassen, da ich nicht wirklich wusste, wie du die Ausgabe verwenden willst. –

+0

In Bezug auf asynchrone Lesevorgänge kann dies ein echtes Problem sein. In meiner Anwendung verwende ich Code, der von einer Probe angepasst wurde, die ich in diesem [Blog-Posting] gefunden habe (http://www.hanselman.com/blog/SoManyMistakesForMeToMakeSoLittleTimeCapturingStandardErrorAndStandardOutput.aspx). –

2

Nicht was Sie gefragt haben, aber ich habe einmal eine App geschrieben, die das getan hat, was Sie tun. Ich ging schließlich dazu über, eine .NET-Bibliothek zu verwenden, um die DNS-Lookups durchzuführen, was sich als viel schneller herausstellte.

Ich bin mir ziemlich sicher, dass ich this library von der CodeProject Website verwendet habe.

1

Ich weiß, das ist ein altes, aber immer noch gerne dazu beitragen. Ich benutze die Shell-Ausgabe von "NsLookup Hostname Server", um die IPv4-Adressen von einem Computernamen in unserer Domain und strip out alle anderen Informationen wie DNS-Server/IPv6-Adressen.

Das ist ein bisschen schnell getan, aber es funktioniert, Es wird auch ein Failover hinzugefügt, wenn die Shell fehlschlägt und Sie die integrierte nslookup-Methode aus C# verwenden.

es ist ziemlich lang, aber es gab mir die Möglichkeit, das ipv4 aus der Shell zu lesen, ohne eine externe Bibliothek oder ohne die eingebaute nslookup Funktion zu verwenden, da es erlaubt, den DNS-Server zu wählen.

Wenn Sie sich über die if-Schleifen in der Mitte wundern, könnte es elegantere Lösungen geben, aber für meinen persönlichen Gebrauch hat das recht gut geklappt, die meisten Hosts in unserer Domain haben 2 ipv6 und 2 ipv4 zurückgegeben bis zu 4 mal.

Hope this helfen kann ..

private void button1_Click(object sender, EventArgs e) 
    { 
     IPAddress[] ips = NsLookup(computername, dnsserver); 

     txtResult.Text = string.Empty; 
     if (ips != null) 
     { 
      txtResult.Text = ips[0].ToString(); 
      txtResult.Text += Environment.NewLine; 
      if (ips[1] != null) 
      { 
       txtResult.Text += ips[1].ToString(); 
      } 
      else 
      { 

      } 
     } 
     else 
     { 
      txtResult.Text = "No IP found"; 
     } 

    } 



    public IPAddress[] NsLookup(string computername, string domaincontroller) 
    { 

     IPAddress[] ips = new IPAddress[2]; 

     try 
     { 
      // Creating streamreaders to read the output and the errors 
      StreamReader outputReader = null; 
      StreamReader errorReader = null; 

      string nslookup = @"C:\Windows\System32\Nslookup.exe"; 

      try 
      { 
       // Setting process startupinfo 
       ProcessStartInfo processStartInfo = new ProcessStartInfo(nslookup, computername + " " + domaincontroller); 
       processStartInfo.ErrorDialog = false; 
       processStartInfo.UseShellExecute = false; 
       processStartInfo.RedirectStandardError = true; 
       processStartInfo.RedirectStandardInput = true; 
       processStartInfo.RedirectStandardOutput = true; 
       processStartInfo.WindowStyle = ProcessWindowStyle.Minimized; 

       // Starting Process 
       Process process = new Process(); 
       process.StartInfo = processStartInfo; 
       bool processStarted = process.Start(); 

       if (processStarted) 
       { 
        // Catching the output streams 
        outputReader = process.StandardOutput; 
        errorReader = process.StandardError; 

        string errorresult = errorReader.ReadLine(); 

        errorReader.Close(); 


        if (errorresult != null) 
        { 
         // Failure got thrown in NsLookup Streamreading, try build-in Method 
         try 
         { 
          ips = Dns.GetHostAddresses(computername); 
          return ips; 
         } 
         catch 
         { 
          return null; 
         } 
       } 
       else 
       { 
        // Clearing out all the values before the addresses. 
        outputReader.ReadLine(); 
        outputReader.ReadLine(); 
        outputReader.ReadLine(); 
        outputReader.ReadLine(); 

        // Reading and Verifying the first outputline (the address is found after "Addresses: ") - 2 part of the array is taken (after second space) 
        string outputline = outputReader.ReadLine(); 
        string[] outputlineaftersplit = outputline.Split(' '); 
        string ipfortesting = outputlineaftersplit[2].Trim(); 

        if (verifyIP(ipfortesting) != null)  // First entry is ipv4 
        { 
         ips[0] = verifyIP(ipfortesting); 

         outputline = outputReader.ReadLine(); 
         ipfortesting = outputline.Trim(); 

         if (verifyIP(ipfortesting) != null) // First and second entry are ipv4 
         { 
          ips[1] = verifyIP(ipfortesting); 
          return ips; 
         } 
         else 
         { 
          return ips; 
         } 
        } 
        else 
        { 
         outputline = outputReader.ReadLine(); 
         ipfortesting = outputline.Trim(); 

         if (verifyIP(ipfortesting) != null) 
         { 
          ips[0] = verifyIP(ipfortesting); 

          outputline = outputReader.ReadLine(); 
          ipfortesting = outputline.Trim(); 

          if (verifyIP(ipfortesting) != null) 
          { 
           ips[0] = verifyIP(ipfortesting); 

           outputline = outputReader.ReadLine(); 
           ipfortesting = outputline.Trim(); 

           if (verifyIP(ipfortesting) != null) 
           { 
            ips[1] = verifyIP(ipfortesting); 
            return ips; 
           } 
           else 
           { 
            return ips; 
           } 

          } 
          else 
          { 
           return ips; 
          } 
         } 
         else 
         { 
          outputline = outputReader.ReadLine(); 
          ipfortesting = outputline.Trim(); 

          if (verifyIP(ipfortesting) != null) 
          { 

           ips[0] = verifyIP(ipfortesting); 

           outputline = outputReader.ReadToEnd(); 
           ipfortesting = outputline.Trim(); 

           if (verifyIP(ipfortesting) != null) 
           { 
            ips[1] = verifyIP(ipfortesting); 
            return ips; 
           } 
           else 
           { 
            return ips; 
           } 

          } 
          else 
          { 
           ips = null; 
           return ips; 
          } 
         } 
        } 
       } 
       } 

       else 
       { 
        // Failure got thrown in NsLookup Streamreading, try build-in Method 
        try 
        { 
         ips = Dns.GetHostAddresses(computername); 
         return ips; 
        } 
        catch 
        { 
         return null; 
        } 
       } 
      } 
      catch 
      { 
       System.Windows.Forms.MessageBox.Show("ERROR 1"); 
       // Failure got thrown in NsLookup Streamreading, try build-in Method 
       try 
       { 
        ips = Dns.GetHostAddresses(computername); 
        return ips; 
       } 
       catch 
       { 
        return null; 
       } 
      } 
      finally 
      { 
       if (outputReader != null) 
       { 
        outputReader.Close(); 
       } 
      } 
     } 
     catch 
     { 
      System.Windows.Forms.MessageBox.Show("ERROR 2"); 
      // Failure got thrown in NsLookup Streamreading, try build-in Method 
      try 
      { 
       ips = Dns.GetHostAddresses(computername); 
       return ips; 
      } 
      catch 
      { 
       return null; 
      } 
     } 

    } 

    public IPAddress verifyIP(string ipfromreader) 
    { 
     IPAddress ipresult = null; 
     bool isIP = IPAddress.TryParse(ipfromreader, out ipresult); 

     if (isIP && (ipresult.AddressFamily != AddressFamily.InterNetworkV6)) 
     { 
      return ipresult; 
     } 
     else 
     { 
      return null; 
     } 
    } 


} 

}