python-3.x - 带循环的假值
问题描述
我正在创建一个工具来执行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)
解决方案
您没有正确使用 f 字符串。您将第一个空字符串作为 f 字符串,然后不要将要格式化的字符串设置为 f 字符串。
代替:
f''+newLine+'.{i}'
你的意思是:
f'{newLine}.{i}'
请注意它如何使用一个字符串(不是多个连接),并且应该替换的所有内容都在{}
s 中。
推荐阅读
- r - 将 csv 写入 s3,具有直接在存储桶内的凭据
- powershell - 如何通过powershell访问windows10中的mdb文件?
- javascript - 本地媒体访问受限,直到用户与 Firefox 中的页面交互
- javascript - Axios 拦截器:阻止对特定页面的访问
- reactjs - 状态数组(不是对象)和扩展运算符
- java - Java ProcessBuilder:如何抑制输出而不是重定向它
- c# - 切断来自服务器的传出 http 调用
- r - 从 URL 下载 csv
- slice - 为什么从较高的负索引切片到较小的负索引会给出空字符串?
- java - 使用自定义类型将 JSON 字符串转换为 Map