Skip to content

Instantly share code, notes, and snippets.

@meeuw
Last active October 23, 2015 19:40
Show Gist options
  • Save meeuw/3c6e899ea8561ae15513 to your computer and use it in GitHub Desktop.
Save meeuw/3c6e899ea8561ae15513 to your computer and use it in GitHub Desktop.
start ssh connection from bottle and send some data to stdin
import threading
from StringIO import StringIO
runcmdLock = threading.Lock()
def runcmd(keyf, username, send):
runcmdLock.acquire(True)
while 1:
if not (keyf, username) in default_app().chan:
key = RSAKey.from_private_key(file_obj=StringIO(keyf))
client = SSHClient()
client.load_system_host_keys('/usr/local/etc/ssh/ssh_known_hosts')
client.connect('127.0.0.1', pkey=key, username=username)
chan = client.invoke_shell()
chan.settimeout(0.0)
default_app().chan[(keyf, username)] = chan
default_app().client[(keyf, username)] = client
else:
chan = default_app().chan[(keyf, username)]
try:
chan.sendall(send)
break
except socket.error:
print 'socket.error'
default_app().chan[(keyf, username)] = None
ret = ''
while not ret.startswith(send[:-1]+'\r\n'):
rlist, wlist, xlist = select.select([chan], [], [], 10)
if rlist:
ret += chan.recv(2048)
#print 1, [ret]
ret = ret[len(send)+1:]
while not '\r\n' in ret:
rlist, wlist, xlist = select.select([chan], [], [], 10)
if rlist:
ret += chan.recv(2048)
#print 2, [ret]
runcmdLock.release()
return ret
app = default_app()
app.chan = {}
app.client = {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment