Last active
October 11, 2021 21:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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