utils.py - Supporting Functions

Gate One utility functions and classes.

exception utils.UnknownFacility[source]

Raised if string_to_syslog_facility() is given a string that doesn't match a known syslog facility.

exception utils.MimeTypeFail[source]

Raised by create_data_uri() if the mimetype of a file could not be guessed.

utils.noop()[source]

Do nothing (i.e. "No Operation")

utils.gen_self_signed_ssl(notAfter=None)[source]

This method will generate a secure self-signed SSL key/certificate pair saving the result as 'certificate.pem' and 'keyfile.pem' in the current working directory. By default the certificate will be valid for 10 years but this can be overridden by passing a valid timestamp via the notAfter argument.

Examples:

gen_self_signed_ssl(60 * 60 * 24 * 365) # 1-year certificate
gen_self_signed_ssl() # 10-year certificate
utils.none_fix(val)[source]

If val is a string meaning 'none', return None. Otherwise just return val as-is. Examples:

>>> import utils
>>> utils.none_fix('none')
None
>>> utils.none_fix('0')
None
>>> utils.none_fix('whatever')
'whatever'
utils.str2bool(val)[source]

Converts strings like, 'false', 'true', '0', and '1' into their boolean equivalents. If no logical match is found, return False. Examples:

>>> import utils
>>> utils.str2bool('false')
False
>>> utils.str2bool('1')
True
>>> utils.st2bool('whatever')
False
utils.generate_session_id()[source]

Returns a random, 45-character session ID. Example:

>>> utils.generate_session_id()
'NzY4YzFmNDdhMTM1NDg3Y2FkZmZkMWJmYjYzNjBjM2Y5O'
utils.mkdir_p(path)[source]

Pythonic version of "mkdir -p". Example equivalents:

>>> import commands, utils
>>> utils.mkdir_p('/tmp/test/testing') # Does the same thing as below:
>>> commands.getoutput('mkdir -p /tmp/test/testing')
utils.cmd_var_swap(cmd, session=None, user_dir=None, user=None, time=None)[source]

Returns cmd with special inline variables swapped out for their respective argument values. The special variables are as follows:

%SESSION% - session %USERDIR% - user_dir %USER% - user %TIME% - time

This allows for unique or user-specific values to be swapped into command line arguments like so:

ssh_connect.py -M -S '/tmp/%SESSION%/%r@%h:%p'
utils.kill_dtached_proc(session, term)[source]

Kills the dtach session associated with the given term and all its sub-processes. Requires session so it can figure out the right processess to kill.

utils.killall(session_dir)[source]

Kills all running Gate One terminal processes including any detached dtach sessions. session_dir - The path to Gate One's session directory.

Creates symbolic links for all plugins in the ./static/ directory. The equivalent of:

root@host:~ $ ln -s *plugin_dir*/<plugin>/static *static_dir*/<plugin>

This is so plugins can reference files in their static directories using the following straightforward path:

https://<gate one>/static/<plugin name>/<some file>

This function will also remove any dead links if a plugin is removed.

utils.get_plugins(plugin_dir)[source]

Adds plugins' Python files to sys.path and returns a dictionary of JavaScript, CSS, and Python files contained in plugin_dir like so:

{
    'js': [ # NOTE: These would be be inside *plugin_dir*/static
        '/static/happy_plugin/whatever.js',
        '/static/ssh/ssh.js',
    ],
    'css': ['/static/ssh/ssh.css'],
    'py': [ # NOTE: These will get added to sys.path
        'happy_plugin',
        'ssh'
    ],
}

*.js files inside of plugin_dir/<the plugin>/static will get automatically added to Gate One's index.html like so:

{% for jsplugin in jsplugins %}
    <script type="text/javascript" src="{{jsplugin}}"></script>
{% end %}

*.css files will get added to the <head> like so:

{% for cssplugin in cssplugins %}
    <link rel="stylesheet" href="{{cssplugin}}" type="text/css" media="screen" />
{% end %}
utils.load_plugins(plugins)[source]

Given a list of plugins, imports them. NOTE: Assumes they're all in sys.path.

utils.merge_handlers(handlers)[source]

Takes a list of Tornado handlers like this:

[
    (r"/", MainHandler),
    (r"/ws", TerminalWebSocket),
    (r"/auth", AuthHandler),
    (r"/style", StyleHandler),
        ...
    (r"/style", SomePluginHandler),
]

...and returns a list with duplicate handlers removed; giving precedence to handlers with higher indexes. This allows plugins to override Gate One's default handlers. Given the above, this is what would be returned:

[
    (r"/", MainHandler),
    (r"/ws", TerminalWebSocket),
    (r"/auth", AuthHandler),
        ...
    (r"/style", SomePluginHandler),
]

This example would replace the default "/style" handler with SomePluginHandler; overriding Gate One's default StyleHandler.

utils.convert_to_timedelta(time_val)[source]

Given a time_val (string) such as '5d', returns a timedelta object representing the given value (e.g. timedelta(days=5)). Accepts the following '<num><char>' formats:

Character Meaning Example
s Seconds '60s' -> 60 Seconds
m Minutes '5m' -> 5 Minutes
h Hours '24h' -> 24 Hours
d Days '7d' -> 7 Days

Examples:

>>> import utils
>>> utils.convert_to_timedelta('7d')
datetime.timedelta(7)
>>> utils.convert_to_timedelta('24h')
datetime.timedelta(1)
>>> utils.convert_to_timedelta('60m')
datetime.timedelta(0, 3600)
>>> utils.convert_to_timedelta('120s')
datetime.timedelta(0, 120)
utils.process_opt_esc_sequence(chars)[source]

Parse the chars passed from terminal.py by way of the special, optional escape sequence handler (e.g. '<plugin>|<text>') into a tuple of (<plugin name>, <text>). Here's an example:

>>> import utils
>>> utils.process_opt_esc_sequence('ssh|user@host:22')
('ssh', 'user@host:22')
utils.raw(text, replacement_dict=None)[source]

Returns text as a string with special characters replaced by visible equivalents using replacement_dict. If replacement_dict is None or False the global REPLACEMENT_DICT will be used. Example:

>>> import utils
>>> test = '\x1b]0;Some xterm title'
>>> print(utils.raw(test))
'^[]0;Some title^G'
utils.string_to_syslog_facility(facility)[source]

Given a string (facility) such as, "daemon" returns the numeric syslog.LOG_* equivalent.

utils.create_data_uri(filepath)[source]

Given a file at filepath, return that file as a data URI.

Raises a MimeTypeFail exception if the mimetype could not be guessed.

Previous topic

termio.py - Terminal Input/Output Module

Next topic

gateone.js

This Page