yibn2008 / find-process Goto Github PK
View Code? Open in Web Editor NEWfind process by port/pid/name etc.
License: MIT License
find process by port/pid/name etc.
License: MIT License
I'm getting an issue caused by text
within matchName
being undefined.
Here's my stack trace.
at o (...\node_modules\find-process\lib\find_process.js:25:1)
at i.parseTable.filter (...\node_modules\find-process\lib\find_process.js:148:1)
at Array.filter (<anonymous>)
at ChildProcess.r.on (...\node_modules\find-process\lib\find_process.js:137:1)
at ChildProcess.emit (events.js:182:13)
at maybeClose (internal/child_process.js:962:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
What would be causing this?
return row.Name === cond.name || (row.Name.endsWith('.exe') && row.Name.slice(0, -4) === cond.name)
This line sometimes can raise a error like below
TypeError: Cannot read property 'endsWith' of undefined
at C:\Users\balbalba\balbalba\resources\app.asar\node_modules\find-process\lib\find_process.js:140:60
at Array.filter (<anonymous>)
at ChildProcess.<anonymous> (C:\Users\mobra\balbalba\balbalba\resources\app.asar\node_modules\find-process\lib\find_process.js:135:12)
at ChildProcess.emit (events.js:203:13)
at ChildProcess.EventEmitter.emit (domain.js:476:20)
at maybeClose (internal/child_process.js:1021:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
This is an edge case but if you have a slim *nix install that doesn't include ps
, trying to find a process by PID results in just an empty array instead of an error (https://github.com/yibn2008/find-process/blob/master/lib/find_process.js#L35-L36).
Perhaps the existence of the necessary utilities by platform should be checked for in a pre-install script.
It does not work properly in container image.
Container: node:12-alpine
If the mac original language is English and then install a Chinese language with one Chinese application. The Chinese showed correctly in Mac Monitor but by using find-process, it will be special characters. May I know how to fix it?
Are you planning on creating some typings for this module (@types/find-process
). Source.
Works Ok
$ yarn find-process -p 3000
yarn run v1.22.10
$ /home/.../node_modules/.bin/find-process -p 3000
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Found 1 process
[localhost:3000)]
pid: 17002
cmd: puma 5.5.2 (tcp://localhost:3000) [meka-erp]
Done in 0.13s.
Error
$ yarn find-process -p 3000
yarn run v1.22.10
$ /home/.../node_modules/.bin/find-process -p 3000
Error: port must be a number
at /home/.../node_modules/find-process/lib/find.js:60:162
at new Promise (<anonymous>)
at find (/home/.../node_modules/find-process/lib/find.js:56:10)
at Object.<anonymous> (/home/.../node_modules/find-process/bin/find-process.js:59:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
error Command failed with exit code 1.
The example code always ends with the error stdout maxBuffer exceeded
find('pid', 123)
.then(function (list) {
console.log(list);
}, function (err) {
console.log(err.message);
});
Tested on node v6.5.0
Hi guys,
Is it possible to get the output of a process when you know its pid ? I'm blocking on that, I have 2 subchildren of a spawn and I can get the output from the spawn but not from the 2 subchildren. I succeded to get their pid and I can kill them but it seems impossible to get their output.
Regards.
Hi, i am running find-process for every few seconds using set interval,because of this wmic commandline utility starts its process for every few seconds and makes system hang by consuming more cpu usage.
Any help on this would be appreciated,Thank You
Dear, sorry for the newbie
question, but where am I going wrong when trying to use find
passing as type name
and using value RegExp
?
I tested the expression on several sites and working, however when using nodejs in the function find
without effect, it does not list any process. However, the processes exist.
return find('name', '/[Vv]isual|[Cc]ode/', true)
.then((list) => {
console.log('List :', list);
}, (err) => {
console.error('Error :', err);
});
Hi.
When I use this package, I found sometimes, it can not get the process by name on windows(ex, this time I can not get the process, then retry again, it can get it.), I think windows wmic method is not stable. Please have a check. Thanks.
Platform: Mac OS
Process: Visual Studio Code
Result:
{
name: 'Visual',
cmd: '/Application/Visual Studio Code.app/Contents/MacOS/Electron'
}
The correct VSCode process name in Activity Monitor
is Code
.
It looks like currently if you use child_process.spawn on win32 with detached:false, find-process is unable to find the process by name when search from within the same parent process that spawned the child.
I didn't test to see if this is a broader issue but the specified case should reproduce
Process list:
[ { pid: '51460',
ppid: '22520',
uid: null,
gid: null,
name: 'lbrynet.exe',
cmd: 'lbrynet start' },
{ pid: '39964',
ppid: '51460',
uid: null,
gid: null,
name: 'lbrynet.exe',
cmd: 'lbrynet start' } ]
Call:
const processListArgs = 'lbrynet.exe';
const processList = await findProcess('name', processListArgs);
This fails to return the process with or without strict mode on.
We'll use 'lbrynet start' for now, but it requires us to pass as 'lbrynet start' - with an extra space because that's how WMIC returns it.
On my machine (darwin), calling find('name', 'whatever')
always returns a non-empty result, no matter what I pass as a search pattern.
The reason is that on my machine there's a process running whose args field is empty in the ps output:
$ ps ax -ww -o pid,ppid,uid,gid,args
...
867 1 0 0 /usr/libexec/ioupsd
871 1 55 55 /System/Library/CoreServices/appleeventsd --server
894 1 441 441 /usr/libexec/rosetta/oahd
897 1 0 0
901 1 0 0 /Library/PrivilegedHelperTools/com.docker.vmnetd
904 1 0 0 /usr/libexec/taskgated
909 1 89 89 /usr/sbin/distnoted agent
...
As you can see, the process with pid 897 has an empty args field. (I don't quite understand how it's possible to launch a process like this, but that's not the question here.)
Now, the code that filters the process list will skip the name match (because column[4]
is empty) and falls through to the return !!column[0]
, which returns true.
As far as I can see, the following patch will fix the problem:
diff --git a/lib/find_process.js b/lib/find_process.js
index 34188ee..74c4a4b 100644
--- a/lib/find_process.js
+++ b/lib/find_process.js
@@ -84,7 +84,7 @@ const finders = {
const columns = utils.extractColumns(data, [0, 1, 2, 3, 4], 5).filter(column => {
if (column[0] && cond.pid) {
return column[0] === String(cond.pid)
- } else if (column[4] && cond.name) {
+ } else if (cond.name) {
return matchName(column[4], cond.name)
} else {
return !!column[0]
I think this is correct because matchName
correctly takes care of returning false if the input text is empty.
(The same change should probably be made in the "android" section below, but I have no way to test that.)
Hello,
Could you check a vulnerability in this library?
Proof of concept and possible fix: 418sec#1
Hello,
One of our users is having trouble with an ENOENT being thrown by find-process
, indicating that WMIC could not be found:
Here is the text of the error, for reference:
Error: spawn cmd ENOENT
at exports._errnoException (util.js:1024:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
at onErrorNT (internal/child_process.js:374:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn cmd',
path: 'cmd',
spawnargs:
[ '/c',
'WMIC path win32_process get Name,Processid,ParentProcessId,Commandline' ] }
Error: spawn cmd ENOENT
at exports._errnoException (util.js:1024:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
at onErrorNT (internal/child_process.js:374:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Is this a known issue that there's a workaround for?
Hi,
After starting a Python server, I can find the process by pid but not by port:
$ python -m http.server 8081 --directory src &
Serving HTTP on 0.0.0.0 port 8081 (http://0.0.0.0:8081/) ...
[1] 34716
$ npx find-process 34716
Found 1 process
[python]
pid: 34716
cmd: python -m http.server 8081 --directory src
$ npx find-process -p 8081
No process found
## System:
- OS: Linux 5.4 Arch Linux
- CPU: (8) x64 Intel(R) Core(TM) i7-3770K CPU @ 3.50GHz
- Memory: 9.14 GB / 15.59 GB
- Container: Yes
- Shell: 5.0.11 - /bin/bash
## Binaries:
- Node: 13.5.0 - /usr/bin/node
- Yarn: 1.21.1 - /usr/bin/yarn
- npm: 6.13.4 - /usr/bin/npm
- Watchman: 4.9.0 - /usr/bin/watchman
I have a situation where I would like to find the port of a process with a known executable. The port could be unknown.
I would like to be able to run something like the following:
find("name", "java", true);
And have it return an array of all java processes and the port they're running on, if any.
Rather than just the process name I'd like to have the file path to its executable (not always provided by the command line...)
On Windows this is possible with:
wmic process get ExecutablePath
Not sure how on other platforms...
On windows, if there are processes with a very long CommandLine, you get the 'stdout maxBuffer exceeded' error.
I am testing find-process
installed as npm global dependency on an ubuntu machine without installing netstat
.
When I use it to find process, it only prompt No process found
instead of the real reason that
Command 'netstat' not found, but can be installed with:
sudo apt install net-tools
Hi,
I'm testing your library (v1.4.1) to retrieve process path from PID.
It is working perfectly except when I'm running a process with very long command line arguments.
I noticed that when I'm running IntelliJ IDE (which has nothing to do with my application using find-process) my application is not able to find any PID.
It looks like WMIC output is not consistent when command line column is very big (in my case more than 8000 characters for intelliJ only). And the parsing function is not able to retrieve PIDs.
Thanks again for what you have done with this library!
背景
问题
as title says..
it would be nice to be able to search by parent-id
It would be great to be able to pass an array of possible values to match and get all the results back at once. I realize that it is possible to do them one at a time, but this seems like it could be more performant if the library handles it.
for instance:
find('pid', [1234. 2345]);
This could return 0-2 results.
For ports, you would likely need to include this #33 so that we can tell which ones matched.
Hi,
when building my code using tsc mycode.ts --lib es6
I keep getting this error. The output JavaScript works fine though.
node_modules/find-process/index.d.ts:1:1 - error TS1046: A 'declare' modifier is required for a top level declaration in a .d.ts file.
function find(type: "name" | "pid" | "port", value: string | number | RegExp, strict?: boolean): Promise<{
I have to test the library you made, i love it, should it also work in x64 win?
This doesn't seem to be able to find processes on UDP ports
find-process/lib/find_process.js
Line 95 in c12511d
should this not match row.Name instead of row.CommandLine
windows系统中如果程序路径中有中文就会检测失败。无论检测pid 还是检测占用的 port 都会失败
If I search in the cli like this find-process [app-name]
it always finds at least the find-process-process itself
❯ find-process [APP]
Found 1 process
[node]
pid: 11347
cmd: node /xxx/pnpm/global/5/node_modules/find-process/bin/find-process.js [APP]
Can this be prevented?
This tool is an obvious attack vector since it prompts for password if running on linux (and searching for a process by port number).
There should be a flag to switch off this behavior, so the tool just fails if a password is required.
ps ax -ww -o pid,ppid,uid,comm,args
should not be used, but ps ax -ww -o pid,comm
, if you want to parse bin
field correctly.
Otherwise, there is no way to split arguments from command.
Consider calling ps command twice, if you really need command arguments. If you don't need arguments, comm
should be enough.
Is it possible to also get the port of a PID, if the process is listening on a port?
This stops the library from working on Windows 7 running Powershell 2, causing it to hang indefinitely.
You should check the Powershell version and either use WMI or Cim.
In the README.md there is the following example to find process which is listening port 80:
const find = require('find-process');
find('port', 80)
.then(function (list) {
if (!list.length) {
console.log('port 80 is free now');
} else {
console.log('%s is listening port 80', list[0].name);
}
})
The console.log('port 80 is free now');
line will never be called because, in lib/find_pid.js line 34, Array.find is used to search for the id. If no process is using that port, then Array.find will return undefined
as the value of columns
so line 41 will always reject the Promise.
Is the intent of the code to resolve the Promise with an empty array (as seems to be the intent of the example) or should the example be changed to something like the following:
const find = require('find-process');
find('port', 80)
.then(function (list) {
console.log('%s is listening port 80', list[0].name);
})
.catch(
function(reason) {
console.log('port 80 is free now');
}
)
Hi,
regarding to the subject that was also discussed in #28 ,
any workarounds / future PR for that ?
The most naive solution might be to create the following flow:
the caller runs findProcess('pid',)
in find_process.js before returning the now found process details,
Check if finders[find] returned response with process details,
Then for the fetched process, run the commands logic implemented in find pid by port but instead of matching the port in
if (matches && matches[1] === String(port))
match the pid
then return the data received by concat both of the results
If you use "find" to get the processes of some name and the system is multiuser, it will return processes from all users. Hence before killing any process it's good to check if the process is owned by current used by mapping any means like owner or userid.
For eg.
The below code snippet can be added for any node console app.
const find = require('find-process');
find('name', 'Teams', true).then(function (list) {
var i;
for (i = 0; i < list.length; i++) {
process.kill(list[i].pid);
}
});
Also, I see that from the returned process, uid and gid in Windows are undefined.
The API doesn't allow control over the logging levels surfaced to the user. There are very sane defaults if you're using find-process
in the CLI, however if you're using it as a library you can't silence this output from netstat
:
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
I'm wondering if you'd be open to a pull request to use a simple logging framework like loglevel (0 dependencies), and allow for configuring a logging level. Possibly update to this signature:
interface Options {
loglevel: LogLevelDesc?;
strict: boolean?;
}
function find(by, value, options?: Options | boolean) {
const opts = Object.assign({
loglevel: 'warn',
strict: typeof strict === 'boolean' ? strict : !!option.strict,
}, options);
...
}
Very happy to put together a pull request, but wanted to gauge if there was any interest first.
I have been reading changes in the most recent commits, preparing to install the new version because the change log in this project is non-existent, and my attention was caught by the following change 4dd1c15
This commit changes the way processes are found on Windows from using WMIC to powershell.exe. This immediately raised many questions: what is the motivation behind this change? why the users are not informed about it? why is this not a breaking change?
Whilst, I was able to find some answers, specifically about motivation:
The WMI command-line (WMIC) utility is deprecated as of Windows 10, version 21H1, and as of the 21H1 semi-annual channel release of Windows Server. This utility is superseded by Windows PowerShell for WMI
from: https://docs.microsoft.com/en-us/windows/win32/wmisdk/wmic
I wanted to point out that in many corporate settings running powershell as a regular user is not allowed, as a security measure. I think this change should be reflected somewhere, potentially even bumping a major version of the package. Is kinda late now, but for some consumers it might save the trouble of investigating why it suddenly stopped working.
I also wish that commit messages were more informative and detailed enough CHANGELOG was published. The HISTORY.md file in the repository does little to no help at all. I suggest this article on how to make a good Change Log: https://keepachangelog.com/en/0.3.0/.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.