pythonsshsubprocessssh-keygen

SSH key asks for passphrase when created using subprocess in python


I have a python project that is supposed to be used for creating a SSH key with ssh-keygen and add it to some remote servers. When I run the command ssh-keygen -f .ssh/id_rsa -t rsa -N "" from the command line everything works fine, and I can simply run the rest of the python code to transfer my key to the remote servers. After that the SSH connections can be made using the key successfully, either from paramiko in python or from the command line.

However, when I run the very same command to create the key using the subprocess library in python, I can't use the key to make connections since it prompts for passphrase, like Enter passphrase for key 'C:\Users\<my_user>/.ssh/id_rsa':. My python code for building the SSH key is as follows:

from pathlib import Path
import subprocess

LOCAL_SSH_KEY_FOLDER = Path().home() / ".ssh"
command = f'-f {LOCAL_SSH_KEY_FOLDER}/id_rsa -t rsa -N ""'
p = subprocess.Popen(["ssh-keygen"] + command.split(' '), stdout=subprocess.PIPE, 
                     stderr=subprocess.PIPE, text=True)
result, errors = p.communicate()

One way to make it work is to remove the N "" part and ask the python code user to input an empty passphrase. It works, but I don't want my user to be prompted for this passphrase.


Solution

  • Thanks to @Kenster, I found out that when I executed the original python script, the SSH key passphrase was set to "" (two double quotes), rather than being empty. The solution was to change the command parameter in the code using the following line, and the problem was gone.

    f'-f {LOCAL_SSH_KEY_FOLDER}/id_rsa -t rsa -N '