How to use ssh-agent in windows in python?

eryk sun eryksun at gmail.com
Thu May 30 01:18:07 EDT 2019


On 5/29/19, Cameron Simpson <cs at cskk.id.au> wrote:
>
> So start with this:
>
>   p = subprocess.Popen('ssh-agent -s', stdin = subprocess.PIPE, stdout =
> subprocess.PIPE, stderr = subprocess.PIPE, shell = True, universal_newlines
> = True)

I'm wary of relying on the default encoding here. ssh-agent probably
writes ASCII or ANSI text to the pipe, and Python defaults to decoding
as ANSI ('mbcs'). However, Windows filesystem paths can use any
Unicode characters. (A filename is a string of up to 255 16-bit
wchar_t values, sans reserved characters, regardless of whether it's
valid UTF-16LE, but let's assume it's valid Unicode text for the sake
of everyone's sanity.) This is a problem when a user name can't be
encoded with the system ANSI codepage. In particular, it's a concern
for the user's %temp% directory (i.e.
"C:/Users/<username>/AppData/Local/Temp") in the SSH_AUTH_SOCK
environment variable.

That said, at least for the MSYS2 build of ssh-agent.exe that's
included with Git, the user's %temp% directory is mapped to "/tmp" in
its emulated POSIX namespace, so this should be okay. Make sure the
Cygwin build behaves the same. Otherwise check whether there's a way
to force it to use UTF-8. MSYS2 apparently respects the LC_CTYPE
environment variable. Without LC_CTYPE set, it fails to even parse the
command line properly:

    >>> bash = r'C:\Program Files\Git\usr\bin\bash.exe'
    >>> command = 'echo αβγδε'
    >>> subprocess.call([bash, '-c', command])
    /usr/bin/bash: echo αβγδε: command not found
    127

With it set, it parses the command correctly and writes UTF-8 encoded
text to stdout when it's a pipe or disk file:

    >>> environ = os.environ.copy()
    >>> environ['LC_CTYPE'] = 'en_US.utf8'
    >>> subprocess.check_output([bash, '-c', command],
    ...     env=environ, encoding='utf-8')
    'αβγδε\n'



More information about the Python-list mailing list