Pregunta

Tengo un proceso de línea de comandos que me gustaría automatizar y capturar en C #.

En la línea de comando, escribo:

nslookup

Esto lanza un shell que me da un > rápido. En el indicador, luego escribo:

ls -a mydomain.local

Esto devuelve una lista de CNAME locales de mi servidor DNS primario y las máquinas físicas a las que están conectados.

Lo que me gustaría hacer es automatizar este proceso desde C #. Si este fuera un comando simple, simplemente usaría Process.StartInfo.RedirectStandardOutput = true, pero el requisito de un segundo paso me está haciendo tropezar.

¿Fue útil?

Solución

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. 

Otros consejos

No es lo que pediste, pero una vez escribí una aplicación que hizo lo que estás haciendo. Eventualmente pasé a usar una biblioteca .NET para hacer las búsquedas de DNS, lo que resultó ser mucho más rápido.

Estoy bastante seguro de que utilicé esta biblioteca del sitio de CodeProject .

Sé que este es viejo, pero aún así me gustaría contribuir. Usé la salida de shell de & Quot; NsLookup Hostname Server & Quot; para obtener las direcciones IPv4 de un nombre de computadora en nuestro dominio y eliminar cualquier otra información como el servidor DNS / direcciones ipv6 ...

Esto se hace un poco rápido pero funciona, también se agrega una conmutación por error si falla el shell de que usaría el método nslookup incorporado de C #.

es bastante largo, pero me dio la posibilidad de leer el ipv4 desde el shell sin usar una biblioteca externa o sin usar la función incorporada nslookup, ya que permite elegir el servidor dns.

Si se está preguntando acerca de los bucles if en el medio, puede haber soluciones más elegantes, pero para mi uso personal, esto funcionó bastante bien, la mayoría de los hosts en nuestro dominio devolvieron 2 ipv6 y 2 ipv4, por lo tanto, probaron a 4 veces.

Espero que esto pueda ayudar ...

    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;
        }
    }


}

}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top