Skip to content

Instantly share code, notes, and snippets.

@Joxebus
Last active April 24, 2020 03:37
Show Gist options
  • Save Joxebus/81e16111a10026312ae9c3a1e8f1fe82 to your computer and use it in GitHub Desktop.
Save Joxebus/81e16111a10026312ae9c3a1e8f1fe82 to your computer and use it in GitHub Desktop.
Script to generate a random password with Groovy
// Give execution permission
⇒ chmod +x random_password.groovy
// Show help
⇒ ./random_password.groovy -h
usage: random_password -[has]
-a,--alphabet <arg> A set of characters to generate the password
-h,--help Usage Information
-s,--size <arg> Size of the output password
// Execute with default values
⇒ ./random_password.groovy
cC3DtEYO
// Execute with custom alphabet
⇒ ./random_password.groovy -a "abcdefg1234;'/"
e2f;cg1c
// Execute with custom size
⇒ ./random_password.groovy -s 16
GXqPJqn$1O_NS3gt
// Execute with custom alphabet and size
⇒ ./random_password.groovy -a "abcdefg1234;'/" -s 12
ab3;dda/dbd3
def letters = (('a'..'z') + ('A'..'Z'))
def numbers = '0'..'9'
def special = '.;!$_-'
def size = 8
// Join all the characteres in a single String
def alphabet = (letters+numbers+special).join()
def cli = new CliBuilder(usage: 'random_password -[has]')
cli.with {
h(longOpt: 'help', 'Usage Information \n')
a(type: String, longOpt: 'alphabet','A set of characters to generate the password')
s(type: Integer, longOpt: 'size','Size of the output password')
}
def generatePassword = { String alphabet, int size ->
new Random().with {
(1..size).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
}
}
def options = cli.parse(args)
if(options.h) {
cli.usage()
return
}
if(options.a){
alphabet = options.a
}
if(options.s){
size = options.s
}
#!/usr/bin/env groovy
import groovy.cli.commons.CliBuilder
def generatePassword = { String alphabet, int size ->
new Random().with {
(1..size).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
}
}
// CLI Commands definition
def cli = new CliBuilder(usage: 'random_password -[has]')
cli.with {
h(longOpt: 'help', 'Usage Information \n')
a(type: String, longOpt: 'alphabet','A set of characters to generate the password')
s(type: Integer, longOpt: 'size','Size of the output password')
}
// default values
def letters = (('a'..'z') + ('A'..'Z'))
def numbers = '0'..'9'
def special = '.;!$_-'
def size = 8
def alphabet = (letters+numbers+special).join()
def options = cli.parse(args)
if(options.h) {
cli.usage()
return
}
if(options.a){
alphabet = options.a
}
if(options.s){
size = options.s
}
println generatePassword(alphabet, size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment