端口扫描程序无法在python中工作

时间:2014-07-31 16:12:55

标签: python optparse

#!/usr/bin/env python

import optparse
import socket
from socket import *
def connScan(tgtHost, tgtPort):
        try:
                connSkt = socket(AF_INET, SOCK_STREAM)
                connSkt.connect((tgtHost, tgtPort))
                connSkt.send('ViolentPython\r\n')
                results = connSkt.recv(100)
                print '[+]%d/tcp open'% tgtPort
                print '[+] ' + str(results)
                connSkt.close()
        except:
                print '[-]%d/tcp closed'% tgtPort
def portScan(tgtHost, tgtPorts):
        try:
                tgtIP = gethostbyname(tgtHost)
        except:
                print "[-] Cannot resolve '%s': Unknown host" %tgtHost
                return
        try:
                tgtName = gethostbyaddr(tgtIP)
                print '\n[+] Scan Results for: ' + tgtName[0]
        except:
                print '\n[+] Scan Results for: ' + tgtIP
        setdefaulttimeout(1)
        for tgtPort in tgtPorts:
                print 'Scanning port ' + tgtPort
                connScan(tgtHost, int(tgtPort))
def main():
        parser = optparse.OptionParser("usage%prog " +\ "-H <target host> -p <target port>")
        parser.add_option('-H', dest='tgtHost', type='string', \ help='specify target host')
        parser.add_option('-p', dest='tgtPort', type='string', \ help='specify target port[s] separated by comma')
        (options, args) = parser.parse_args()
        tgtHost = options.tgtHost
        tgtPorts = str(options.tgtPort).split(', ')
        if (tgtHost == None) | (tgtPorts[0] == None):
                print parser.usage
                print '[-] You must specify a target host and port[s].'
                exit(0)
        portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
        main()

getting an error that :
 File "scanner.py", line 33
    parser = optparse.OptionParser("usage%prog " +\ "-H <target host> -p <target port>")
                                                                                       ^
SyntaxError: unexpected character after line continuation character

1 个答案:

答案 0 :(得分:1)

Python将裸\字符解释为'我将在下一行继续',因此短版本是删除\,制作行:

    parser = optparse.OptionParser("usage%prog " + "-H <target host> -p <target port>")

如果你想保留它,并演示你如何使用续行,你可以在\之后立即按回车:

parser = optparse.OptionParser("usage%prog " +\
     "-H <target host> -p <target port>")

请注意,在最后一个示例中\之后没有任何内容,甚至没有空格。

如果您想要nmap功能而不仅仅是为了学习的乐趣,那么值得查看python-nmap模块:http://xael.org/norman/python/python-nmap/