C#을 사용하여 NSLookup 쉘 출력 캡처
문제
C#에서 자동화하고 캡처하고 싶은 명령 줄 프로세스가 있습니다.
명령 줄에서 i를 입력합니다.
nslookup
이것은 나에게 프롬프트를 제공하는 쉘을 시작합니다. 프롬프트에서 다음을 입력합니다.
ls -a mydomain.local
이것은 기본 DNS 서버와 첨부 된 물리적 시스템의 로컬 CNAME 목록을 반환합니다.
내가하고 싶은 것은 C#에서이 프로세스를 자동화하는 것입니다. 이것이 간단한 명령이라면 프로세스 만 사용하면 startinfo.redirectStandardOutput = true를 사용하지만 두 번째 단계의 요구 사항은 나를 넘어갑니다.
해결책
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.
다른 팁
당신이 물었던 것이 아니라, 한 번 당신이하고있는 일을 한 앱을 썼습니다. 나는 결국 .NET 라이브러리를 사용하여 DNS 조회를 수행하여 훨씬 더 빠른 것으로 판명되었습니다.
나는 내가 사용했다고 확신한다 이 도서관 CodeProject 사이트에서.
나는 이것이 오래된 것임을 알고 있지만 여전히 기여하는 것을 좋아합니다. "NSLookup HostName Server"의 쉘 출력을 사용하여 도메인의 CompuTername에서 IPv4 주소를 가져 와서 DNS Server / IPv6 주소와 같은 다른 정보를 제거했습니다.
이것은 약간 빨리 수행되지만 작동합니다. C#의 내장 NSLookup 메소드를 사용하는 쉘이 실패하면 장애 조치가 추가됩니다.
다소 길지만 외부 라이브러리를 사용하지 않거나 DNS 서버를 선택할 수 있으므로 내장 NSLookup 기능을 사용하지 않고 쉘에서 IPv4를 읽을 수 있습니다.
중간에 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;
}
}
}
}