Demonstration effect

Global installation wifi-password-CLI dependency

npm install wifi-password-cli -g
# or
npx wifi-password-cli
Copy the code

use

$ wifi-password [network-name]

$ wifi-password
12345678

$Wifi-password Office wifi
a1234b2345
Copy the code

Think Node.js is amazing? It’s not. Let’s see how it works, okay

Realize the principle of

OSX system

Run the following command to query the wifi password

security find-generic-password -D "AirPort network password" -wa "wifi-name"
Copy the code

Linux system

All wi-fi connection information in the/etc/NetworkManager/system – connections/folder

We query the wifi password through the following command

sudo cat /etc/NetworkManager/system-connections/<wifi-name>
Copy the code

Windows system

Run the following command to query the wifi password

netsh wlan show profile name=<wifi-name> key=clear
Copy the code

Realize the source

Its implementation of the source code is also very simple, interested in learning

Github.com/kevva/wifi-…

The entry file is index.js. Firstly, different acquisition methods are selected by judging the user’s operating system

'use strict';
const wifiName = require('wifi-name');

module.exports = ssid= > {
	let fn = require('./lib/linux');

	if (process.platform === 'darwin') {
		fn = require('./lib/osx');
	}

	if (process.platform === 'win32') {
		fn = require('./lib/win');
	}

	if (ssid) {
		return fn(ssid);
	}

	return wifiName().then(fn);
};
Copy the code

Linux

'use strict';
const execa = require('execa');

module.exports = ssid= > {
	const cmd = 'sudo';
	const args = ['cat'.`/etc/NetworkManager/system-connections/${ssid}`];

	return execa.stdout(cmd, args).then(stdout= > {
		let ret;

		ret = /^\s*(? :psk|password)=(.+)\s*$/gm.exec(stdout);
		ret = ret && ret.length ? ret[1] : null;

		if(! ret) {throw new Error('Could not get password');
		}

		return ret;
	});
};
Copy the code

OSX

'use strict';
const execa = require('execa');

module.exports = ssid= > {
	const cmd = 'security';
	const args = ['find-generic-password'.'-D'.'AirPort network password'.'-wa', ssid];

	return execa(cmd, args)
		.then(res= > {
			if (res.stderr) {
				throw new Error(res.stderr);
			}

			if(! res.stdout) {throw new Error('Could not get password');
			}

			return res.stdout;
		})
		.catch(err= > {
			if (/The specified item could not be found in the keychain/.test(err.message)) {
				err.message = 'Your network doesn\'t have a password';
			}

			throw err;
		});
};

Copy the code

Windows

'use strict';
const execa = require('execa');

module.exports = ssid= > {
	const cmd = 'netsh';
	const args = ['wlan'.'show'.'profile'.`name=${ssid}`.'key=clear'];

	return execa.stdout(cmd, args).then(stdout= > {
		let ret;

		ret = /^\s*Key Content\s*: (.+)\s*$/gm.exec(stdout);
		ret = ret && ret.length ? ret[1] : null;

		if(! ret) {throw new Error('Could not get password');
		}

		return ret;
	});
};
Copy the code