-1

I have to write a python code to execute some commands from a client. The python script needs to be there in client1 machine.

The command has to be executed in client3. but client3 is not accessible directly from client1. We need to do first ssh to "client2" server and then ssh to client3.

Is there a way out?

esham
  • 1
  • 1
  • us3 iptables on host1 to forward packets to host2 – Pedro Lobito Apr 19 '17 at 09:31
  • I'm not sure what the problem is. If there was no gateway server, you'd do `ssh client2 "command"`, so can't you just `ssh gateway "ssh client2 'command'"`? – Aran-Fey Apr 19 '17 at 09:42
  • The client2 is not directly reachable from client1. You need to first login to gateway server and from that machine, ssh to client2 – esham Apr 19 '17 at 09:47
  • This concept with logging in intermediate host is known as `bastion host`. https://10mi2.wordpress.com/2015/01/14/using-ssh-through-a-bastion-host-transparently/ and http://blog.scottlowe.org/2015/11/21/using-ssh-bastion-host/ for some details and how to issue the `ssh` commands. – zloster Apr 19 '17 at 14:19

1 Answers1

1

I Haven't managed this personally, but you sound like you could make use of the following answer: How to execute a process remotely using python

Here's the example that answer gives:

import subprocess
ret = subprocess.call(["ssh", "user@host", "program"]);

# or, with stderr:
prog = subprocess.Popen(["ssh", "user@host", "program"], stderr=subprocess.PIPE)
errdata = prog.communicate()[1]

Using the subprocess library you can execute SSH and then execute commands on the client 2 machine from your client 1 with your python code.

Hope it helps!

Community
  • 1
  • 1
beerandsmiles
  • 104
  • 3
  • 11
  • You can also start ssh as `Popen(['ssh', 'user@host'], stdin=PIPE)` and execute commands with `process.stdin.write('command\n')`, which is useful if you're going to send a lot of commands. – Aran-Fey Apr 19 '17 at 09:46
  • >>Popen(['ssh', 'user@host'], stdin=PIPE) How to pass password for ssh here? – esham Apr 19 '17 at 10:30
  • Having a look through that answer above, it seems the best solution is to set up SSH keys to avoid passwords altogether. – beerandsmiles Apr 19 '17 at 22:06