Can I fetch a unique server machine identifier with node.js?

送分小仙女□ 提交于 2019-12-05 00:47:20

Node has no built-in was to access this kind of low-level data.

However, you could execute ifconfig and parse its output or write a C++ extension for node that provides a function to retrieve the mac address. An even easier way is reading /sys/class/net/eth?/address:

var fs = require('fs'),
    path = require('path');
function getMACAddresses() {
    var macs = {}
    var devs = fs.readdirSync('/sys/class/net/');
    devs.forEach(function(dev) {
        var fn = path.join('/sys/class/net', dev, 'address');
        if(dev.substr(0, 3) == 'eth' && fs.existsSync(fn)) {
            macs[dev] = fs.readFileSync(fn).toString().trim();
        }
    });
    return macs;
}

console.log(getMACAddresses());

The function returns an object containing the mac addresses of all eth* devices. If you want all devices that have one, even if they are e.g. called wlan*, simply remove the dev.substr(0, 3) == 'eth' check.

If you're just looking for a unique server id, you could take the mongodb/bson approach and use the first n bytes of the md5 hash of the server's host name:

var machineHash = crypto.createHash('md5').update(os.hostname()).digest('binary');

This code is from node-buffalo. Not perfect, but may be good enough depending on what you're trying to do.

I tried the getmac package but it would not work for me (node v0.10, Mac OS X) - so I set out and built my own: https://github.com/scravy/node-macaddress . It works in Windows, OS X, Linux, and probably every unix with ifconfig :-)

Here is node.js code using command line tools to get MAC address:

`$ ifconfig | grep eth0 | awk '{print $5}'`

for wlan0

`$ ifconfig | grep wlan0 | awk '{print $5}'`

In node.js, use this - save the code to getMAC.js - "$ node getMAC.js" to run

`// Get MAC address - $ ifconfig | grep wlan0 | awk '{print $5}'
 var exec = require('child_process').exec;
 function puts(error, stdout, stderr) { console.log(stdout) }
 exec("ifconfig | grep wlan0 | awk '{print $5}'", puts);
 `

The complete answer is further down, but basically you can get that info in vanilla node.js via:

require('os').networkInterfaces()

This gives you all the info about networking devices on the system, including MAC addresses for each interface.

You can further narrow this down to just the MACS:

JSON.stringify(  require('os').networkInterfaces(),  null,  2).match(/"mac": ".*?"/g)

And further, to the pure MAC addresses:

JSON.stringify(  require('os').networkInterfaces(),  null,  2).match(/"mac": ".*?"/g).toString().match(/\w\w:\w\w:\w\w:\w\w:\w\w:\w\w/g)

This last one will give you an array-like match object of the form:

['00:00:00:00:00:00', 'A8:AE:B6:58:C5:09', 'FC:E3:5A:42:80:18' ]

The first element is your lo or local interface.

I randomly generated the others for public example using https://www.miniwebtool.com/mac-address-generator/

If you want to be more 'proper' (or break it down into easier to digest steps):

var os = require('os');

var macs = ()=>{
  return JSON.stringify(  os.networkInterfaces(),  null,  2)
    .match(/"mac": ".*?"/g)
    .toString()
    .match(/\w\w:\w\w:\w\w:\w\w:\w\w:\w\w/g)
  ;
}


console.log( macs() );

Basically, you're taking the interface data object and converting it into a JSON text string. The. you get a match object for the mac addresses and convert that into a text string. Then you extract only the MAC addresses into an iteratable match object that contains only each MAC in each element.

There are surly more succinct ways of doing this, but this one is reliable and easy to read.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!