Skip to content

Instantly share code, notes, and snippets.

@yanbe
Created April 13, 2009 13:26
Show Gist options
  • Save yanbe/94443 to your computer and use it in GitHub Desktop.
Save yanbe/94443 to your computer and use it in GitHub Desktop.
# An example of bootstrapping remote echo client via SSH connection
import socket
import subprocess
import sys
host = '192.168.1.20'
SSH_CLIENT = sys.platform=='win32' and 'plink' or 'ssh'
REMOTE_CODE = '''"import os, socket, sys
host = os.environ['SSH_CONNECTION'].split()[0]
port = int(sys.stdin.read())
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while 1:
s.send(s.recv(1024))
s.close()
"'''
p = subprocess.Popen([SSH_CLIENT, host, 'python', '-c', REMOTE_CODE],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 0))
s.listen(1)
port = s.getsockname()[1]
p.stdin.write(str(port))
p.stdin.close()
conn, addr = s.accept()
print 'Connected by', addr
while 1:
conn.send(raw_input('local: '))
data = conn.recv(1024)
if not data: break
print 'remote:', data
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment