当前位置: 首页 > article >正文

C# Exe + Web 自动化 (BitComet 绿灯 自动化配置、设置)

BitComet GreenLight,内网黄灯转绿灯 (HighID), 增加p2p连接率提速下载-CSDN博客
前两天写个这个,每次开机关机后要重来一遍很麻烦的索性写个自动化。


先还是按照上面的教程自己制作一遍,留下Luck 以及 路由器相关的 端口记录信息。

(因为自动化我没写创建的逻辑,只是写了更改端口号的逻辑,所以基础信息条目需要存在。)

基于更改信息,自动化主要逻辑如下

1、取得Luck 设定好的端口

2、复制到路由器相关端口映射页面保存

3、启动BT,设置新的端口映射数据


完整代码如下:

 public class NetworkManagerExt
 {
     private string HostPort { get; set; }
     private string RemotePort { get; set; }
     private const string BitCometPath = @"D:\Program Files\BitComet\BitComet.exe";
     private const string LuckyPath = @"D:\Lucky\lucky.exe";
     private const string RouterUrl = "http://192.168.0.1/";
     private const string RouterPassword = "你自己的密码";
     private const string LuckyUrl = "http://127.0.0.1:16601/#/login";
     private const string LuckyPassword = "666"; //luck 默认密码
     private const int DefaultTimeoutSeconds = 30;

     public void ConfigureNetwork()
     {
         StartLuckyAndConfigureRouter();
     }

     public void StartBitComet()
     {
         if (!string.IsNullOrEmpty(RemotePort))
         {
             ConfigureBitComet(RemotePort);
         }
         else
         {
             Console.WriteLine("Error: RemotePort not set. Cannot configure BitComet.");
         }
     }

     private Process GetOrStartProcess(string exePath)
     {
         string processName = System.IO.Path.GetFileNameWithoutExtension(exePath);
         Process[] processes = Process.GetProcessesByName(processName);
         return processes.Length > 0 ? processes[0] : Process.Start(exePath);
     }

     private void ConfigureBitComet(string port)
     {
         Process calc = Process.Start(BitCometPath);
         AutomationElement mainExe = null;

         // 等待BitComet窗口出现
         DateTime startTime = DateTime.Now;
         TimeSpan timeout = TimeSpan.FromSeconds(DefaultTimeoutSeconds);

         while (mainExe == null)
         {
             if (DateTime.Now - startTime > timeout)
             {
                 throw new TimeoutException("Timeout waiting for BitComet window to appear");
             }

             AutomationElementCollection elementCollection = AutomationElement.RootElement.FindAll(
                 TreeScope.Children,
                 new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window)
             );

             foreach (AutomationElement item in elementCollection)
             {
                 if (item.Current.Name.Contains("BitComet", StringComparison.OrdinalIgnoreCase))
                 {
                     mainExe = item;
                     break;
                 }
             }

             if (mainExe == null)
             {
                 System.Threading.Thread.Sleep(500); // 短暂等待后重试
             }
         }

         WindowPattern windowPattern = (WindowPattern)mainExe.GetCurrentPattern(WindowPattern.Pattern);
         windowPattern.SetWindowVisualState(WindowVisualState.Normal);

         System.Windows.Forms.SendKeys.SendWait("^p");
         bool setOperated = false;
         startTime = DateTime.Now;

         while (!setOperated)
         {
             if (DateTime.Now - startTime > timeout)
             {
                 throw new TimeoutException("Timeout waiting for BitComet settings dialog");
             }

             var tempWindow = mainExe.FindFirst(
                 TreeScope.Children,
                 new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window)
             );

             if (tempWindow != null)
             {
                 var tempPane = tempWindow.FindFirst(
                     TreeScope.Subtree,
                     new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)
                 );

                 var onButtonPane = tempWindow.FindFirst(
                     TreeScope.Children,
                     new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)
                 );

                 if (tempPane != null)
                 {
                     ValuePattern valuePattern = (ValuePattern)tempPane.GetCurrentPattern(ValuePattern.Pattern);
                     valuePattern.SetValue(port);
                     setOperated = true;

                     InvokePattern invokePattern = (InvokePattern)onButtonPane.GetCurrentPattern(InvokePattern.Pattern);
                     invokePattern.Invoke();
                 }
             }

             if (!setOperated)
             {
                 System.Threading.Thread.Sleep(500); // 短暂等待后重试
             }
         }
     }

     private void StartLuckyAndConfigureRouter()
     {
         Process calc = GetOrStartProcess(LuckyPath);
         AutomationElement mainExe = null;

         // 等待Lucky窗口出现
         DateTime startTime = DateTime.Now;
         TimeSpan timeout = TimeSpan.FromSeconds(DefaultTimeoutSeconds);

         while (mainExe == null)
         {
             if (DateTime.Now - startTime > timeout)
             {
                 throw new TimeoutException("Timeout waiting for Lucky window to appear");
             }

             var element = AutomationElement.RootElement.FindFirst(
                 TreeScope.Subtree,
                 new PropertyCondition(AutomationElement.NameProperty, "万吉")
             );

             if (element != null)
             {
                 mainExe = element;
             }
             else
             {
                 System.Threading.Thread.Sleep(500); // 短暂等待后重试
             }
         }

         using (IWebDriver driver = new EdgeDriver())
         {
             // 设置隐式等待,适用于所有元素查找
             driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

             // 创建显式等待对象
             WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(DefaultTimeoutSeconds));

             // 登录Lucky
             driver.Navigate().GoToUrl(LuckyUrl);

             // 等待输入框出现并输入密码
             var inputElements = wait.Until(d => d.FindElements(By.CssSelector("input[placeholder='默认666']")));
             foreach (var item in inputElements)
             {
                 item.Clear();
                 item.SendKeys(LuckyPassword);
             }

             // 等待登录按钮出现并点击
             IWebElement loginButton = wait.Until(d => {
                 var button = d.FindElement(By.CssSelector("button.el-button.el-button--primary.is-round"));
                 return button.Text == "登录" ? button : null;
             });
             loginButton.Click();

             // 获取端口信息
             driver.Navigate().GoToUrl("http://127.0.0.1:16601/#/stun");

             // 等待第一个IP端口信息出现
             IWebElement firstIpSpan = wait.Until(d => d.FindElement(By.XPath(
                 "/html/body/div[1]/div/section/section/section/main/div/div/div[1]/div/div[1]/div[1]/div[1]/div/div/div/div/table/tbody/tr[2]/td[2]/span[1]/span")));

             // 等待第二个IP端口信息出现
             IWebElement secondIpSpan = wait.Until(d => d.FindElement(By.XPath(
                 "/html/body/div[1]/div/section/section/section/main/div/div/div[1]/div/div[1]/div[1]/div[1]/div/div/div/div/table/tbody/tr[2]/td[2]/span[3]/span")));

             string firstIpPort = firstIpSpan.Text;
             string secondIpPort = secondIpSpan.Text;

             if (!string.IsNullOrEmpty(firstIpPort) && !string.IsNullOrEmpty(secondIpPort))
             {
                 HostPort = firstIpPort.Split(':')[1];
                 RemotePort = secondIpPort.Split(':')[1];

                 // 配置路由器
                 ConfigureRouter(driver, wait);
             }
         }
     }

     private void ConfigureRouter(IWebDriver driver, WebDriverWait wait)
     {
         driver.Navigate().GoToUrl(RouterUrl);

         // 等待密码输入框出现
         IWebElement routerPwd = wait.Until(d => d.FindElement(By.XPath("/html/body/div[6]/div[2]/ul/li[2]/ul/li[1]/input")));
         routerPwd.Clear();
         routerPwd.SendKeys(RouterPassword);

         // 等待登录按钮出现并点击
         IWebElement loginButton = wait.Until(d => d.FindElement(By.XPath("/html/body/div[6]/div[2]/ul/li[3]/input")));
         loginButton.Click();

         // 等待功能1按钮出现并点击
         IWebElement func1 = wait.Until(d => d.FindElement(By.XPath("/html/body/div[3]/div[2]/div[2]/ul/li[3]/div/i[2]")));
         func1.Click();

         // 等待功能2按钮出现并点击
         IWebElement func2 = wait.Until(d => d.FindElement(By.XPath("/html/body/div[3]/div[2]/div[1]/div[3]/div[2]/div[1]/div/div[2]/div[1]/div[8]/div/div/input[3]")));
         func2.Click();

         // 等待功能3按钮出现并点击
         IWebElement func3 = wait.Until(d => d.FindElement(By.XPath("/html/body/div[3]/div[2]/div[1]/div[3]/div[2]/div[1]/div[2]/div/div[3]/table/tbody/tr[2]/td[7]/i")));
         func3.Click();

         // 设置外部端口
         IWebElement outport = wait.Until(d => d.FindElement(By.XPath("/html/body/div[3]/div[2]/div[1]/div[3]/div[2]/div[1]/div[2]/div/div[3]/table/tbody/tr[2]/td[3]/input")));
         outport.Clear();
         outport.SendKeys(HostPort);

         // 设置内部端口
         IWebElement selfport = wait.Until(d => d.FindElement(By.XPath("/html/body/div[3]/div[2]/div[1]/div[3]/div[2]/div[1]/div[2]/div/div[3]/table/tbody/tr[2]/td[4]/input")));
         selfport.Clear();
         selfport.SendKeys(RemotePort);

         // 保存路由器设置
         IWebElement saveButton = wait.Until(d => d.FindElement(By.XPath("/html/body/div[3]/div[2]/div[1]/div[3]/div[2]/div[1]/div[2]/div/div[3]/table/tbody/tr[2]/td[7]/input[1]")));
         saveButton.Click();
     }
 }

路由器 Web 部分(ConfigureRouter()方法),需要自行Web 页面 元素 XPath 取得慢慢调整,我的路由器是 TPLink ,TL-WDR8500,配置界面大致如下:

调用代码
 

   static void Main(string[] args)
   {
       var networkManager = new NetworkManagerExt();
       networkManager.ConfigureNetwork();
       networkManager.StartBitComet();
   }

这样 每次开机执行一下这个exe,保障BT 是绿灯,前面配置设置那些步骤全自动化。

需要的包和引用如下:(基于 .net 9.0 编译通过,测试通过)

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <ApplicationManifest>app.manifest</ApplicationManifest>
  </PropertyGroup>
	<ItemGroup>
		<FrameworkReference Include="Microsoft.WindowsDesktop.App" />
		<PackageReference Include="Selenium.WebDriver" Version="4.29.0" />
	</ItemGroup>
</Project>



P.S :Windows 10 上的应用程序,抓取窗体、控件类型等等信息,采用的工具是

Accessibility Insights for Windowshttps://accessibilityinsights.io/docs/windows/overview/


http://www.kler.cn/a/591868.html

相关文章:

  • 如何创建并保存HTML文件?零基础入门教程
  • 深入理解 Vue 的响应式原理:从 Vue 2 到 Vue 3
  • Tailwind CSS 学习笔记(一)
  • LeetCode 第11题~第13题
  • Express.js 是一个轻量级、灵活且功能强大的 Node.js Web 应用框架
  • 【保姆级教程】Windows系统+ollama+Docker+Anythingllm部署deepseek本地知识库问答大模型,可局域网多用户访问
  • 单片机开发资源分析的实战——以STM32G431RBT6为例子的单片机资源分析
  • Qt6.8实现麦克风音频输入音频采集保存wav文件
  • 代码随想录算法训练营第三十二天 | 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
  • 【第15届蓝桥杯】软件赛CB组省赛
  • 3 C#调用visionPro的toolblock的步骤
  • Redis——事务实现以及应用场景
  • Linux下使用cgroup限制进程IO
  • 【Godot】CanvasItem
  • 神经外科手术规划的实现方案及未来发展方向
  • vue 获取当前时间并自动刷新
  • Spring 创建bean的流程
  • java项目40分钟后token失效问题排查(40分钟后刷新页面白屏)
  • 20242817李臻《Linux⾼级编程实践》第四周
  • [spring]集成junit