简体   繁体   中英

SSH persistent connection using pxssh in flask

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')

Try calling:

ssh = connect_ssh()

only once under "app = Flask()" line and rerun it and it will run only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM