【问题标题】:Executing python script from php从php执行python脚本
【发布时间】:2015-05-21 07:31:04
【问题描述】:

我有以下 php 代码,它正在调用与 php 文件位于同一文件夹中的 python 脚本 nmapdb.py。

function banner($name) {

$output = exec('python nmapdb.py $name');
echo $output;

}

python scipt 如下:

ip=sys.argv[1]
print("Please get cup of coffee...Coz I am gonna take some time...")
nm=nmap.PortScanner()
nm.scan(hosts=ip , arguments='-sV --script=banner')
result=nm.get_nmap_last_output()
fo=open("result.xml","w")
fo.write(result)
fo.close()

con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');


tree=etree.parse('result.xml')
root=tree.getroot()
root.tag
entries=tree.findall('host')
i=0
while i < len(entries):
    sub=entries[i].find('address')
    adr=sub.attrib['addr']
    adrtype=sub.attrib['addrtype']
    sub=entries[i].find('ports')
    sub1=sub.findall('port')
    j=0
    while j < len(sub1):
        prot=sub1[j].attrib['protocol']
        prtid=sub1[j].attrib['portid']
        sub2=sub1[j].find('state')
        stat=sub2.attrib['state']
        sub2=sub1[j].find('service')
        servname=sub2.attrib['name']
        try:
           sub2.attrib['product']
        except KeyError:
           prod='unknown'
        else:
           prod=sub2.attrib['product']
        try:
           sub2.attrib['devicetype']
        except KeyError:
           devtype='unknown'
        else:
           devtype=sub2.attrib['devicetype']
        try:
           sub2.attrib['ostype']
        except KeyError:
           os='unknown'
        else:
           os=sub2.attrib['ostype']
        j=j+1
        comm= "http://api.hostip.info/get_json.php?ip="+adr+"&position=true"
        response = urllib.urlopen(comm).read()
        data=json.loads(response)
        country=data['country_name']
        city=data['city']


        with con:

                cur = con.cursor()
                cur.execute("""INSERT INTO nmap_table (Ip_Addr, Addr_Type, Protocol, Port_Id, State, Service_Name, Product, Device, OS, Country, City) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (adr, adrtype, prot, prtid, stat, servname, prod, devtype, os, country, city))
        i=i+1
print("Kudos....I'm done....Please check the database...")

但问题是,当我从 php 调用 python 脚本时,它无法正常工作......只有第一个打印语句进入浏览器......而脚本在执行时工作正常终端...请帮助....

【问题讨论】:

  • exec "命令结果的最后一行" 使用第二个参数进行输出捕获

标签: php python


【解决方案1】:

函数横幅($name){

$output = exec('python nmapdb.py $name', $full_output); 回声$输出; // 这里只是脚本的最后一行 print_r($full_output); // 这里将是python脚本的所有控制台输出 }

【讨论】:

  • 我已经尝试过您的解决方案,但仍然无法正常运行......浏览器中的输出为“数组”......谢谢......
  • echo implode('',$full_output)
最近更新 更多