Reputation: 44405
I have two machines, A
and B
. Both machines can be either Windows or Linux machines, but - for simplicity - I know beforehand which is which. I also know a username and a password for the remote machine B
(no other authentication method). So I have four possible combinations:
A=Windows B=Windows
A=Windows B=Linux
A=Linux B=Windows
A=Linux B=Linux
I am looking for a small python script (or better: standard library) with which it is possible to execute a remote command on B
from A
. To be precise: On machine A
I start a python script to run some command cmd
on the remote machine B. Is there a generic way to do so in python?
For the Linux->Linux combination I could think using ssh
for example and subprocess
, but I probably run into problems with the username/password authentication.
For the Windows->Windows combination there is a tool called psservice
which I already have been using (together with subprocess).
Any idea how to solve this problem in a most pythonic way? Does not need to be one function, it can be implemented in four different ways. And, if possible, without the use of third-party libraries (which is somewhat inconsistent, as psservice
is already a third-party library I am using...).
Upvotes: 2
Views: 3241
Reputation: 11
Try paramiko. I am using it and it is very simple to use.
EDIT 1
host='IP'
username='user'
password='password'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username, password)
stdin, stdout, stderr = ssh.exec_command("pwd")
stdout.read()
ssh.close()
EDIT 2:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=password)
stdin, stdout, stderr = ssh.exec_command('pwd')
stdout.read()
ssh.close()
EDIT 3 Here also a solution using private/public keys:
key = paramiko.RSAKey.from_private_key_file(keyDest, keyPass)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, pkey=key)
stdin, stdout, stderr = ssh.exec_command('pwd')
stdout.read()
ssh.close()
Both, EDIT 1 and EDIT 3 works fine in my script..
Upvotes: 1
Reputation: 60644
I suggest using ssh/sftp, via the paramiko library.
All major ciphers and hash methods are supported. SFTP client and server mode are both supported too.
And it is cross-platform.
Upvotes: 1