我正在学习Python并遇到问题。我无法在Windows CMD中执行以下代码。我尝试了一个“Hello World”程序并按预期执行。但是当我尝试这个程序时,什么都没发生。没有错误消息或任何东西。我使用python 3.3和Pycharm 3.1。
__author__ = 'Johan'
import optparse
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 ('[-] Can not resolve '': 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=str, \
help='specify target host')
parser.add_option('-p', dest='tgtPort', type='int', \
help='specify target port[s] separated by comma')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = options.tgtPort
if(tgtHost is None) | (tgtPorts[0] is None):
print('[-] You must specify a target host and port[s]')
exit(0)
portScan(tgtHost, tgtPorts)
if __name__== '__main__':
main()
答案 0 :(得分:2)
你的缩进都被破坏了 - 除了其他答案和评论中提到的if __name__ == "main"
问题之外,每个函数都嵌套在它之前的那个中,这可能不是它应该的样子。你可能想要这样的东西:
__author__ = 'Johan'
import optparse
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 ('[-] Can not resolve '': 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=str, \
help='specify target host')
parser.add_option('-p', dest='tgtPort', type='int', \
help='specify target port[s] separated by comma')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = options.tgtPort
if(tgtHost is None) | (tgtPorts[0] is None):
print('[-] You must specify a target host and port[s]')
exit(0)
portScan(tgtHost, tgtPorts)
if __name__== '__main__':
main()