Skip to content

Instantly share code, notes, and snippets.

@aozen
Last active November 18, 2025 20:45
Show Gist options
  • Select an option

  • Save aozen/5c930f2ef288a46c6cd7910ffbc515e4 to your computer and use it in GitHub Desktop.

Select an option

Save aozen/5c930f2ef288a46c6cd7910ffbc515e4 to your computer and use it in GitHub Desktop.
generate random password with given length
#!/usr/bin/env node
const crypto = require('crypto')
const defaultOpts = {
length: 20,
includeLower: true,
includeUpper: true,
includeNumbers: true,
includeSymbols: true,
excludeSimilar: true, // avoid 0, O, l, 1
excludeAmbiguous: true, // punctuation like {}[]()/\
prefix: '',
customChars: '', // override allowed chars entirely
}
const generate = (opts = {}) => {
const o = { ...defaultOpts, ...opts }
let pool = o.customChars || ''
if (!o.customChars) {
if (o.includeLower) pool += 'abcdefghijklmnopqrstuvwxyz'
if (o.includeUpper) pool += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if (o.includeNumbers) pool += '0123456789'
if (o.includeSymbols) pool += '!@#$%^&*()_+[]{}|;:,.<>?'
}
if (o.excludeSimilar) pool = pool.replace(/[0OIl1]/g, '')
if (o.excludeAmbiguous) pool = pool.replace(/[\{\}\[\]\(\)\/\\'"`,.;:~]/g, '')
if (!pool) throw new Error('Character pool is empty. enable/change some options or specify customChars')
const bytes = crypto.randomBytes(o.length)
let pwd = ''
for (let i = 0; i < o.length; i++) {
const idx = bytes[i] % pool.length
pwd += pool[idx]
}
return o.prefix + pwd
}
const length = Number(process.argv[2]) || 20
console.log(generate({ length }))
@aozen
Copy link
Author

aozen commented Aug 13, 2025

SETUP

curl -s https://gist.githubusercontent.com/aozen/5c930f2ef288a46c6cd7910ffbc515e4/raw/generatePassword.js -o ~/bin/generatepassword
chmod +x ~/bin/generatepassword
export PATH="$HOME/bin:$PATH"

or export into /usr/local/bin and you probably wont need to export PATH.

Then use with or without param:

generatepassword
generatepassword 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment