Windows自动更新本地计算机IP地址的主机文件

时间:2017-06-27 16:17:56

标签: windows batch-file automation

我开发了多个应用程序并将它们托管在我的工作笔记本电脑上进行本地调试为了访问这些站点,我输入了一个URL,主机文件重定向到笔记本电脑的IP地址。

我的问题是如何自动更新我的主机文件以将这些网址映射到计算机的当前IP地址。

这将非常有用,因为我将机器停靠在我的桌面并接收一个IP地址,然后步行到会议连接到wifi并接收另一个IP地址。如果我再也不用担心这件事会很棒。

1 个答案:

答案 0 :(得分:0)

在宏观计划中......您需要做的就是在受保护区域中编写结构化文本文件。要对automatically执行no user interaction,您首先需要用户授予您的应用程序权限。一旦您获得访问权限,它就像往常一样。

下面是我为改变主机文件而编写的应用程序的略微修改的复制/粘贴。原样,它并不完全符合您的要求,但是,您可以根据需要进行相应的定制。原样,这是一个命令行工具。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;

namespace ModifyHostFile
{
    class Program
    {
        const string HostFileLocation = @"C:\Windows\System32\drivers\etc\hosts";
        const string HostFileTmpLocation = @"C:\Windows\System32\drivers\etc\hosts_tmp";

        static void Main(string[] args)
        {
            WelcomeUser();

            if (args.Length == 0)
            {
                Console.WriteLine("Must supply action switch [A]dd, or [R]emove entries");
                args = new string[1];
                args.SetValue(Console.ReadLine(), 0);
            }

            switch (args[0].ToUpper())
            {
                case "A":
                    Console.WriteLine("Ok, this will ADD entries in your HOST file.");
                    AddEntriesToHostFile();
                    break;
                case "R":
                    Console.WriteLine("Ok, this will REMOVE entries from your HOST file.");
                    RemoveOurEntriesFromHostFile();
                    break;
                case "EXIT":
                    Environment.Exit(0);
                    break;
                default:
                    Console.WriteLine("Action switch not recognized.");
                    Console.WriteLine("Press ENTER to quit");
                    Console.ReadLine();
                    return;
            }

            Console.WriteLine("Done.");
            Console.WriteLine("Press ENTER to quit.");
            Console.ReadLine();
            return;
        }

        private static void WelcomeUser()
        {
            int padCount = 119;
            char padChar = '#';
            List<string> messageLines = new List<string>();
            messageLines.Add("#");
            messageLines.Add("Welcome to \"Modify Host File\"");
            messageLines.Add("This tool can execute 2 actions.");
            messageLines.Add("It can add specific entries to your Host file.");
            messageLines.Add("It can remove specific entries from your host file.");
            messageLines.Add("Entries are removed so you can get your original file back.");
            messageLines.Add("#");

            messageLines = messageLines.Select(p => p.PadForConsole(padChar, padCount)).ToList();

            foreach (string item in messageLines)
            {
                ConsoleColor originalColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(item);
                Console.ForegroundColor = originalColor;
            }
            Console.WriteLine();
            Console.WriteLine();
        }

        public static void RemoveOurEntriesFromHostFile()
        {
            HostEntriesToadd entries = new ModifyHostFile.HostEntriesToadd();
            try
            {
                using (StreamReader sr = new StreamReader(HostFileLocation))
                {
                    using (StreamWriter sw = new StreamWriter(HostFileTmpLocation, false))
                    {
                        string currentLine = string.Empty;
                        while ((currentLine = sr.ReadLine()) != null)
                        {
                            if (entries.Contains(currentLine))
                            {
                                //don't write the line
                                Console.WriteLine("Removed " + currentLine + " from host file");
                            }
                            else
                            {
                                //write the line
                                sw.WriteLine(currentLine);
                            }
                        }
                    }
                }
                ReplaceTheFiles(HostFileTmpLocation, HostFileLocation);
            }
            catch (System.UnauthorizedAccessException)
            {
                WarnForElevatedPermissions();
            }

        }

        public static void AddEntriesToHostFile()
        {
            HostEntriesToadd entries = new ModifyHostFile.HostEntriesToadd();
            try
            {
                using (StreamWriter sw = new StreamWriter(HostFileTmpLocation, false))
                {
                    sw.Write(File.ReadAllText(HostFileLocation));
                    foreach (string item in entries)
                    {
                        sw.WriteLine(item);
                        Console.WriteLine("Added " + item + " from host file");
                    }
                }
                ReplaceTheFiles(HostFileTmpLocation, HostFileLocation);
            }
            catch (System.UnauthorizedAccessException)
            {
                WarnForElevatedPermissions();
            }

        }

        private static void WarnForElevatedPermissions()
        {
            ConsoleColor originalColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Access Violation Exception");
            if (!IsAdministrator())
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("IsAdministrator: False");
                Console.ForegroundColor = originalColor;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("IsAdministrator: True");
                Console.ForegroundColor = originalColor;
            }
            Console.ForegroundColor = originalColor;
            Console.WriteLine("This tool will re-write your System's host file.");
            Console.WriteLine("Because your System's host file resides in a protected area on your computer");
            Console.WriteLine("this tool MUST run with elevated permissions, aka run as administrator.");

            Console.WriteLine("");
        }

        public static bool ReplaceTheFiles(string FileToReplaceWith, string FileToReplace)
        {
            try
            {
                File.Copy(FileToReplaceWith, FileToReplace, true);//overwrite the old file
                File.Delete(FileToReplaceWith);//delete the tmp file
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
            return true;
        }

        public static bool IsAdministrator()
        {
            return (new WindowsPrincipal(WindowsIdentity.GetCurrent()))
                    .IsInRole(WindowsBuiltInRole.Administrator);
        }

    }



    public class HostEntriesToadd : List<string>
    {
        public HostEntriesToadd()
        {
            this.Add("127.0.0.1 www.somesite.com");
            this.Add("127.0.0.1 someothersite.com");
            this.Add("127.0.0.1 blahblahblah.com");
            this.Add("127.0.0.1 damnthatdamn.com");
            this.Add("127.0.0.1 whateveryouwant.com");
        }
    }

    public static class StringHelpers
    {
        public static string PadForConsole(this string Text, char PadWith, int TotalLineLength)
        {
            List<string> texts = new List<string>();
            texts.Add(Text);
            if (texts[0].Length >= TotalLineLength - 2)
            {
                texts.Add(string.Empty);
                for (int i = 0; i < texts[0].Length; i++)
                {
                    if (texts.Last().Length < TotalLineLength - 2)
                    {
                        texts[texts.Count - 1] = texts[texts.Count - 1] + texts[0][i];
                    }
                    else
                    {
                        texts.Add(texts[0][i].ToString());
                    }
                }
                texts.RemoveAt(0);
            }

            for (int i = 0; i < texts.Count; i++)
            {
                string currentLine = texts[i].ToString();
                int leftPadCount = ((TotalLineLength - currentLine.Length) / 2);
                string leftPadString = new string(PadWith, leftPadCount);
                //int rightPadCount = (TotalLineLength - currentLine.Length) / 2;
                int rightPadCount = (TotalLineLength - currentLine.Length - leftPadCount);
                string rightPadString = new string(PadWith, rightPadCount);
                texts[i] = string.Format("{0}{1}{2}", leftPadString, texts[i], rightPadString);
            }
            string retVal = string.Empty;
            retVal = string.Join(System.Environment.NewLine, texts);
            return retVal;
        }
    }
}