问题
I am working on web interface to run command on remote servers using pxssh. Is there anyway I can create persistent ssh connection, below code calls connect_ssh for every request.
from flask import Flask, jsonify, render_template, request, g, current_app
from flask import _app_ctx_stack
from pexpect import pxssh
app = Flask(__name__)
def connect_ssh():
s = pxssh.pxssh()
s.login('localhost', 'user', 'passwd')
return s
def get_ssh():
top = _app_ctx_stack.top
if not hasattr(top, 'ssh_conn'):
top.ssh_conn = connect_ssh()
return top.ssh_conn
@app.route('/_remote_cmd')
def remote_cmd():
cmd = request.args.get('cmd', '', type=str)
ssh = get_ssh()
ssh.sendline(cmd)
ssh.prompt()
res = ssh.before
return jsonify(result=res)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run('0.0.0.0')
回答1:
Try calling:
ssh = connect_ssh()
only once under "app = Flask()" line and rerun it and it will run only once.
来源:https://stackoverflow.com/questions/34509746/ssh-persistent-connection-using-pxssh-in-flask