1

I want to connect from one remote server to other using python script.I already tried in shell script and its works well but it will cause future issues.Hence I want to stick up with python.

I have tried all the links given in stackoverflow and github.But it did not work for me.

The code I tried: [1] CODE 1

import sys
import os
import subprocess
from subprocess import Popen, PIPE, STDOUT
from time import sleep
from os import waitpid, execv, read, write
 #Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="root -a"
ssh = subprocess.Popen(['ssh', 'root@10.10.10.3',  COMMAND],
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result

Connection should be successful using python and one should be able to connect and run any command from one remote server to other using this code.

user34
  • 103
  • 1
  • 1
  • 7

1 Answers1

0

you can use a python lib---paramiko

goudan
  • 58
  • 4
  • Including example code that illustrates your point is of most help to readers. Your answer is not adding enough value. Refer to guidelines here: https://stackoverflow.com/help/how-to-answer – avg Mar 25 '19 at 12:02
  • @goudan I tried using paramiko, but it did not work.I got error as: Permission denied.Can you write code for it please.? – user34 Mar 26 '19 at 10:36
  • import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname='c1.salt.com', port=22, username='aaa', password='123') stdin, stdout, stderr = ssh.exec_command('ls') result = stdout.read() ssh.close() – goudan Mar 26 '19 at 10:53
  • you need a public key,you can use your local public key. import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key) stdin, stdout, stderr = ssh.exec_command('df') result = stdout.read() ssh.close() – goudan Mar 27 '19 at 06:47