README
Repo name: random_hostname_nick3499
Set system hostname with pseudo-random alpha-numeric string.
random_hostname.py
changes system hostname; be sure user wants system hostname to change.
Note: Shebang/Interpreter Directive
The shebang line starts with #!
, because those human-readable characters, encoded to ASCII, become 0x23 and 0x21, which together become a magic number or a magic byte string detected by functions in the exec() family. Such exec()
functions ascertain whether a file is an executable binary or a script.
Note: the space between the shebang and the interpreter directive is optional.
Import Modules
from random import randrange
from subprocess import run
random.randrange()
returns a random integer within a specific range.subprocess.run()
executes Bash command described by args from Python.
subprocess.run()
After the script is done juggling and playing slight of hand with characters, rand_host
is passed as an arg to hostnamectl
through the subprocess.run()
method.
run(['sudo', 'hostnamectl', 'set-hostname', rand_host], check=True)
subprocess.run()
runshostnamectl
in Bash, waits forhostnamectl
to finish, then returns aCompletedProcess
instance.check=True
capturesstdout
orstderr
.
random.randrange()
random.randrange()
returns a peudo-random number. psuedo-random, basically, because random logic is an oxymoron. random.randrange()
takes three integers: random.randrange(start, stop, increment). The integer returned becomes a Unicode code point passed to the chr() built-in method, where chr(97)
returns 'a'
, so chr(randrange(97, 123, 1))
will return a pseudo-random lowercase letter between 'a'
and 'z'
, just as the f-string f'{rand_lwr()}'
returns a lowercase letter.
rand_host
An f-string is assigned to rand_host
. Each set of braces contains an embedded expression. For example, the f-string f'{rand_az()}'
could become 'q'
, since rand_az()
returns a random lowercase letter.
rand_host = f'{rand_az()}{rand_AZ()}{rand_09()}{rand_az()}{rand_AZ()}{rand_09()}'
rand_host
would contain something akin to mV4jA8
, as each embedded expression returns a character. See Example Prompt section.
Example Prompt
foo@sA1nJ5:~/Desktop $