我正在使用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')
答案 0 :(得分:1)
尝试致电:
ssh = connect_ssh()
在“app = Flask()”行下只运行一次并重新运行它,它只运行一次。