os.system和os.popen

import os
# os.system直接输出
os.system("ping 127.0.0.1")

  

输出:

���� Ping 127.0.0.1 ���� 32 �ֽڵ�����:
���� 127.0.0.1 �Ļظ�: �ֽ�=32 ʱ��<1ms TTL=64
���� 127.0.0.1 �Ļظ�: �ֽ�=32 ʱ��<1ms TTL=64
���� 127.0.0.1 �Ļظ�: �ֽ�=32 ʱ��<1ms TTL=64
���� 127.0.0.1 �Ļظ�: �ֽ�=32 ʱ��<1ms TTL=64

127.0.0.1 �� Ping ͳ����Ϣ:
���ݰ�: �ѷ��� = 4���ѽ��� = 4����ʧ = 0 (0% ��ʧ)��
�����г̵Ĺ���ʱ��(�Ժ���Ϊ��λ):
��� = 0ms��� = 0ms��ƽ�� = 0ms

 

import os

# os.popen手动输出
ping = os.popen("ping 127.0.0.1")
out = ping.read()
print(out)

  

输出:

正在 Ping 127.0.0.1 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64

127.0.0.1 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 0ms,最长 = 0ms,平均 = 0ms

 

或者:

import os

# os.popen手动输出
ping_list = os.popen("ping 127.0.0.1").readlines()
print(ping_list)

  

输出:

['\n', '正在 Ping 127.0.0.1 具有 32 字节的数据:\n', '来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128\n', '来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128\n', '来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128\n', '来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128\n', '\n', '127.0.0.1 的 Ping 统计信息:\n', ' 数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),\n', '往返行程的估计时间(以毫秒为单位):\n', ' 最短 = 0ms,最长 = 0ms,平均 = 0ms\n']

 

案例:扫描局域网内ip

import _thread
import time
import os


def ping_ip(ip):
    # windows
    _cmd = "ping %s -n 1" % ip
    # Linux
    # _cmd = "ping %s -c 1" % ip
    os.system(_cmd)


if __name__ == '__main__':
    # 来自 192.168.1.2 的回复: 字节=32 时间=41ms TTL=64
    ip_template = '192.168.50.'
    for i in range(1, 255):
        ip = ip_template + str(i)
        # 多线程方法
        _thread.start_new_thread(ping_ip, (ip,))
        time.sleep(0.1)

  

posted @ 2018-02-05 17:40  安迪9468  阅读(275)  评论(0编辑  收藏  举报