Skip to content

Instantly share code, notes, and snippets.

@operatorequals
Last active May 6, 2018 18:31
Show Gist options
  • Save operatorequals/d654ece10f3dcfc74d08f8b08e5d656c to your computer and use it in GitHub Desktop.
Save operatorequals/d654ece10f3dcfc74d08f8b08e5d656c to your computer and use it in GitHub Desktop.
Parses Connection Strings like "protocol://[host[:password]]@host[:port]" - supports Public Key passing instead of Password
def parse_conn_string(conn_string):
'''
Parses string like:
smb://username@host:445
sftp://host:22
ssh://host:22
sftp://username#pub_key_path@host:22
sftp://username:password@host:22
sftp://username:password@192.168.1.5:22
*Used in satori-remote:
https://github.com/satori-ng/satori-remote/blob/master/satoriremote/__init__.py
'''
arg_regex = r'(\w*)://((\w*)(([:#])(.+))?@)?([\.\w]*)(\:(\d+))?'
m = re.match(arg_regex, conn_string)
try:
conn_dict={}
conn_dict['protocol'] = m.group(1)
conn_dict['username'] = m.group(3)
conn_dict['auth_type'] = "key" if m.group(5) == '#' else "passwd"
conn_dict['auth'] = m.group(6)
conn_dict['host'] = m.group(7)
try:
conn_dict['port'] = int(m.group(9))
except: # if :port is not defined
conn_dict['port'] = None
pass
if conn_dict['username'] is None:
conn_dict['username'] = raw_input("Username:")
if conn_dict['auth'] is None:
import getpass
conn_dict['auth'] = getpass.getpass("Password:")
return conn_dict
except AttributeError:
raise ValueError("'{}' is not a valid remote argument".format(conn_string))
@operatorequals
Copy link
Author

sftp://username:password@0.0.0.0:22

{'protocol': 'sftp', 'username': 'username', 'auth_type': 'passwd', 'auth': 'password', 'host': '0.0.0.0', 'port': 22}

sftp://username#path/to/key@0.0.0.0:22

{'protocol': 'sftp', 'username': 'username', 'auth_type': 'key', 'auth': 'path/to/key', 'host': '0.0.0.0', 'port': 22}

@operatorequals
Copy link
Author

operatorequals commented May 6, 2018

Test it out on:
Regex101.com.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment