C#修改VMware虚拟网络设置中的IP地址映射

近期为了项目需要,需要用exe,一键修改WMware中,网卡的NAT 模式中,网关IP,映射传入端口,自动修改虚拟机IP地址,虚拟端口,描述。

 

WMware实际是执行了 dos命令,然后再将执行完毕的数据,保存在注册表,方便下一次读取,并在WMware中的虚拟网络编辑器中显示。

 

所以,修改WMware的虚拟网络编辑器中的内容,就需要修改两处,一处是执行dos命令,一处是修改注册表。

 

打开cmd,输入下面的命令,便可以修改 VMware Network Adapter VMnet8  的子网IP与子网掩码

netsh interface ip set address "VMware Network Adapter VMnet8" static " 192.168.1.100 255.255.255.0

 

然后需要修改注册表:

\HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMnetLib\\VMnetConfig\\vmnet8

中的  IPSubnetAddress,为 IP子网掩码,

 

\HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMnetLib\\VMnetConfig\\vmnet8\\NAT 中的 GatewayIPAddress 为网关。修改即可

 

在cmd 下输入一下命令,即可修改网络映射的问题:

netsh interface portproxy add v4tov  listenport=6011 protocol=tcp  connectaddress=192.168.221.201 connectport=6090

connectaddress:需要代理访问到的远程IP

connectport:远程代理端口

listenport:为本地指定绑定端口(可以与connectport不一致)

Protocol:  是TCP 还是 udp 方式

 

然后,写入注册表中:

TCP模式的话,

\HKEY_LOCAL_MACHINE\SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMnetLib\\VMnetConfig\\vmnet8\\NAT\\TCPForward

那么修改这两处的IP就完成了。

 

/********************************************************************
	created:	2019/08/14
	created:	14:8:2019   11:19
	filename: 	D:\MY_Source\Modify_WMWare_Net\ModifyVMNet\Form1.cs
	file path:	D:\MY_Source\Modify_WMWare_Net\ModifyVMNet
	file base:	Form1
	file ext:	cs
	author:		qq249191508.com
	
	purpose:	WMware虚拟网络编辑器 exe中生成:  main_IP.txt, mapping_IP.txt   两个文件。
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using Microsoft;
using Microsoft.Win32;


namespace ModifyVMNet
{
    public partial class Form1 : Form
    {
        private List<MapIP> m_listMapIP = new List<MapIP>();
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 验证IP
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool IsCorrectIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        private void WriteMainIP2Reg(List<string> listMainIP)
        {
            RegistryKey key = Registry.LocalMachine;
            RegistryKey software = null;

            software = key.CreateSubKey("SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMnetLib\\VMnetConfig\\vmnet8");
            software.SetValue("IPSubnetAddress", listMainIP[0], RegistryValueKind.String);


            software = key.CreateSubKey("SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMnetLib\\VMnetConfig\\vmnet8\\NAT");
            software.SetValue("GatewayIPAddress", listMainIP[1], RegistryValueKind.String);
        }

        private void WriteMapIP2Reg(string strMainPort, string strVirtualIP, string strVirtualPort, string strNetType)
        {
            RegistryKey key = Registry.LocalMachine;

            byte[] bytes = Encoding.ASCII.GetBytes("222");

            string strNetTemp = strNetType.ToUpper();
            RegistryKey software = null;
            if (strNetTemp == "TCP")
            {
                software = key.CreateSubKey("SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMnetLib\\VMnetConfig\\vmnet8\\NAT\\TCPForward");
            }
            else
            {
                software = key.CreateSubKey("SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMnetLib\\VMnetConfig\\vmnet8\\NAT\\UDPForward");
            }

            software.SetValue(strMainPort, strVirtualIP + ":" + strVirtualPort, RegistryValueKind.String);
            software.SetValue(strMainPort+ "Description", bytes, RegistryValueKind.Binary);

            key.Close();
        }

        private string AppPath()
        {
            string strPath = System.Windows.Forms.Application.StartupPath;
            if (strPath.Substring(strPath.Length - 1, 1) == "\\")
            {
                strPath = strPath.Substring(0, strPath.Length - 1);
            }

            return strPath;
        }

        public void ExecuteReg(string regPath)
        {
            if (File.Exists(regPath))
            {
                regPath = @"""" + regPath + @"""";
                Process.Start("regedit", string.Format(" /s {0}", regPath));
            }
        }

        public string ExecCmd(string command, bool returnError = false, bool noReturn = false)
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.StandardInput.WriteLine(command);
            process.StandardInput.WriteLine("exit");
            string text = "";
            bool flag = !noReturn;
            if (flag)
            {
                bool flag2 = !returnError;
                if (flag2)
                {
                    text = process.StandardOutput.ReadToEnd();
                }
                else
                {
                    text = process.StandardError.ReadToEnd();
                    bool flag3 = text == "";
                    if (flag3)
                    {
                        text = process.StandardOutput.ReadToEnd();
                    }
                }
            }
            return text;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Btn_Modify_Click(object sender, EventArgs e)
        {

            try
            {
                // 读取 主机地址
                string strMainIPText = AppPath() + "\\main_IP.txt";
                List<string> listGateNet = new List<string>();
                using (StreamReader sr = new StreamReader(strMainIPText))
                {
                    string line;

                    // 从文件读取并显示行,直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        if(line.Length < 5)
                        {
                            continue;
                        }

                        if( !IsCorrectIP(line) )
                        {
                            throw new Exception("在 main_IP.txt 中请输入正确的IP");
                        }

                        listGateNet.Add(line);
                    }
                }

                string strCmdIP = "netsh interface ip set address \"VMware Network Adapter VMnet8\" static " + listGateNet[1] + " 255.255.255.0";


                // 执行各个端口映射。
                ExecCmd(strCmdIP, false, false);

                // 写入注册表
                WriteMainIP2Reg(listGateNet);


                // 读取 端口映射表
                string strIPText = AppPath() + "\\mapping_IP.txt";
                using (StreamReader sr = new StreamReader(strIPText))
                {
                    string line;

                    // 从文件读取并显示行,直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        if(line.Length < 5)
                        {
                            continue;
                        }
                        string[] strOneline = line.Split(',');
                        if (strOneline.Length < 5)
                        {
                            continue;
                        }

                        MapIP tempMapIP = new MapIP();
                        tempMapIP.MainPort = strOneline[0];
                        tempMapIP.NetType = strOneline[1];
                        tempMapIP.VirtualIP = strOneline[2];
                        tempMapIP.VierualPort = strOneline[3];
                        tempMapIP.Describe = strOneline[4];

                        m_listMapIP.Add(tempMapIP);
                    }
                }

                // 我的博客地址: http://www.qq249191508.com
                for (int i = 0; i < m_listMapIP.Count; i++)
                {
                    //netsh interface portproxy add v4tov4 listenport=6020  connectaddress=192.168.220.135 connectport=8888 protocol=tcp

                    string strMainPort = " listenport=" + m_listMapIP[i].MainPort;
                    string strNetType = " protocol=" + m_listMapIP[i].NetType;
                    string strVirtualIP = "  connectaddress=" + m_listMapIP[i].VirtualIP;
                    if( !IsCorrectIP( m_listMapIP[i].VirtualIP ) )
                    {
                        throw new Exception("在 mapping_IP.txt中,请输入正确的虚拟机IP.");
                    }

                    string strVirtualPort = " connectport=" + m_listMapIP[i].VierualPort;

                    string strCmd = "netsh interface portproxy add v4tov " + strMainPort + strNetType + strVirtualIP + strVirtualPort;

                    // 执行各个端口映射。
                    ExecCmd(strCmd, false, false);

                    WriteMapIP2Reg(m_listMapIP[i].MainPort, m_listMapIP[i].VirtualIP, m_listMapIP[i].VierualPort, m_listMapIP[i].NetType);
                }

                lb_view.Text = "成功...";
            }
            catch (Exception ex)
            {
                lb_view.Text = ex.ToString();

                // 向用户显示出错消息
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(ex.Message);
            }
        }
    }
}

 

main_IP.txt文件内容:

192.168.221.0
192.168.221.1

mapping_IP.txt文件内容:

6011,tcp,192.168.221.201,6090,描述
6012,tcp,192.168.221.202,6090,描述
6013,tcp,192.168.221.203,6090,描述
6014,tcp,192.168.221.204,6090,描述

这两个文件,在exe 同级目录下

源码我在百度网盘也放了一份,解压密码为: www.qq249191508.com

链接: https://pan.baidu.com/s/1Sl0Q9193YLcoj4Uct5avPw 提取码: 556s 

--------------

最后,请关注我的博客吧: http://www.qq249191508.com. 坝坝虎个人博客

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chen249191508

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值