Python - ping for for循环

时间:2016-06-27 02:10:02

标签: python windows python-3.x networking

我尝试ping for循环,它只对最后一个数字做了这个问题 在这种情况下,ping只对x.x.x.4地址

进行
import subprocess
import socket

ipl = socket.gethostbyname(socket.gethostname())
seg1, seg2, seg3, seg4 = ipl.split(".")
stip = seg1 + "." + seg2 + "." + seg3 + "."

i = 0
for i in range(1,5):
    cmd = "ping -n 1 " + stip + str(i)
    print(cmd)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout) = p.communicate()
    fiw = open("1.txt", 'w')
    fiw.write(str(stdout))

2 个答案:

答案 0 :(得分:0)

fiw = open("1.txt", 'w')更改为fiw = open("1.txt", '+a')

import subprocess
import socket

ipl = socket.gethostbyname(socket.gethostname())
seg1, seg2, seg3, seg4 = ipl.split(".")
stip = seg1 + "." + seg2 + "." + seg3 + "."

i = 0
for i in range(1,5):
    cmd = "ping -n 1 " + stip + str(i)
    print(cmd)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout) = p.communicate()
    fiw = open("1.txt", 'w')
    fiw.write(str(stdout))

输出到文本文件是我希望2管道ips的功能之一,它用UP响应

答案 1 :(得分:0)

fiw = open("1.txt",'w')
for i in range(1,5):
    cmd = "ping -n 1 " + stip + str(i)
    print(cmd)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout) = p.communicate()
    fiw.write(str(stdout))
fiw.close()

尝试更改代码