代码示例
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace SystemInfoTest
{
/// <summary>
/// @author scl
/// linux ip动态修改
/// </summary>
public class NetConfigTest
{
/*
1. su root //切换至特权模式,并输入密码
2. vim /etc/sysconfig/network-scripts/ifcfg-ens33 //进入网卡ens33的配置页面
3. i //输i进入文件编辑模式(i=insert)
4.1 BOOTPROTO="static" //修改:将dhcp修改为static,修改后为BOOTPROTO=static
4.2 ONBOOT=yes //修改为yes, 网卡开机自启动
4.3 IPADDR="xxx.xxx.xxx.xxx" //新增:配置静态IP地址,按需配置
4.4 NETMASK="255.xxx.xxx.xxx" //新增:配置子网掩码
4.5 GATEWAY="xxx.xxx.xxx.xxx" //新增:配置网关
4.6 DNS1="xxx.xxx.xxx.xxx" //新增:配置DNS
5. Esc或Ctrl+c //退出文件编辑模式
6. :wq //保存文件修改并退出
7. service network restart //重启网卡
8. ip add //查看网卡ens33的IP地址已经变成配置的静态IP地址
9. ping xxx.xxx.xxx.xxx //ping自己,ping网关,验证网络能通
*/
public static void Main(string[] args)
{
// 网络配置文件
string netConfig = "/etc/sysconfig/network-scripts/ifcfg-ens33";
// 备份配置文件
string netConfigBak = "/etc/sysconfig/network-scripts/ifcfg-ens33.bak";
Console.WriteLine(netConfig);
Console.WriteLine("---------------------------------");
// 检测配置文件是否存在
if (!File.Exists(netConfig))
{
throw new FileNotFoundException($"网络配置文件未找到,请确认路径是否存在:{netConfig}");
}
// 备份配置文件
// 检测备份文件是否存在
if (!File.Exists(netConfigBak)) File.Copy(netConfig, netConfigBak); // 不存在,拷贝
else File.Copy(netConfig, netConfigBak, true); // 覆盖
// 操作备份文件
StreamReader bakReader = new StreamReader(File.OpenRead(netConfigBak), Encoding.UTF8);
StreamWriter srcWriter = new StreamWriter(File.OpenWrite(netConfig), Encoding.UTF8);
srcWriter.AutoFlush = true;
// 配置类
NetConfigInfo configInfo = new();
configInfo.Ipaddr = "192.168.153.146";
configInfo.Gateway = "192.168.153.3";
configInfo.NetMask = "255.255.255.0";
configInfo.DnsList = new List<string>() {"8.8.8.8", "114.114.114.114"};
// todo 参数验证
while (!bakReader.EndOfStream)
{
var readLine = bakReader.ReadLine();
if (readLine == null || !readLine.Contains("=")) continue;
readLine = readLine.TrimStart();
// 处理DNS,外部配置有dns,内部dns直接遗弃
if (configInfo.DnsList is {Count: > 0} && readLine.StartsWith("DNS", StringComparison.CurrentCultureIgnoreCase)) continue;
switch (readLine.Split("=")[0].ToLower())
{
case "bootproto":
readLine = "BOOTPROTO=static";
break;
case "onboot":
readLine = "ONBOOT=yes";
break;
case "ipaddr":
readLine = string.IsNullOrEmpty(configInfo.Ipaddr) ? readLine : $"IPADDR={configInfo.Ipaddr}";
break;
case "netmask":
readLine = string.IsNullOrEmpty(configInfo.NetMask) ? readLine : $"NETMASK={configInfo.NetMask}";
break;
case "gateway":
readLine = string.IsNullOrEmpty(configInfo.Gateway) ? readLine : $"GATEWAY={configInfo.Gateway}";
break;
default:
break;
}
srcWriter.WriteLine(readLine);
}
// 文本末尾添加dns配置
if (configInfo.DnsList is {Count: >0})
{
for (int i = 0; i < configInfo.DnsList.Count; i++)
{
Console.WriteLine($"DNS{i + 1}={configInfo.DnsList[i]}");
srcWriter.WriteLine($"DNS{i + 1}={configInfo.DnsList[i]}");
}
}
// 关闭流
bakReader.Close();
srcWriter.Close();
// 执行网络重启
// 命令信息
RestartNetWork();
// 延迟100毫秒检测状态
Thread.Sleep(100);
// 检测网络重启情况
var startFlag = CheckNetStatus();
if (startFlag) Console.WriteLine("网络服务重启成功");
// 网络服务启动失败,恢复到上次网络配置文件
Console.WriteLine("------------test----------------");
if (!startFlag)
{
Console.WriteLine("网络服务重启失败");
// 重启失败将原来的备份文件覆盖
File.Copy(netConfigBak, netConfig, true);
// 重启网络
RestartNetWork();
var status = CheckNetStatus();
Console.WriteLine($"回退之前网络配置状态:{status}");
}
}
private static bool CheckNetStatus()
{
var startInfo = new ProcessStartInfo("systemctl", "status network") {RedirectStandardOutput = true};
var process = Process.Start(startInfo);
// 启动标志位
bool startFlag = false;
if (process != null)
{
Console.WriteLine("检测网络服务命令执行成功");
using (var sr = process.StandardOutput)
{
while (!sr.EndOfStream)
{
var lineMsg = sr.ReadLine()?.TrimStart();
if (lineMsg != null && lineMsg.StartsWith("Active"))
{
// 激活数据判断
// Active: active (exited) since Sat 2022-04-02 11:30:09 CST; 23ms ago
var activeLineArr = lineMsg.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (activeLineArr.Length > 2 && activeLineArr[1].Equals("active")) startFlag = true;
break;
}
}
if (!process.HasExited)
{
Console.WriteLine("关闭资源");
sr.Close();
process.Kill();
}
}
}
return startFlag;
}
private static void RestartNetWork()
{
var startInfo = new ProcessStartInfo("systemctl", "restart network") {RedirectStandardOutput = true};
var process = Process.Start(startInfo);
if (process != null)
{
Console.WriteLine("重启网络服务成功");
using (var sr = process.StandardOutput)
{
var msg = sr.ReadToEnd();
Console.WriteLine(msg);
if (!process.HasExited)
{
Console.WriteLine("关闭");
process.Kill();
}
}
}
}
}
public class NetConfigInfo
{
/// <summary>
/// Ip地址
/// </summary>
public string Ipaddr { get; set; }
/// <summary>
/// 网关
/// </summary>
public string Gateway { get; set; }
/// <summary>
/// 子网掩码
/// </summary>
public string NetMask { get; set; }
/// <summary>
/// DNS
/// </summary>
public List<string> DnsList { get; set; }
}
}