81 lines
2.2 KiB
JavaScript
81 lines
2.2 KiB
JavaScript
import express from 'express';
|
|
import ping from 'ping';
|
|
import 'dotenv/config';
|
|
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT;
|
|
|
|
|
|
async function startPing(ips,req, res) {
|
|
try {
|
|
const pingResults = await Promise.all(
|
|
ips.map(async (ip, index) => {
|
|
try {
|
|
console.log(req[index]);
|
|
const result = await ping.promise.probe(ip);
|
|
if (result.alive == 1){
|
|
return {
|
|
status: 200,
|
|
time: new Date().toISOString(),
|
|
result: [ {
|
|
target: ip,
|
|
alive: result.alive ? 1 : 0,
|
|
"time ms": result.time + ' ms',
|
|
output: result.output,
|
|
devices: req[index]
|
|
}
|
|
]
|
|
};
|
|
} else {
|
|
return {
|
|
status: 503,
|
|
time: new Date().toISOString(),
|
|
result: [ {
|
|
target: ip,
|
|
alive: result.alive ? 1 : 0,
|
|
"time ms": result.time + ' ms',
|
|
"status": "error",
|
|
"message": "Network Unreachable",
|
|
devices: req[index],
|
|
output: result.output
|
|
}
|
|
]
|
|
};
|
|
}
|
|
} catch (error) {
|
|
return {
|
|
target: ip,
|
|
error: error.message,
|
|
};
|
|
}
|
|
})
|
|
);
|
|
res.json(pingResults);
|
|
} catch (error) {
|
|
res.status(500).json({ error: 'Server error', details: error.message });
|
|
}
|
|
}
|
|
|
|
// Endpoint to check ping status
|
|
app.get('/ping', async (req, res) => {
|
|
try {
|
|
const device = process.env.TARGET_DEVICE ? process.env.TARGET_DEVICE.split(',').map(dev => dev.trim()) : [];
|
|
if (device.length === 0) {
|
|
return res.status(400).json({ error: 'No target devices configured in .env' });
|
|
}
|
|
const IPs = process.env.TARGET_IPS ? process.env.TARGET_IPS.split(',').map(ip => ip.trim()) : [];
|
|
if (IPs.length === 0) {
|
|
return res.status(400).json({ error: 'No target IPs configured in .env' });
|
|
}
|
|
startPing(IPs, device, res);
|
|
} catch (error) {
|
|
res.status(500).json({ error: 'Failed to ping', details: error.message });
|
|
}
|
|
});
|
|
|
|
// Start server
|
|
app.listen(PORT, () => {
|
|
console.log(`Server running on http://localhost:${PORT}`);
|
|
});
|