Skip to content

Instantly share code, notes, and snippets.

@max-mapper
Last active June 3, 2020 00:31
Show Gist options
  • Save max-mapper/4356968 to your computer and use it in GitHub Desktop.
Save max-mapper/4356968 to your computer and use it in GitHub Desktop.
automatically scan for and join open internet enabled wifi networks on linux using node.js (tested on raspberry pi raspbian)
#!/usr/bin/env node
var iw = require('iwlist')(process.argv[2] || 'wlan0')
var tried = {}
var silent = process.argv[4]
// wait for some time so that linux can try to associate with a known network first
var delay = process.argv[3] || 30000
if (!silent) console.log('waiting ' + delay/1000 + ' seconds')
setTimeout(start, process.argv[3] || 30000)
function start() {
iw.associated(function(err, associated) {
if (associated) {
if (!silent) console.log('already associated -- exiting')
return process.exit()
}
findOpenNetwork()
})
}
function findOpenNetwork() {
if (!silent) console.log('scanning for open networks...')
iw.scan(function(err, networks) {
if (err) {
if (!silent) console.log('error scanning', err)
return process.exit()
}
networks = removeSecureNetworks(networks)
if (networks.length === 0) {
if (!silent) console.log('no open networks nearby')
return process.exit()
}
var network = getNextNetwork(networks)
if (!silent) console.log('attempting to join ' + network.essid)
connectToNetwork(network.essid)
})
}
function connectToNetwork(essid) {
iw.connect(essid, function(err) {
if (err) {
if (!silent) console.log('error joining ' + essid, err)
return start()
}
iw.online(function(err) {
if (err) {
if (!silent) console.log(essid + ' is not internet enabled', err)
return findOpenNetwork()
}
if (!silent) console.log('got online successfully via network: ' + essid)
process.exit()
})
})
}
function removeSecureNetworks(networks) {
openNetworks = []
networks.map(function(network) {
if (!network.encrypted) openNetworks.push(network)
})
return openNetworks
}
function getNextNetwork(networks) {
var network = networks.shift()
if (!network) return process.exit()
while (tried[network.essid]) {
network = networks.shift()
}
return network
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment