簡體   English   中英

從 txt 文件 Ping 地址

[英]Ping addresses from a txt file

嘗試從文件 ping 地址並將結果打印給最終用戶。

腳本:

import sys
import ipaddress
import subprocess
import os
import re
import sys
from tabulate import tabulate
#Main routine
def main():
    address = sys.argv[1]
    pingthis = ['ping', '-c', '1', address]
    r = (subprocess.run(pingthis, stdout=subprocess.PIPE, check=True,).stdout.decode('utf-8'))
    pingtable = tabulate([[address, (re.search(r'time=(\d+)', r).group(1))]], headers=["IP", "TimeToPing (ms)"], tablefmt="simple",)
    pingfile = open("pingfile.txt", "r+")
    with open("pingfile.txt", "r") as fin:
        for line in pingfile:
            response = (subprocess.run(pingthis, stdout=subprocess.PIPE, check=True,).stdout.decode('utf-8'))
            if response == 0:
                with open("pingfile.txt", "w") as fout:
                     fin.write(pingfile)

    print(pingtable)
#Call main() function
if __name__ == "__main__":
    main()

raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['ping', '-c', '1', 'ingfile.txt']' returned non-zero exit status 2 . 還有更多我打開 pingfile.txt 並寫入時需要添加?為什么當代碼顯示address時, ingfile.txt會出錯?

您的語法熒光筆顯示您在open語句中的“w”之后有 2 個“”,您的引號不平衡

with open("pingfile.txt", "r") as fin:
    for line in pingfile:
        response = (subprocess.run(pingthis, stdout=subprocess.PIPE, check=True,).stdout.decode('utf-8'))
        if response == 0:
            with open("pingfile.txt", "w"") as fout: # <-- this line
                 fin.write(pingfile)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM