天天看點

C#遠端連接配接代碼

1 /// <summary>
 2 /// 服務連接配接配置類(驗證服務賬号是否正确)
 3 /// </summary>
 4 /// <param name="remoteHost">IP位址</param>
 5 /// <param name="userName">遠端賬号</param>
 6 /// <param name="passWord">遠端密碼</param>
 7 /// <returns></returns>
 8 public bool Connect(string remoteHost, string userName, string passWord)
 9 {
10 bool Flag = false;
11 Process proc = new Process();
12 try
13 {
14 proc.StartInfo.FileName = "cmd.exe";
15 proc.StartInfo.UseShellExecute = false;
16 proc.StartInfo.RedirectStandardInput = true;
17 proc.StartInfo.RedirectStandardOutput = true;
18 proc.StartInfo.RedirectStandardError = true;
19 proc.StartInfo.CreateNoWindow = true;
20 proc.Start();
21 string dosLine = @"net use " + remoteHost +" /User:domain\\" + userName + " " + passWord + " /PERSISTENT:YES";
22 proc.StandardInput.WriteLine(dosLine);
23 proc.StandardInput.WriteLine("exit");
24 while (!proc.HasExited)
25 {
26 proc.WaitForExit(1000);
27 }
28 
29 string errormsg = proc.StandardError.ReadToEnd();
30 proc.StandardError.Close();
31 if (String.IsNullOrEmpty(errormsg))
32 {
33 Flag = true;
34 }
35 }
36 catch (Exception ex)
37 {
38 Console.WriteLine(ex.Message);
39 throw ex;
40 }
41 finally
42 {
43 proc.Close();
44 proc.Dispose();
45 }
46 return Flag;
47 }      
1 public static bool Ping(string remoteHost)
 2         {
 3             bool Flag = false;
 4             Process proc = new Process();
 5             try
 6             {
 7                 proc.StartInfo.FileName = "cmd.exe";
 8                 proc.StartInfo.UseShellExecute = false;
 9                 proc.StartInfo.RedirectStandardInput = true;
10                 proc.StartInfo.RedirectStandardOutput = true;
11                 proc.StartInfo.RedirectStandardError = true;
12                 proc.StartInfo.CreateNoWindow = true;
13                 proc.Start();
14                 string dosLine = @"ping -n 1 " + remoteHost;
15                 proc.StandardInput.WriteLine(dosLine);
16                 proc.StandardInput.WriteLine("exit");
17                 while (proc.HasExited == false)
18                 {
19                     proc.WaitForExit(500);
20                 }
21                 string pingResult = proc.StandardOutput.ReadToEnd();
22                 if (pingResult.IndexOf("(0% loss)") != -1 || pingResult.IndexOf("(0% 丢失)") != -1)
23                 {
24                     Flag = true;
25                 }
26                 proc.StandardOutput.Close();
27             }
28             catch (Exception ex)
29             {
30             }
31             finally
32             {
33                 try
34                 {
35                     proc.Close();
36                     proc.Dispose();
37                 }
38                 catch
39                 {
40                 }
41             }
42             return Flag;
43         }      

轉載于:https://www.cnblogs.com/Zhengxue/p/8548083.html