Home > Blockchain >  Python using Subprocess with private key
Python using Subprocess with private key

Time:02-22

I have a problem establishing an SSH connection to a server. My script is quite simple and gives me an error:

user@host: Permission denied (publickey).

The user and host are variables and they are correct:

I believe the problem might be related to the passphrase of my private key as I do not know how to add it to the script.

Could you, please help me? Thank you.

def test_check():
    username = input()
    host = input()
    command = "cd ~/public_html/"
    private_key = "path-to-the-key"
    ssh = subprocess.check_output(["ssh", "-i",private_key, "-p22", "{}@{}".format("username", host), command])

print(test_check())


 

CodePudding user response:

Means that your system can't see the keys. Ensure that you have the keys loaded with "ssh-add -K ".

This works fine for me:

    def fun():
       uname='uname'
       host='server.com'
       command='ls /home/uname/'
       ssh = subprocess.check_output(['ssh', '-i', '~/.ssh/key_rsa', f'{uname}@{host}', command])
       print(ssh)

CodePudding user response:

There are several possible solution.

  1. Run ssh-agent, and supply it with your key. Probably the least problematic option from a safety perspective.

  2. You can use the input argument to check_output (Python 3.4 ). This should be a byte string. From a safety perspective, this is probably not a great idea because it would leave your private key password in a script as plain text.

  3. You could remove the password from your private key (also not a great idea from a safety perspective).

CodePudding user response:

Thank you for the help, I have solved the issue. It was caused by the fact that I attempted to connect through the PyCharm. When I ran the script via terminal it worked properly.

  • Related