SSH persistent connection using pxssh in flask

杀马特。学长 韩版系。学妹 提交于 2019-12-13 07:16:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!