My issue is that I have a ports.txt file in it has 4 port numbers. I wish for this program to scan all port numbers specified within the txt file. currently It will only scan the first port number listed in the txt file against the 40 odd IP addresses. I hope my formatting is correct and my detail is enough. ty
import socket
import os
import sys
from datetime import datetime
import win32evtlogutil
import win32evtlog
def main():
### call step 1 function
ipList = network_addr()
# call step 2 function
portList = read_ports()
print(portList)
#call step 3 function
for ip in ipList:
for port in portList:
scan_ports(ip,port)
# call step 4 function
report_to_EventViewer(ipList[0:10], 2) # warning
#report_to_EventViewer(ipList, 1) # error
# processing inputs
# Step 1: process input 1 (subnet or network address):
def network_addr():
while True:
ip_list = []
subnet_Addr = input('Enter a Class-C Network Address or subnet with format (x.x.x): ')
subnet = subnet_Addr.split('.') # subnet is a list of 3 items (octets)
try:
if (len(subnet)==3 and 192<=int(subnet[0])<=223 and 0<=int(subnet[1])<=255 and 0<=int(subnet[2])<=255):
#return subnet_Addr
print('valid subnet: ',subnet_Addr)
for ip in range(11,40,2):
ip_temp = subnet_Addr + '.' + str(ip)
ip_list.append(ip_temp)
return ip_list
else:
value = 'wrong subnet entered'
print(value)
except ValueError:
print('wrong subnet entered, octects must be digits')
# Step 2: process input 2 (read port numbers from ports.txt):
def read_ports():
with open("ports.txt", 'r') as file_path:
port_list = []
for port in file_path:
try:
if int(port) in port_list:
print(f'port: {port} already exists')
else:
port_list.append(int(port))
except:
print(f'the port number: {port} is not a valid integer')
return port_list
else:
print('ports.txt is empty \n .... Exiting Port Scan App')
sys.exit()
# Step 3: scan ports
def scan_ports(ip,port):
# to get and format system time
dateTimeObj = datetime.now()
timeStamp = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S)")
try:
# open log file
with open("ip_port_log.txt","+r") as log:
# create client socket
socket.setdefaulttimeout(0.1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip,port))
if result == 0:
data = "IP:" + ip + ":" + str(port) + " Open " + timeStamp
# write_to_console or display on screen
print(data)
# write in log file
log.write(data + "\n")
else:
data = "IP:" + ip + ":" + str(port) + " Closed/Filtered or host is offline " + timeStamp
# write_to_console or display on screen
print(data)
# write in log file
log.write(data + "\n")
# close the client socket
sock.close()
except socket.error:
print("Can't connect to IP: ", ip)
sys.exit()
except KeyboardInterrupt:
print("User pressed Ctrl+c")
sys.exit()
# Step 4: Report to Event Viewer
# output 3
def report_to_EventViewer(mylist, eventtype):
IP_EVT_APP_NAME = " CheckIPPort - IP-Port Scan Application"
IP_EVT_ID = 7040 ##According to ???
IP_EVT_CATEG = 9876 ##According to ???
IP_EVT_TYPE = win32evtlog.EVENTLOG_WARNING_TYPE # WARNING=2
IP_EVT_ERR = win32evtlog.EVENTLOG_ERROR_TYPE # ERROR=1
IP_EVT_STRS = mylist
IP_EVT_DATA = b"Scan IP Address Event Data"
win32evtlogutil.ReportEvent(IP_EVT_APP_NAME, \
IP_EVT_ID, \
eventCategory=IP_EVT_CATEG, \
eventType=eventtype, \
strings=IP_EVT_STRS, \
data=IP_EVT_DATA)
main()
you issue is in your read_ports method, you return inside the loop so it will ALWAYS only read the first one. Rewrite the method to something like:
def read_ports():
with open("ports.txt", 'r') as file_path:
port_list = []
for port in file_path:
try:
if int(port) in port_list:
print(f'port: {port} already exists')
else:
port_list.append(int(port))
except:
print(f'the port number: {port} is not a valid integer')
if not len(port_list):
print('ports.txt is empty \n .... Exiting Port Scan App')
sys.exit()
return port_list
Related
I am trying to create an exemption that will handle non-existent ip addresses. When I type a random ip address, for instance 122.67.254.1, the program still proceeds to scan for ports instead of
raising an exception. I need for fake IPs like this to be exempted rather than for the port scanning to proceed on a non-existent host.
#!/usr/bin/env python
import socket
import sys
from datetime import datetime
# Clear the screen
# subprocess.call('clear', shell=True)
# Ask for input
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
# Seek user input and validate format using try block
MinRange = int(input("Enter starting port number: "))
MaxRange = int(input("Enter ending port number: "))
CheckRange = range(MinRange, MaxRange + 1, 1)
# Create a function to use the command for a given host and port
def CheckPort(host, port):
s = socket
try:
s.connect((host, port))
except:
return False
else:
return True
# Every scan should create a new file. Check if file exists. If so, delete it
# Open file in append + read mode, create if does not exist
xfile = open("ScanResults", "w")
# Print a nice banner with information on which host we are about to scan
print("-" * 60)
print("Please wait, scanning remote host", remoteServerIP)
print("-" * 60)
# Check what time the scan started
t1 = datetime.now()
# Using the range function to specify ports (here it will scans all ports between 1 and 1024)
# We also put in some error handling for catching errors
try:
for port in range(MinRange, MaxRange):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result: int = sock.connect_ex((remoteServerIP, port))
if result == 0:
print("Port {}: Open".format(port))
xfile.write(result)
sock.close()
except KeyboardInterrupt:
print("You pressed Ctrl+C")
sys.exit()
except socket.gaierror:
print('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print("Couldn't connect to server")
sys.exit()
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
# Printing the information to screen
print('Scanning Completed in: ', total)
# notify user process has finished
start = t1
end = t2
print("Task completed. Port range", MinRange, " - ", MaxRange, " has been scanned. ")
elapsed = end - start
now = datetime.now()
dt_string = now.strftime("%m/%d/%Y %H:%M:%S")
print("Scan completed at: ", dt_string)
print("Total scan time: ", elapsed, "seconds.")
#FinTup = ["Port", globals(Newvar), "is open", "\n"]
#FinOut = ''.join(FinTup)
FinTup = ["Scan completed at", str(dt_string), "\n"]
FinOut = ''.join(FinTup)
xfile.write(FinOut)
FinTup = ("Total scan time:", str(elapsed), "seconds.", "\n")
FinOut = ''.join(FinTup)
xfile.write(FinOut)
xfile.close()
I'm implementing a circular distributed hash table, each peer knows its immediate successor and set up TCP connection with its successor, like, 1->3->4->5->8->1.
User will input a 4-digit number, and we proceed it into a certain value using a hash function written by us. For example, user inputs 3456, corresponding hash value is 128. Peer 3 get the input from user, and pass the hash value to its successor(4) asking if he is greater than hash value. If not, the successor will pass the hash to its successor(5). Repeat this until it find the right peer. (Here, since 8 < 128, we say peer 1 is the one we want)
Now, we know peer 1 is the peer we want. Then we let peer 1 make a TCP connection with the requesting peer 3, and send 3 "FIND1,3456,3", when peer 3 get this message, it should print out "peer 1 has the value".
The problem I met is, after I find peer 1 is the one I want, my peer 1 client sets up TCP connection with peer 3 server (peer 1 client said the connection is set up), but peer 3 doesn't get any message from peer 1, what's wrong with it?
How should I fix it?
Thanks for your patience to read these, feel free to ask if there is anything ambiguous :)
#!/usr/bin/python2.7
import sys
import socket
import time
import threading
import re
from collections import defaultdict
successor = defaultdict(dict)
peer = int(sys.argv[1])
successor[1] = int(sys.argv[2])
successor[2] = int(sys.argv[3])
serverName = 'localhost'
peerPort = 50000 + int(peer)
address = (serverName,peerPort)
#-------------proceed input string---------------------------
def getFileNum(name):
fileValid = re.match('^request ([0-9]{4})$',name)
if fileValid is None:
print 'invalid file!'
return
else:
hashName = fileValid.group(1)
return hashName
#----------------get request input--------------------------------
def getRequestInput(clientSocketTCP):
while flag == 0:
fileName = raw_input()
hashname = getFileNum(fileName)
if hashname is not None:
hashname = re.sub('^(0)*','',hashname)
hashnum = int(hashname) % 256
info = 'FILE_REQUEST'+str(hashname) + ','+ str(hashnum) + ','+ str(peer) + ',1'
clientSocketTCP.send(info)
print 'File request message for '+ str(hashname) + ' has been sent to my successor.'
clientSocketTCP.close()
#-------------------send file to successor---------------------------
def sendRequestToS(clientSocketTCP):
global important
while flag == 0:
if important:
an = re.match('^FILE_REQUEST([0-9]{4}),',important)
if an:
hashname = an.group(1)
clientSocketTCP.send(important)
print 'File request message for '+ str(hashname) + ' has been sent to my successor.'
important = ''
clientSocketTCP.close()
#-----------------------find file-------------------------------------
def findF():
global flag
global important
while flag == 0:
if re.match('^FIND',important):
obj = re.match('^FIND[0-9]{1,3},([0-9]{4}),([0-9]{1,3})',important)
n = int(obj.group(2))
info = important
ff = threading.Thread(target=clientTCPTemp,args=(n,info))
ff.start()
ff.join()
important = ''
#--------------------set up client temporary---------------------------
def clientTCPTemp(n,info):
global flag
clientConn = False
clientSocketTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverPortTCP = 50000 + n
print serverPortTCP
while not clientConn:
try:
clientSocketTCP.connect((serverName,serverPortTCP))
clientConn = True
print "Now client connection works!!!!!"
except:
print "fail"
clientSocketTCP.send(info)
print info
print 'A response message, destined for peer '+ str(n) +', has been sent.'
clientSocketTCP.close()
#--------------------TCP server---------------------------------------
def serverTCP():
global flag
global serverSetUp
global important
serverSocketTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverConn = False
while not serverConn:
try:
serverSocketTCP.bind((serverName,peerPort))
serverConn = True
serverSocketTCP.listen(2)
serverSetUp = 0
print 'The server is ready to receive'
except:
pass
while flag == 0:
connectionSocket, addr = serverSocketTCP.accept()
print 'connect by'+ str(addr)
threeinfo = connectionSocket.recv(1024)
print threeinfo
if re.match('^FILE_REQUEST',threeinfo):
obj = re.match('^FILE_REQUEST([0-9]{4}),([0-9]{1,3}),([0-9]{1,3}),([01])$',threeinfo)
if obj is not None:
filename = obj.group(1)
hashn = int(obj.group(2))
peerID = int(obj.group(3))
endCircle = int(obj.group(4))
if peer < hashn and endCircle:
print 'File ' +filename +' is not stored here. '
important = threeinfo
if peer > successor[1]:
important = re.sub('1$','0',threeinfo)
else:
print 'File '+ filename+' is here.'
important = 'FIND'+str(peer)+','+ filename +','+ str(peerID)
elif re.match('^FIND',threeinfo):
dest = re.match('^FIND([0-9]{1,3}),([0-9]{4})','',threeinfo)
fromP = dest.group(1)
fileP = dest.group(2)
print 'Received a response message from peer '+fromP+', which has the file '+fileP
connectionSocket.send('i receive from you------------------------')
print sen
connectionSocket.send('can you hear me?')
connectionSocket.close()
#--------------------TCP client----------------------------------------
def clientTCP(n):
global flag
global serverSetUp
global important
clientConn = False
# while serverSetUp == 1:
# pass
clientSocketTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverPortTCP = 50000 + n
while not clientConn:
try:
clientSocketTCP.connect((serverName,serverPortTCP))
clientConn = True
print "Now client connection works!!!!!"
except:
pass
try:
rt = threading.Thread(target=getRequestInput,args=(clientSocketTCP,))
sr = threading.Thread(target=sendRequestToS,args=(clientSocketTCP,))
ff = threading.Thread(target=findF,args=())
rt.start()
sr.start()
ff.start()
except:
print 'thread failed'
sen = raw_input()
clientSocketTCP.send(sen)
m = clientSocketTCP.recv(1024)
print m
clientSocketTCP.close()
#----------------start thread---------------------------------
#------adapt from https://www.tutorialspoint.com/python/python_multithreading.html --------
flag = 0
serverSetUp = 1
important = ''
findFile = False
try:
serTCP = threading.Thread(target=serverTCP,args=())
cliTCP = threading.Thread(target=clientTCP,args=(successor[1],))
serTCP.start()
cliTCP.start()
except:
print "thread can not be set up"
while flag == 0:
try:
pass
except KeyboardInterrupt:
flag = 1
I'm currently working on this Python port scanner, I'm trying to implement a feature that will allow this port scanner to scan a local subnet.
Currently when the target IP ends in .0, it scans every IP in that subnet range, (.1 - .255) except when I run the program, returns 'cannot resolve , unknown host' for every single IP within the subnet range. The code I currently have is below:
# import modules used in port scanner
import optparse
from socket import *
from threading import *
import ipaddress
# connect-scan function, deals with connecting to the host / determining if ports are open / closed, takes arguments tgtHost, tgtPort
def connScan(tgtHost, tgtPort):
try:
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
connSkt.send('\r\n')
result = connSkt.recv(100)
# prints result if port is open
print '[+] ' + str(tgtPort) + '/tcp open'
except:
# prints result if port is closed
print '[-] ' + str(tgtPort) + '/tcp closed'
finally:
connSkt.close()
# port-scan function, takes arguments tgtHost, tgtPorts
def portScan(tgtHost, tgtPorts):
try:
# tries to get target IP address
tgtIP = gethostbyname(tgtHost)
except:
# if unsuccesful, prints out following result
print '[-] cannot resolve ' + unicode(tgtHost) + ': unknown host'
return
try:
# tries to get target address
tgtName = gethostbyaddr(tgtIP)
print '\n[+] scan results for: ' + tgtName[0]
except:
print '\n[+] scan results for: ' + tgtIP
# sets default time out to 1
setdefaulttimeout(1)
# for every port in tgtPorts
for tgtPort in tgtPorts:
# creates thread, target is connScan function, arguments are tgtHost, int(tgtPort)
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
# starts the thread
t.start()
def main():
parser = optparse.OptionParser('usage %prog -t <target-host> -p <target-port(s)>')
parser.add_option('-t', dest='tgtHost', type='string', help='specify target host, for local subnet, use 192.168.1.0 (scans range 192.168.1.1 - 192.168.1.255')
parser.add_option('-p', dest='tgtPort', type='string', help='specify target port(s), seperated by a comma, seperate ranges with a -')
(options, args) = parser.parse_args()
if (options.tgtHost == None) | (options.tgtPort == None):
print parser.usage
exit(0)
else:
tgtHost = options.tgtHost
if tgtHost.endswith('.0'):
hosts = ipaddress.ip_network(unicode(tgtHost+'/24'))
else:
hosts = [tgtHost]
# allows ranges of ports to be used, when seperated by a -
if '-' in str(options.tgtPort):
tgtPorts = options.tgtPort.split('-')
tgtPorts = range(int(tgtPorts[0]),int(tgtPorts[1]))
else:
tgtPorts = str(options.tgtPort).split(',')
for tgtHost in hosts:
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()
I've been trying to find the solution for this, however have come up empty. Does anyone know whats wrong with the code?
I've been editing this port scanner for an information security project.
The code works but throws errors (Pycharm Edu) on lines 63 and 34 in that order.
The error message for line 63 is: 'line 63, in
checkhost(target). I've looked at this and can't see why this would throw an error specifically as it is defined on line 34.
The error message for line 34 is: 'NameError: global name 'conf' is not defined'. It's not clear why this is a problem either.
Any help is much appreciated.
The Python code environment is Python 2.7.10
#! /usr/bin/python
from logging import getLogger, ERROR # Import Logging Things
getLogger("scapy.runtime").setLevel(ERROR) # Get Rid if IPv6 Warning
import scapy
import sys
from datetime import datetime # Other stuff
from time import strftime
try:
target = raw_input("[*] Enter Target IP Address: ")
min_port = raw_input("[*] Enter Minumum Port Number: ")
max_port = raw_input("[*] Enter Maximum Port Number: ")
try:
if int(min_port) >= 0 and int(max_port) >= 0 and
int(max_port) >= int(min_port): # Test for valid range of ports
pass
else: # If range didn't raise error, but didn't meet criteria
print "\n[!] Invalid Range of Ports"
print "[!] Exiting..."
sys.exit(1)
except Exception: # If input range raises an error
print "\n[!] Invalid Range of Ports"
print "[!] Exiting..."
sys.exit(1)
except KeyboardInterrupt: # In case the user wants to quit
print "\n[*] User Requested Shutdown..."
print "[*] Exiting..."
sys.exit(1)
ports = range(int(min_port), int(max_port)+1)
start_clock = datetime.now() # Start clock for scan time
SYNACK = 0x12 # Set flag values for later reference
RSTACK = 0x14
def checkhost(target): # Function to check if target is up
conf.verb = 0 # Hide output
try:
ping = sr1(IP(dst = ip)/ICMP()) # Ping the target
print "\n[*] Target is Up, Beginning Scan..."
except Exception: # If ping fails
print "\n[!] Couldn't Resolve Target"
print "[!] Exiting..."
sys.exit(1)
def scanport(port): # Function to scan a given port
try:
srcport = RandShort() # Generate Port Number
conf.verb = 0 # Hide output
SYNACKpkt = sr1(IP(dst = target)/TCP(sport = srcport,
dport = port,flags = "S"))
pktflags = SYNACKpkt.getlayer(TCP).flags
if pktflags == SYNACK: # Cross reference Flags
return True # If open, return true
else:
return False
RSTpkt = IP(dst = target)/TCP(sport = srcport, dport = port,
flags = "R") # Construct RST packet send(RSTpkt)
except KeyboardInterrupt: # In case the user needs to quit
RSTpkt = IP(dst = target)/TCP(sport = srcport, dport = port,
flags = "R") send(RSTpkt)
print "\n[*] User Requested Shutdown..."
print "[*] Exiting..."
sys.exit(1)
checkhost(ip) # Run checkhost() function from earlier
print "[*] Scanning Started at " + strftime("%H:%M:%S") + "!\n"
for port in ports: # Iterate through range of ports
status = scanport(port) # Feed each port into scanning function
if status == True: # Test result
print "Port " + str(port) + ": Open" # Print status
stop_clock = datetime.now() # Stop clock for scan time
total_time = stop_clock - start_clock # Calculate scan time
print "\n[*] Scanning Finished!" # Confirm scan stop
print "[*] Total Scan Duration: " + str(total_time) # Print scan time
The problem is with your import statement, it should
be:
>>> import scapy
>>> from scapy.all import conf
>>> conf.verb = 0
or even better to get rid of possible similar errors in the future
just import scapy as:
>>> from scapy.all import *
>>> conf.verb = 0
Now it should work fine.
I have a nice little script, which should give me the open serial port in def serial_port(): Which is '/dev/ttyACM0' as usual. However my next function def connect_phone(): doesn't accept this as an input (giving me an serial.serialutil.SerialException:, but only when its typed manually. Does anyone get whats the issue here?
the complete script is this:
import sys
import glob
import serial
import time
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
def connect_phone():
ser = serial.Serial("'"+serial_ports()[0]+"'", #'/dev/ttyACM0', (this is the problem here)
460800,
timeout=5,
xonxoff = False,
rtscts = False,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE)
ser.write(bytes('AT+CGMI' + '\r\n'))
ser.timeout = 1
ser.write('AT+CGMM' + '\r\n')
ser.timeout = 1
time.sleep(2)
ser.write('AT+CNMI=?\r') #checks whether mobile phone can receive delivery reports
response = ser.read(999)
return response
print("'"+serial_ports()[0]+"'")
time.sleep(1)
print(connect_phone())