Question

J'ai un processus de ligne de commande que j'aimerais automatiser et capturer en C #.

Sur la ligne de commande, je tape:

nslookup

Ceci lance un shell qui me donne un > rapide. À l'invite, je tape ensuite:

ls -a mydomain.local

Ceci renvoie la liste des CNAME locaux de mon serveur DNS principal et des machines physiques auxquelles ils sont connectés.

Ce que je voudrais faire, c'est automatiser ce processus à partir de C #. Si c’était une simple commande, j’utiliserais simplement Process.StartInfo.RedirectStandardOutput = true, mais l’exigence d’une deuxième étape m’a déclenché.

Était-ce utile?

La solution

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. 

Autres conseils

Ce n’est pas ce que vous avez demandé, mais j’ai écrit une fois une application qui a fait ce que vous faites. J'ai finalement décidé d'utiliser une bibliothèque .NET pour effectuer les recherches DNS, ce qui s'est avéré beaucoup plus rapide.

Je suis presque sûr d'avoir utilisé cette bibliothèque du site CodeProject .

Je sais que c’est un vieux projet, mais j’aime quand même contribuer. J'ai utilisé la sortie du shell de & Quot; Serveur de nom d'hôte NsLookup & Quot; pour obtenir les adresses IPv4 d’un nom d’ordinateur dans notre domaine et effacer toute autre information telle que les adresses de serveur DNS / ipv6 ..

C’est assez rapide, mais cela fonctionne. Si le shell échoue, le basculement ajoute une méthode permettant d’utiliser la méthode nslookup intégrée à C #.

il est plutôt long mais il m’a donné la possibilité de lire le fichier ipv4 à partir du shell sans passer par une bibliothèque externe ni par la fonction intégrée de nslookup, car elle permet de choisir le serveur DNS.

Si vous vous interrogez sur les boucles if au milieu, il existe peut-être des solutions plus élégantes, mais pour mon usage personnel, cela a très bien fonctionné. La plupart des hôtes de notre domaine ont renvoyé 2 ipv6 et 2 ipv4. à 4 fois.

J'espère que cela peut vous aider.

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


}

}

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top