scan-connect-ip.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env node
  2. const { spawnSync } = require('child_process')
  3. const path = require('path')
  4. const config = require(path.join(__dirname, '..', '..', 'configs', 'config.js'))
  5. const projectRoot = path.resolve(__dirname, '..', '..')
  6. /** 从 config 解析并返回 adb 可执行文件路径 */
  7. function getAdbPath() {
  8. return config.adbPath?.path
  9. ? path.resolve(projectRoot, config.adbPath.path)
  10. : path.join(projectRoot, 'lib', 'scrcpy-adb', 'adb.exe')
  11. }
  12. /** 判断 adb connect 输出是否表示连接成功 */
  13. function isConnectSuccess(output) {
  14. const s = (output || '').trim()
  15. return s.includes('connected') || s.includes('already connected')
  16. }
  17. /** 对单个 IP 执行 adb connect,返回是否成功(不抛错,失败返回 false) */
  18. function tryConnectOne(adbPath, ip, port) {
  19. const quotedAdb = adbPath.includes(' ') ? `"${adbPath}"` : adbPath
  20. const cmd = `${quotedAdb} connect ${ip}:${port}`
  21. const shell = process.platform === 'win32' ? 'cmd' : 'sh'
  22. const shellArg = process.platform === 'win32' ? '/c' : '-c'
  23. const r = spawnSync(shell, [shellArg, cmd], { encoding: 'utf-8', timeout: 500 })
  24. return r.status === 0 && isConnectSuccess(r.stdout)
  25. }
  26. /** 扫描网段 basePrefix.1~.255,返回连接成功的 IP 列表 */
  27. function scanSubnet(adbPath, basePrefix, port) {
  28. const connected = []
  29. for (let i = 1; i <= 255; i++) {
  30. const ip = `${basePrefix}.${i}`
  31. if (tryConnectOne(adbPath, ip, port)) {
  32. connected.push(ip)
  33. }
  34. }
  35. return connected
  36. }
  37. const basePrefix = process.argv[2]
  38. const port = process.argv[3] || '5555'
  39. if (!basePrefix || !/^\d+\.\d+\.\d+$/.test(basePrefix)) {
  40. process.exit(1)
  41. }
  42. const adbPath = getAdbPath()
  43. const connected = scanSubnet(adbPath, basePrefix, port)
  44. process.stdout.write(connected.join('\n') + (connected.length ? '\n' : ''))
  45. process.exit(0)