从php执行python脚本

时间:2015-05-21 07:31:04

标签: php python

我有以下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脚本时,它无法正常运行...只有第一个print语句才会进入浏览器....而脚本在执行时工作正常终端......请帮助......

1 个答案:

答案 0 :(得分:0)

功能横幅($ name){

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