Giter VIP home page Giter VIP logo

find-process's People

Contributors

bert-huang avatar blakef avatar cormoran avatar dependabot[bot] avatar dominicboettger avatar effectrenan avatar h3r3zy avatar jennifer-shehane avatar julusian avatar yibn2008 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

find-process's Issues

Feature Request: Return port in found processes

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.

special characters in mac

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?

Security issue

Hello,
Could you check a vulnerability in this library?

Proof of concept and possible fix: 418sec#1

Find process on windows is not stable

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.

Adding logging level configuration

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.

using exe in name of process returns no results

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.

Command name with whitespaces is truncated on Mac OS

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.

Cannot find by port on Arch Linux

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

Environment

## 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

Matching by 'name' returns true if args field is empty

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.)

spawn cmd ENOENT on Windows Server 2016

Hello,

One of our users is having trouble with an ENOENT being thrown by find-process, indicating that WMIC could not be found:

cypress-io/cypress#3912

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?

Cannot find PID on Windows 10 when process with very long command line running

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!

Can't find child processes by name on win32

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

stdout maxBuffer exceeded

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

Process name shows incorrect

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.

Getting output (stdout) from a process

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.

Upgrade to powershell on windows and Change Management

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/.

Example clarification

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');
    }
  )

Get Executable Path?

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...

Get the port as well

Is it possible to also get the port of a PID, if the process is listening on a port?

Not return processes when value is a `regular expression`

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);
    });

The function always returns an empty array.
Captura de tela de 2021-02-18 13-05-19

Allow search by multiple options of one type in one call

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.

stdout maxBuffer exceeded

On windows, if there are processes with a very long CommandLine, you get the 'stdout maxBuffer exceeded' error.

Avoid prompting for password

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.

hints for netstat not found

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

v1.4.5: Error: port must be a number

1.4.4

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.

1.4.5

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.

Details

  • OS: Linux ... 5.11.0-40-generic 44~20.04.2-Ubuntu SMP Tue Oct 26 18:07:44 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
  • node: v12.19.0

Win 64

I have to test the library you made, i love it, should it also work in x64 win?

Build error A 'declare' modifier is required

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<{

TypeError: Cannot read property 'endsWith' of undefined

                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)

Check the process owner or any mapping between user and process before killing process in Node JS

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.

  1. Start some known process.
  2. Kill that process. (It can kill the same process from other users)

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.

Provide port details (if binded) for find process PID

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

`matchName` throws TypeError: Cannot read property 'match' of undefined

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.