首页 > 解决方案 > 带循环的假值

问题描述

我正在创建一个工具来执行host多个 IP 范围的命令。这些 IP 范围与我的脚本位于同一文件夹中的文件中。

我可以使用 IP 读取我的文件,我可以创建我的线程,但代码执行i不像循环(作为变量):

找不到主机 10.123.204.{i}:3(NXDOMAIN)

这是我的代码:

import threading
from argparse import ArgumentParser
from itertools import product
import subprocess


def check_host(host: str):
    subprocess.run(["host", host])
    #status = 'up' if return_code == 0 else 'down'
    #print(f'{host} : is {status}')


def start_threads(addr_range):
    for addr in addr_range:
        t = threading.Thread(target=check_host, args=(addr,), 
                             name=f'Thread:{addr}')
        t.start()
        yield t


def ping_network_range(net_class: str):
    myFile=open('../findRoute/ip.txt', 'r')
    net_class = net_class.upper()
    for line in myFile:
        if net_class == 'A':
            newLine=line+''
            newLine=newLine[:-1]
            threads = list(start_threads(f''+newLine+'.{i}' for i in range(256)))#here is the error
        elif net_class == 'B':#TBD
            threads = list(start_threads(f'127.0.{i}.{j}' 
                                        for i, j in product(range(256), range(256))))
        else:
            raise ValueError(f'Wrong network class name {net_class}')

    for t in threads:
        t.join()


if __name__ == "__main__":
    parser = ArgumentParser(description='Host network addresses by network class')
    parser.add_argument('-c', '--nclass', choices=('A', 'B'), 
                        required=True, help='Choose class A or B')
    args = parser.parse_args()
    ping_network_range(args.nclass)

标签: python-3.x

解决方案


您没有正确使用 f 字符串。您将第一个空字符串作为 f 字符串,然后不要将要格式化的字符串设置为 f 字符串。

代替:

f''+newLine+'.{i}'

你的意思是:

f'{newLine}.{i}'

请注意它如何使用一个字符串(不是多个连接),并且应该替换的所有内容都在{}s 中。


推荐阅读