0

I am trying to access a remote machine to execute remote a Python script (remote_test.py).

I changed the SSH configuration so that if I enter ssh user@ip from host terminal it connects to remote system without asking for password.

When I run a Python script on the host machine to execute remote_test.py by using SSH in a subprocess call like this:

P = subprocess.Popen(
    [
        "ssh",
        "user@some_ip",
        "sudo",
        "python",
        "/home/path/remote_test.py",
    ],
    shell=False,
    stdout=subprocess.PIPE
)

It requires me to enter a password.

How can I access the remote machine without needing to enter a password?

Environment:

  • Python version 2.7
  • Host and Remote systems are both using Ubuntu 14.04 LTS.
jwpfox
  • 5,124
  • 11
  • 45
  • 42

1 Answers1

1

You should not use Popen to run the program ssh, but rather use a library like the excellent paramiko to run ssh commands. It has a documented API for connecting using public keys, which is discussed here: How to ssh connect through python Paramiko with public key

Then you'll be able to do something like this:

import paramiko
ssh = paramiko.SSHClient()

ssh.connect('some_ip', username='user', key_filename='keyfile')

stdin, stdout, stderr = ssh.exec_command('sudo python /home/path/remote_test.py')
Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436