Ssh To Machine Through A Middle Host
In my work with my professor I have to ssh into our server and from there I ssh into each node to run our programs. I am trying to write a python program that will let me do everyt
Solution 1:
You don't need Python to do this. Check the ProxyCommand configuration option for SSH. Here is a tutorial that explains the details.
Solution 2:
With a trick from my colleague, you can ssh/scp from local to nodes directly.
Edit your ~/.ssh/config:
Host *
ControlMaster auto
ControlPath ~/.ssh/master-%r@%h:%p
Host node1 node2 or node*
ProxyCommand ssh server 'nc -w 5 %h 22'
Have fun!
Solution 3:
You can do it with Paramiko:
proxy_command = 'ssh -i %s %s@%s nc %s %s' % (proxy_key, proxy_user, proxy_host, host, 22)
proxy = paramiko.ProxyCommand(proxy_command)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=user, password=password, sock=proxy)
stdin, stdout, stderr = client.exec_command('echo HELLO')
print"Echo: %s" % (", ".join(stdout.readlines()))
client.close()
It works with SFTPClient
too:
proxy_command = 'ssh -i %s %s@%s nc %s %s' % (proxy_key, proxy_user, proxy_host, host, 22)
proxy = paramiko.ProxyCommand(proxy_command)
transport = paramiko.Transport(proxy)
transport.connect(username=user, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
Solution 4:
You can do this by creating a tunnel through your server to the node:
import os, sys, shlex
import subprocess
import paramiko
cmd = "ssh -f -N -p " + str(serverport) + " -l " + serveruser + " -L " + str(tunnelport) + ":" + nodehost + ":" + str(nodeport) + " " + serverhost
args = shlex.split(cmd)
tun = subprocess.Popen(args)
stat = tun.poll()
Once the tunnel is set up you can ftp to the nodes:
transport = paramiko.Transport(("127.0.0.1", tunnelport))
transport.connect(username=nodeusername, password=nodepw)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(localfile, remotefile)
Or you can connect and execute a command using paramiko.SSHClient().connect("127.0.0.1", port=port, username=user, password=pw) and paramiko.SSHClient().exec_command(command).
Then the tunnel process can be killed thus:
p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line inout.splitlines():
if cmd in line:
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
Solution 5:
Use plink root@10.112.10.1 -pw password ls -l
Download plink and copy it to your windows machine
Post a Comment for "Ssh To Machine Through A Middle Host"