【问题标题】:How can I make python change the characters in a batch file?如何让 python 更改批处理文件中的字符?
【发布时间】:2022-11-22 19:33:28
【问题描述】:

我正在制作一个脚本来更改您的 dns,然后 ping 一个网站以测试延迟,我已经创建了一个包含所有 DNS 的列表,我想使用外部批处理脚本来更改 dns。但是,我是 python 的新手,我不知道如何让 python 从列表中获取数据并将其替换为批处理文件。这对我很有帮助,谢谢!

**Python脚本**

from tcp_latency import measure_latency

host = input("Enter host: ")

def pinger():
    latency = sum(measure_latency(host, port=80, runs=10, timeout=2.5))
    latency = latency/10
    print("Your average latency is",latency)

dns = ["1.1.1.1","1.0.0.1","8.8.8.8","8.8.4.4","9.9.9.9","149.112.112.112","208.67.222.222","208.67.220.220","8.26.56.26","8.20.247.20","185.228.168.9","185.228.169.9"]

批处理脚本

@echo off
cls
for /F "skip=3 tokens=1,2,3* delims= " %%G in ('netsh interface show interface') DO (
    IF "%%H"=="Disconnected" netsh interface set interface "%%J" enabled
    IF "%%H"=="Connected" netsh interface set interface "%%J" enabled
    echo %%J
    netsh interface ip set dns %%J static 1.1.1.1
)

我还没有尝试过任何方法

【问题讨论】:

    标签: python python-3.x networking


    【解决方案1】:

    简单的字符串替换应该可以很好地工作

    dns = ["1.1.1.1","1.0.0.1","8.8.8.8","8.8.4.4","9.9.9.9","149.112.112.112","208.67.222.222","208.67.220.220","8.26.56.26","8.20.247.20","185.228.168.9","185.228.169.9"]
    
    # Assumes .bat and .py scripts are in the same directory
    bat_file = "tester.bat"
    
    # Read original .bat file
    with open(bat_file, "r") as fs:
        bat_str = fs.read()
    
    base_name = bat_file.split(".")[0]
    for dns_ip in dns:
        new_bat_str = bat_str.replace("1.1.1.1", dns_ip)
        # Parse new name for .bat file
        new_bat_file = f"{base_name}_dns_{dns_ip.replace('.', '')}.bat"
        with open(new_bat_file, "w") as fs:
            fs.write(new_bat_str)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多