Skip to content
4 changes: 2 additions & 2 deletions mycli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
from .lexer import MyCliLexer
from .__init__ import __version__
from .compat import WIN
from .packages.filepaths import dir_path_exists
from .packages.filepaths import dir_path_exists, guess_socket_location

import itertools

Expand Down Expand Up @@ -429,7 +429,7 @@ def _connect():
# Try a sensible default socket first (simplifies auth)
# If we get a connection error, try tcp/ip localhost
try:
socket = '/var/run/mysqld/mysqld.sock'
socket = guess_socket_location()
_connect()
except OperationalError as e:
# These are "Can't open socket" and 2x "Can't connect"
Expand Down
16 changes: 15 additions & 1 deletion mycli/packages/filepaths.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
from mycli.encodingutils import text_type
import os

DEFAULT_SOCKET_DIRS = ('/var/run/', '/var/lib/', '/tmp')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/tmp might not be such a good idea; on a multi-user system anyone might create a socket in this directory to intercept passwords...



def list_path(root_dir):
"""List directory if exists.

:param dir: str
:param root_dir: str
:return: list

"""
Expand Down Expand Up @@ -84,3 +86,15 @@ def dir_path_exists(path):

"""
return os.path.exists(os.path.dirname(path))


def guess_socket_location():
"""Try to guess the location of the default mysql socket file."""
socket_dirs = filter(os.path.exists, DEFAULT_SOCKET_DIRS)
for directory in socket_dirs:
for r, dirs, files in os.walk(directory, topdown=True):
for filename in files:
if filename.startswith('mysql') and filename.endswith('.socket'):
return os.path.join(r, filename)
dirs[:] = [d for d in dirs if d.startswith('mysql')]
return ''