【亲测有效】icmp,tcpping工具源码
icmp,tcpping工具源码
import socket
import subprocess
import platform
import time
import sys
def icmp_ping(host, count=4):
param = '-n' if platform.system().lower() == 'windows' else '-c'
try:
# 执行 ping 命令
result = subprocess.run(['ping', param, str(count), host], capture_output=True, text=True)
# 输出 ICMP ping 结果并及时刷新
if result.returncode == 0:
print(f"ICMP Ping {host} 成功!")
print(result.stdout)
else:
print(f"ICMP Ping {host} 失败!")
print(result.stderr)
sys.stdout.flush()
except Exception as e:
print(f"执行 ICMP ping 命令时发生错误: {e}")
sys.stdout.flush()
def tcp_ping(host, port, timeout=2):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
start_time = time.time()
sock.connect((host, port))
end_time = time.time()
connection_time = end_time - start_time
print(f"TCP Ping {host}:{port} 成功!连接时间: {connection_time:.4f} 秒")
sock.close()
except socket.timeout:
print(f"TCP Ping {host}:{port} 失败!连接超时")
except ConnectionRefusedError:
print(f"TCP Ping {host}:{port} 失败!连接被拒绝")
except Exception as e:
print(f"执行 TCP ping 时发生错误: {e}")
# 及时刷新标准输出
sys.stdout.flush()
def main():
# 执行初始的 ICMP 和 TCP ping 操作
initial_host = 'www.qq.com'
print(f"正在测试初始主机: {initial_host}")
icmp_ping(initial_host)
tcp_ping(initial_host, 80)
# 等待用户输入域名、网址或 IP 地址进行测试
while True:
user_input = input("请输入要测试的域名、网址或 IP 地址 (输入 'exit' 退出): ")
if user_input.lower() == 'exit':
print("退出程序。")
break
# 用户输入端口号
port_input = input("请输入端口号(默认为 80,直接回车跳过):")
port = 80 # 默认端口
if port_input.strip(): # 如果用户输入了端口号
try:
port = int(port_input.strip())
except ValueError:
print("端口号无效,将使用默认端口 80")
port = 80
# 执行 ICMP 和 TCP ping 操作
print(f"正在测试用户输入主机: {user_input},端口: {port}")
icmp_ping(user_input)
tcp_ping(user_input, port)
if __name__ == '__main__':
main()
使用效果: