RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1095657
Accepted
JDo
JDo
Asked:2020-03-17 13:37:56 +0000 UTC2020-03-17 13:37:56 +0000 UTC 2020-03-17 13:37:56 +0000 UTC

从文本文件中提取和修改特定行

  • 772

有一个网络接口的文本文件:

auto eth0 bri0
iface eth0 inet static
    address 192.168.1.118/24
iface eth0.110 inet manual
    vlan-raw-device eth0
iface bri0 inet static
    address 192.168.110.1/24
    bridge_ports eth0.110
    bridge_stp on
    bridge_maxwait 10 ```

您需要从 eth0 获取地址并将其替换为另一个地址,例如 192.168.1.13。

我创建了一个获取所有接口和 ip 的类:

 public class IpChangeService
{
    private readonly string[] configFile;
    private List<string> interfaceName = new List<string>();
    private List<string> ipAddress = new List<string>();
    private string currentAdapter;

    public IpChangeService(string[] configFile, string currentAdapter)
    {
        this.configFile = configFile;
        this.currentAdapter = currentAdapter;
    }

    public (IList<string> iface, IList<string> ipAddress) GetCurrentInterfaces()
    {
        foreach (var line in configFile)
        {
            if (line.Contains("iface") && line.Contains("inet static"))
            {
                if (interfaceName != null)
                {
                    var str = line.Split(' ')[1] + " ";
                    var strWithoutSpaces = str.Replace(" ", "");
                    interfaceName.Add(strWithoutSpaces);
                }
            }

            if (interfaceName!=null && line.Contains("address"))
            {
                // see http://stackoverflow.com/questions/4890789/regex-for-an-ip-address
                ipAddress.Add(Regex.Match(line, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}").Value);
            }
        }

        return (interfaceName, ipAddress);
    }

    public int GetCurrentInterfaceIndex()
    {
        return interfaceName.IndexOf(currentAdapter);
    }

嗯,在主程序中我接收数据并尝试写下来,但是我觉得这样不正确,而且它不能正常工作(地址被歪斜插入)!而且我仍然不知道如何在没有通过索引硬编码的情况下正确选择 ip。

iface eth0 inet static
    address 192.168.1.118/24168.1.13/24

 private static void Main(string[] args)
    {
        var fileName = $"{AppDomain.CurrentDomain.BaseDirectory}interfaces";
        var inputLines = File.ReadAllLines(fileName, Encoding.Default);
        string interfaceName;
        string ipAddress;
        var ipChangeService = new IpChangeService(inputLines, "eth0");

        var currentIface = ipChangeService.GetCurrentInterfaces();
        var index = ipChangeService.GetCurrentInterfaceIndex();

        interfaceName = currentIface.iface[index];
        ipAddress = currentIface.ipAddress[0]; //FIXME: ХАРДКОД! 

        Console.WriteLine(interfaceName);

        var s2 = "192.168.1.113/24"; // ip на который заменяем строчку

        var configText = File.ReadAllText(fileName, Encoding.Default);

        configText = configText
            .Remove(configText.IndexOf(currentIface.ipAddress[0], StringComparison.Ordinal), ipAddress.Length)
            .Insert(configText.IndexOf(currentIface.ipAddress[0], StringComparison.Ordinal), s2);

        using (var file = new StreamWriter(fileName))
        {
            file.Write(configText);
        }
        Console.ReadKey();
    }

但最重要的是,目前尚不清楚如何从所有现有的(可能有几个)中准确地选择 ip 地址 eth0。然后替换这个特定的子字符串。

c#
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. OXYGEN
    2020-03-17T14:40:02Z2020-03-17T14:40:02Z

    试试这样:

    在入口

    在入口

    private void button2_Click(object sender, EventArgs e)
        {
            string searchFor = "iface eth0";
    
            bool IsFoundIface = false;
            string path = "data.txt";
    
            int foundindex=0;
            string port="";
            int size;
    
    
            if (File.Exists(path))
            {
                var dataFile = File.ReadAllLines(path);
                size= dataFile.Length;
    
                for (int i = 0; i < dataFile.Length; i++)
                {
                    if (dataFile[i].IndexOf(searchFor, StringComparison.Ordinal) != -1)
                    {
                        IsFoundIface = true;
                    }
                    if (IsFoundIface && dataFile[i+1].IndexOf("address", StringComparison.Ordinal) != -1)
                    {
                        var splitonport = dataFile[i + 1].Split('/');
                        foundindex = i + 1;
                        port = splitonport[1];
                        break;
                    }
    
                }
                string[] newData = new string[size];
                for (int i = 0; i < size; i++)
                {
                    if (i != foundindex)
                    {
                        newData[i] = dataFile[i];
                    }
                    else
                    {
                        newData[i] = string.Format("      address {0}/{1}", textBox1.Text, port);
                    }
                }
    
                File.WriteAllLines(path,newData);
            }
    
        }
    

    在我们得到的输出

    auto eth0 bri0
    iface eth0 inet static
          address 192.168.1.13/24
    iface eth0.110 inet manual
        vlan-raw-device eth0
    iface bri0 inet static
        address 192.168.110.1/24
        bridge_ports eth0.110
        bridge_stp on
        bridge_maxwait 10 ```
    
    • 1
  2. Best Answer
    EvgeniyZ
    2020-03-18T10:57:35Z2020-03-18T10:57:35Z

    如果您只需要更换,那么您可以这样做:

    • 我们制作了一个方法来搜索带有 Ip 的行:

      private static (string Line, int Index) GetIp(IList<string> lines, string search)
      {
          var adresses = lines.Select((Line, Index) => (Line, Index)).Where(x => x.Line.Contains("address"));
          foreach (var item in adresses)
          {
              for (int i = item.Index; i >= 0; i--)
              {
                  if (lines[i].Contains(search))
                  {
                      return item;
                  }
              }
          }
      
          return default;
      }
      

      我解释:

      1. 我们将所有行转换为(значение, индекс)并仅采用具有address. 结果,我们将在列表中包含所有带有 ip 地址及其索引的行。
      2. 我们将 ip 与接口进行比较 - 只需for从带有 ip 的线路所在的位置运行到所需线路的循环​​即可。如果接口与我们要查找的接口匹配,则返回 ip 及其索引。
    • 然后一切都很简单:

      • 我们从文件中逐行读取所有内容:

        var lines = File.ReadAllLines("File.txt"); 
        
      • 找到我们需要的ip:

        var (Line, Index) = GetIp(lines, "iface eth0");
        
      • 更改该行中的 ip 地址:

        lines[Index] = lines[Index].Replace(Line.Split().LastOrDefault(), "0.0.0.0");
        
      • 好吧,它还有待保存:

        File.WriteAllLines("File.txt", lines);
        

    结果:

    auto eth0 bri0
    iface eth0 inet static
        address 0.0.0.0
    iface eth0.110 inet manual
        vlan-raw-device eth0
    iface bri0 inet static
        address 192.168.110.1/24
        bridge_ports eth0.110
        bridge_stp on
        bridge_maxwait 10 ```
    
    • 1

相关问题

  • 使用嵌套类导出 xml 文件

  • 分层数据模板 [WPF]

  • 如何在 WPF 中为 ListView 手动创建列?

  • 在 2D 空间中,Collider 2D 挂在玩家身上,它对敌人的重量相同,我需要它这样当它们碰撞时,它们不会飞向不同的方向。统一

  • 如何在 c# 中使用 python 神经网络来创建语音合成?

  • 如何知道类中的方法是否属于接口?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    如何从列表中打印最大元素(str 类型)的长度?

    • 2 个回答
  • Marko Smith

    如何在 PyQT5 中清除 QFrame 的内容

    • 1 个回答
  • Marko Smith

    如何将具有特定字符的字符串拆分为两个不同的列表?

    • 2 个回答
  • Marko Smith

    导航栏活动元素

    • 1 个回答
  • Marko Smith

    是否可以将文本放入数组中?[关闭]

    • 1 个回答
  • Marko Smith

    如何一次用多个分隔符拆分字符串?

    • 1 个回答
  • Marko Smith

    如何通过 ClassPath 创建 InputStream?

    • 2 个回答
  • Marko Smith

    在一个查询中连接多个表

    • 1 个回答
  • Marko Smith

    对列表列表中的所有值求和

    • 3 个回答
  • Marko Smith

    如何对齐 string.Format 中的列?

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5