我过去对PHP很陌生,因为我过去一直在使用PHP。我正在尝试通过将PHP代码转换为python来练习python。我有以下php代码,可从Web服务器接收POST数据,并通过ssh进行调用,以将远程服务器的文本文件输出回该页面。

app.js:

$(document).ready(function(){
$("button").on('click', function() {
    //call python script to generate report
     $.get("/", function(data){
        $( "#statusOutput" ).val(data);
    });
});
});


gettextoutput.php:

<?php //gettextoutput.php

    $user = 'user';
    $password = 'pass';
    $path = '/path/to/my/text/file';

    if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        $hostname = $_POST['hostname']; //10.139.x.x
        $textoutput = file_get_contents("ftp://$user:$password@$hostname/$path");
        echo $textoutput; // I can use this to display the text output back to the page
    }
?>


我想知道是否也有办法在python中执行此操作?任何信息,将不胜感激!

最佳答案

这应该使您踏上前进的道路。使用必须安装的Flask和FTPlib。这与Flask随附的名为werkzeug(WSGI)的服务器兼容。

#This answers makes a few assumptions | assumes a payload in json format | assumes Flask as framework | Assumes werkzeug as a WSGI server
from Flask import Flask, request, send_file
from ftplib import FTP

app = Flask(__name__)

@app.route('/', methods['POST'])
def get_some_file():
    input = request.get_json()
    ftp = FTP("SOMESERVERFTPIP")
    ftp.login(input['user'],input['password'])
#This will create local file and write contents of ftp file to it
    with open(/local/path/+input['path'], 'w') as f:
        ftp.retrbinary('RETR %s' % input['path'], f.write)

    #Filename should be a path, you may concatenate etc..
    return send_file('/local/path'/+input['filename'],
                     mimetype='text/txt',
                     attachment_filename='filename',
                     as_attachment=True)

关于javascript - Python获取发布数据以调用远程python脚本以显示在页面上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51106909/

10-12 15:00
查看更多