MCPcopy Create free account
hub / github.com/TeleBoxOrg/TeleBox_Plugins / checkPortInUse

Function checkPortInUse

ssh/ssh.ts:60–124  ·  view source on GitHub ↗
(port: number)

Source from the content-addressed store, hash-verified

58 try {
59 await execFileAsync("systemctl", ["is-active", "--quiet", serviceName]);
60 return true;
61 } catch { }
62 }
63 try {
64 await execFileAsync("pgrep", ["sshd"]);
65 return true;
66 } catch {
67 return false;
68 }
69}
70
71// HTML转义函数
72// 验证路径安全性
73function validatePath(pathStr: string): boolean {
74 if (!pathStr || typeof pathStr !== "string") return false;
75 // 检查危险字符
76 const dangerousChars = /[;&|`$(){}[\]<>'"\\]/;
77 if (dangerousChars.test(pathStr)) return false;
78 // 检查路径遍历
79 if (pathStr.includes("../") || pathStr.includes("..\\")) return false;
80 return true;
81}
82
83// 端口验证函数
84const validatePort = (port: string): number | null => {
85 const portNum = parseInt(port, 10);
86 if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
87 return null;
88 }
89 return portNum;
90};
91
92// 检查端口是否被占用
93async function checkPortInUse(port: number): Promise<{ inUse: boolean; processInfo?: string }> {
94 const parseListeners = async (
95 command: string,
96 args: string[],
97 ): Promise<{ inUse: boolean; processInfo?: string }> => {
98 const { stdout } = await execFileAsync(command, args);
99 const portPattern = new RegExp(`:${port}(?:\\s|$)`);
100 const lines = stdout.split("\n").filter((line) => portPattern.test(line));
101 if (lines.length === 0) return { inUse: false };
102
103 const processInfos = await Promise.all(lines.map(async (line) => {
104 const parts = line.trim().split(/\s+/);
105 const protocol = parts[0] || "tcp";
106 const address = parts.find((part) => portPattern.test(part)) || `:${port}`;
107 const pid = line.match(/pid=(\d+)/)?.[1] || line.match(/\s(\d+)\/\S+/)?.[1];
108 let processName = "未知进程";
109 if (pid) {
110 try {
111 const { stdout: nameOutput } = await execFileAsync("ps", ["-p", pid, "-o", "comm="]);
112 processName = nameOutput.trim() || processName;
113 } catch { }
114 }
115 return `${protocol} ${address} (${processName})`;
116 }));
117 return { inUse: true, processInfo: processInfos.join(", ") };

Callers 1

changeSSHPortMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected