用python语言设计一个ping程序设计,要求Ping后不加参数实现四次ping。Ping后增加“-t”参数实现无限次ping。
时间: 2024-03-26 19:38:50 浏览: 85
Ping_python_ping_
好的,下面是一个基于Python实现Ping的示例代码,可以满足您的要求:
```python
import os
import platform
import subprocess
import sys
def ping(host, count=4):
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, str(count), host]
return subprocess.call(command) == 0
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python ping.py <host> [-t]')
sys.exit(-1)
host = sys.argv[1]
count = 4
if len(sys.argv) > 2 and sys.argv[2] == '-t':
count = -1
if count == -1:
print(f'Pinging {host} indefinitely...')
while True:
if not ping(host):
print(f'{host} is down!')
break
else:
print(f'Pinging {host} {count} times...')
for i in range(count):
if ping(host):
print(f'{host} is up!')
else:
print(f'{host} is down!')
```
您可以将上述代码保存为 `ping.py` 文件,然后在命令行中运行 `python ping.py <host>` 来进行Ping操作。如果要实现无限次Ping,可以加上 `-t` 参数,例如:`python ping.py <host> -t`。
阅读全文