【问题标题】:SSH persistent connection using pxssh in flask在烧瓶中使用 pxssh 的 SSH 持久连接
【发布时间】:2016-01-05 17:10:05
【问题描述】:

我正在开发 Web 界面以使用 pxssh 在远程服务器上运行命令。无论如何我可以创建持久的 ssh 连接,下面的代码为每个请求调用 connect_ssh。

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

【问题讨论】:

    标签: python ssh flask pexpect


    【解决方案1】:

    尝试调用:

    ssh = connect_ssh()

    在“app = Flask()”行下只运行一次,然后重新运行它,它只会运行一次。

    【讨论】:

    • 现在我得到 AttributeError: 'NoneType' object has no attribute 'ssh_conn'
    • 感谢 usre42635,我将 get_ssh 移到了下面的块中,它只被 app.app_context():ssh = get_ssh() 调用一次
    猜你喜欢
    • 1970-01-01
    • 2015-07-14
    • 2013-09-13
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2015-04-09
    相关资源
    最近更新 更多