Получение вывода оболочки nslookup с помощью C # - PullRequest
6 голосов
/ 09 декабря 2008

У меня есть процесс командной строки, который я хотел бы автоматизировать и перехватить в C #.

В командной строке я набираю:

nslookup

Это запускает оболочку, которая выдает> приглашение. В ответ на приглашение введите:

ls -a mydomain.local

Возвращает список локальных CNAME с моего основного DNS-сервера и физических компьютеров, к которым они подключены.

Что я хотел бы сделать, это автоматизировать этот процесс из C #. Если бы это была простая команда, я бы просто использовал Process.StartInfo.RedirectStandardOutput = true, но требование второго шага сбивает меня с толку.

Ответы [ 3 ]

7 голосов
/ 09 декабря 2008
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. 
2 голосов
/ 09 декабря 2008

Не то, что вы спросили, но я однажды написал приложение, которое сделало то, что вы делаете. В конце концов я перешел на использование библиотеки .NET для поиска DNS, что оказалось намного быстрее.

Я почти уверен, что использовал эту библиотеку с сайта CodeProject.

1 голос
/ 06 июля 2011

Я знаю, что это старый, но все еще хотел бы внести свой вклад. Я использовал вывод оболочки «NsLookup Hostname Server», чтобы получить IPv4-адреса от имени компьютера в нашем домене и удалить любую другую информацию, такую ​​как адреса DNS-сервера / ipv6.

Это довольно быстро делается, но это работает, также добавляется аварийное переключение, если оболочка перестала работать, вы бы использовали встроенный метод nslookup из C #.

это довольно долго, но это дало мне возможность читать ipv4 из оболочки без использования внешней библиотеки или без использования встроенной функции nslookup, поскольку она позволяет выбирать сервер DNS.

Если вам интересно узнать о циклах if посередине, возможно, есть более элегантные решения, но для моего личного использования это сработало довольно хорошо, большинство хостов в нашем домене вернули 2 ipv6 и 2 ipv4, поэтому они тестируют до 4 раз.

Надеюсь, что это может помочь ..

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


}

}

...