Skip to content

Instantly share code, notes, and snippets.

@relthyg
Last active October 11, 2021 21:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save relthyg/56cc0ccd1bc8f7ae1032b89af3759ed0 to your computer and use it in GitHub Desktop.
Save relthyg/56cc0ccd1bc8f7ae1032b89af3759ed0 to your computer and use it in GitHub Desktop.
mysql-dsn: Connect to a mysql database from the command line using a DSN as argument
#!/usr/bin/env python3
#
# mysql-dsn
# Takes a DSN as argument and tries to connect to the specified database using the "mysql"-command.
# Passwords must be quoted ("url-encoded").
#
# Example:
# $ mysql-dsn mysqli://me:top_secret@hostname:33006/db-name
import re
import subprocess
import sys
import urllib.parse
if len(sys.argv) < 2:
print("Syntax: " + sys.argv[0] + " {DSN}")
sys.exit(1)
dsn = sys.argv[1]
netloc_regex = re.compile(r"(?:([^:]+)(?::(.*))?@)?([^:]+)(?::([\d]+))?")
scheme, netloc, path, params, query, fragment = urllib.parse.urlparse(dsn)
username, password, host, port = netloc_regex.search(netloc).groups()
subprocess.run([
"mysql", path.replace("/", ""),
"--user", username,
"--host", host,
"--port", str(port),
"-p"+urllib.parse.unquote(password)
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment