简体   繁体   中英

port scanner in python

  if data.find('!scan') != -1:
     nick = data.split('!')[ 0 ].replace(':','')
     targetip = gethostbyname(arg)
     sck.send('PRIVMSG ' + chan + " :" ' scanning host' + targetip + '\r\n')
     for i in range(20, 1025):
         s = socket(AF_INET, SOCK_STREAM)
         result = s.connect_ex((targetip, i))
         if (result == 0) :
              s.send('PRIVMSG ' + chan + " :" 'port %d: OPEN' % (i,) + '\r\n')
         s.close()

I'm trying to code a small portscanner for my IRC bot, and I keep getting this error..

NameError: name 'gethostbyname' is not defined
>>> import socket
>>> socket.gethostbyname('localhost')
'127.0.0.1'

As mentioned make sure you imported the socket module, and depending on how you did that you can call gethostbyname() .

At the top of your script, it's looks like you performed:

from socket import *

Or something "relatively" large that's bringing socket names directly into yours global namespace.

You shouldn't do that because it's bad practice and causes issues like the one you're experiencing where you're confusing socket.socket (the class) with socket (the module). Your namespace has become muddled with everything that gets imported from the socket module, which is a lot:

>>> import socket
>>> len(socket.__all__)
241

( __all__ being the module variable that specifies the public names for a module and dictates what gets exported when someone performs a from x import * on your module).

241 is a lot of distinct names to import into the global namespace (assuming that's the case) and gives you a lot of rope with which to hang yourself as far as overwriting or accidentally reusing variables that were imported from socket .

gethostbyname should be imported from somewhere? Try socket.gethostbyname() , or whatever you imported socket as.

You can do port scans pretty easily in about 2 lines with Scapy . You can dump the DNS name of your target directly into it. If you still need the target's IP address though, remember to import socket before calling socket.gethostbyname .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM