You can use the urlparse.urlsplit()
function (which is also available in Python 2); the .netloc
parameter would contain the username and password (which both would be escaped to not contain plain :
or @
characters, see RFC 3986 Section 3.2.1):
import urlparse
def starPassword(route):
parsed = urlparse.urlsplit(route)
if '@' not in parsed.netloc:
return route
userinfo, _, location = parsed.netloc.partition('@')
username, _, password = userinfo.partition(':')
if not password:
return route
userinfo = ':'.join([username, '*****'])
netloc = '@'.join([userinfo, location])
parsed = parsed._replace(netloc=netloc)
return urlparse.urlunsplit(parsed)
Demo:
>>> starPassword('smtp://foobar%40example.com:abc@smtp.example.com:465')
'smtp://foobar%40example.com:*****@smtp.example.com:465'
>>> starPassword('smtp://foobar:abc@smtp.example.com:25')
'smtp://foobar:*****@smtp.example.com:25'
>>> starPassword('smtp://smtp.example.com:1234')
'smtp://smtp.example.com:1234'
>>> starPassword('smtp://foo@smtp.example.com:42')
'smtp://foo@smtp.example.com:42'