Python: Retrieve list of sockets on current machine? - python

I'm brand new to Python (as of last week) and I'm still getting to grips with the basics so please excuse any ignorance I display.
As part of my homework I have been asked to make a basic port scanner and one of the functions I have to include is the retrieval of a list of sockets on the current machine. I have been looking around and managed to piece together a piece of code that allows me to enter the IP of the machine I wish to scan but I want to try and make it so it automatically scans whichever machine it is running on.
elif (userChoice == "4"):
print("You selected " + userChoice)
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # s will be equal to the command looking for the IPV4 addresses
except socket.error:
sys.exit("Failed to create socket.") # error handling message to be printed to the console should a socket failed to be created
print("Socket created")
hostAddress = input("Please enter host address to scan - example 'www.server.com': ")
print ("You entered " + hostAddress )
try:
remoteIP = socket.gethostbyname(hostAddress)
except socket.gaierror:
sys.exit("Hostname could not be resolved exiting")
ret = input("Hit return to go back to the menu")
continue
print("IP address of " + hostAddress + ' is ' + remoteIP)
This is my code so far. If anyone could help me out or tell me if I'm even going in the right direction with this I would be very grateful.
Also, with me being a noob, if anyone has any suggestions for good reading materials to help me get to get to grips with the basics I would very much appreciate it.
Thanks.

To check open ports on remote server-
# For input hostAddress
remoteIP = socket.gethostbyname(hostAddress)
for port in range(1,1025):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteIP, port))
if result == 0:
print("Port %s: Open"%port)
sock.close()
=> Port 80: Open

Related

Taking multiple inputs from user in command prompt with python

I am trying to build a very simplistic port scanner in order to practice with the concept of sockets. The design I have is as following:
from socket import *
ip = input("Submit IP to scan:")
start = input("Submit starting port:")
end = input("Submit ending port:")
print("Scanning IP:", ip)
for port in range(int(start),int(end)):
print("Scanning port:" + str(port) + "..")
var_socket = socket(AF_INET,SOCK_STREAM)
var_socket.settimeout(3)
if var_socket.connect_ex((ip,port)) == 0:
print("port", port, "is open")
else:
print("err code:", var_socket.connect_ex((ip,port)))
var_socket.close()
print("Scanning completed!")
This all works pretty well when I run it from a file. Unfortunately I may not always have the luxury to run my scripts from a file, so I'll need to be able to create this script in a command shell. I've made some attempts myself with tips and tricks from the internet, but they all failed in some way.
from socket import * #Press enter. Note that I am in a windows terminal.
ip = input("enter ip to scan:")\ #Press enter
start = input("enter starting port:")\ #Press enter
output:
Syntax error: Invalid syntax
The other solution I found actually worked, but brings some unwanted complexity along the way:
from socket import *
ip,start,end = map(int,input().split()) #Press enter
This solution allows me to enter 3 values seperated by a space, mapping them to ip, start and end respectively. Of course this will not work unless I design a function that manually transforms the entered ip value into a valid dotted decimal IP address. Does anyone know a better approach to ask for multiple inputs in a shell environment?
Thanks a lot in advance.
When copying your script, the python interpreter reads your code line by line, which makes it fill your input with the script you are typing.
One solution to avoid that is to read files from a different place (arguments, files, …). Or, you can also load your script in memory, then execute before asking for the inputs:
script = '''
from socket import *
ip = input("Submit IP to scan:")
start = input("Submit starting port:")
end = input("Submit ending port:")
print("Scanning IP:", ip)
for port in range(int(start),int(end)):
print("Scanning port:" + str(port) + "..")
var_socket = socket(AF_INET,SOCK_STREAM)
var_socket.settimeout(3)
if var_socket.connect_ex((ip,port)) == 0:
print("port", port, "is open")
else:
print("err code:", var_socket.connect_ex((ip,port)))
var_socket.close()
print("Scanning completed!")
'''
exec(script)

Threaded python SSH port scanner doesn't work

So I'm trying to make a program that scans the SSH port for IPs in a list. Because the process is painfully long I'm trying to use threading (I can use multiprocessing if it is more suitable for the program) to make everything faster but I'm running in a problem where the program says "Trying IP" (that's what it's meant to say every time it scans an IP) a lot of times without giving a result and then it gives the results (significantly fewer results than IP scans) and having other weird patterns. It should say Trying IP and then the result but it doesn't and even the result is always failing even if it does find IPs with the SSH port open. At some point I was curious if it misses IPs with SSH so I searched for an IP range that should have a lot of them and it only caught 2000 of them even if the guy who posted the class said he got 45000, yeah I know, maybe something happened and an insane amount of people closed SSH but no, I downloaded something called a "scanning archive" made by some Romanian hackers that had a SSH port scanner in it and when I scanned the same IP range I caught 6600.
So can someone help me figure out what is wrong with the code and tell me how to improve it?
import socket
import threading
from queue import Queue
from datetime import datetime
time_start = datetime.now()
SSH_ips = []
def scan(ip_number):
ip_try = ip_list[ip_number]
port = 22
try:
print("Trying IP")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip_try,port))
if result == 0:
SSH_ips.append(ip_try)
print("Found %d" % (ip_try))
else:
print("Didn't work")
except:
pass
def gulag():
while True:
worker = q.get()
scan(worker)
q.task_done()
q = Queue()
for x in range(15000):
t = threading.Thread(target=gulag)
t.daemon = True
t.start()
for worker in range(0, 65026):
q.put(worker)
q.join()
time_finish = datetime.now()
time_elapsed = time_finish - time_start
ip_list_lenght = len(SSH_ips)
SSH_ips.sort()
print("Found %s IPs in %s." % (ip_list_lenght, time_elapsed));
print(SSH_ips)
... what is wrong with the code and tell me how to improve it?
try:
print("Trying IP")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...
except:
pass
Please don't just pass on exception but actually check why it failed. It is likely that you run against the limit of open file descriptors and thus creation of a new socket failed. In this case of course no connection will be attempted to this IP address.
result = sock.connect_ex((ip_try,port))
if result == 0:
SSH_ips.append(ip_try)
print("Found %d" % (ip_try))
else:
print("Didn't work")
Similar here check why exactly connect_ex failed instead of just assuming that it failed because there is no open port on the other end.

Port Scanner 3.5 Python Print Issue After Going Through set range

import socket
import sys
from datetime import datetime
#Ask the user for input, the form of a remote host entire in the IP address of the target machine
remoteServer =input ("Enter a remote host to scan:")
remoteServerIP =socket.gethostbyname(remoteServer)
#Print a block of text with information on which host we are about to scan.
#While scanning display a message so the user knows the program is working and isn't frozen
print ("_"*60)
print ("Please wait, currently scanning remote host", remoteServerIP)
print ("_"*60)
#Show/check the time scan started
t1 = datetime.now()
#range function to specify ports, this case I have set the pogram to go through ports 1 to 150
# port in range works like so
try:
for port in range (1, 150):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print ("Port {}: Open".format(port))
sock.close()
# Press Ctrl C to leave the application
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)
My boss has told me to start learning about Metasploitable2 and Kali Linux as such I have attempted to create a port scanner it seems to work fine for most of the part however. after if has finished scanning the ports within it's set range it close completely rather then print ('Scanning Completed in: ', total) with listed findings. What have I done wrong here? And I 'm well aware this is script slow I'm going to attempt to make it multithreaded later on.

Connection refused with sockets in python

First off, thanks to all users because I learnt a lot reading questions and answers on this website.
I'm starting to learn Python and I'm trying to send information of a PC over internet through sockets to another PC. It all worked great when I connected two computers of my localhost. However, I'm trying to connect with a friend's computer and I can't do it. I know (thanks to previous topics on this page) that the server needs to forward a port to his own computer. My friend already did that and, me as a client and he as a server, we haven't been able to connect.
I'd like to show you my really simple code because I'm sure I mistaken something I can't figure out what.
This is the client script:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("Public IP of server",9990))
if True:
print "Conexion establecida"
while True:
mensaje = raw_input("Mensaje a enviar: ")
if mensaje == "close":
break
else:
s.send(mensaje)
print "Mensaje enviado."
s.close()
And this is the server script:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",9990))
s.listen(1)
sc, addr = s.accept()
print "Conexion establecida con ", str(addr[0])
while True:
recibido = sc.recv(1024)
if recibido == "close":
break
print str(addr[0]) + " dice: ", recibido
sc.close()
s.close()
The client script connect with the public ip the server and, if true, let the user send a message. The server scripts just receives the message and prints it. I hope it is enough to no not make you lose a lot of time. Lot of thanks for reading me!

How to add visuals to python chat program

I have written a basic python socket based chat program (My second one) and i would like to add some visuals to make it a little more user friendly.
Should I layer the visuals over the existing program or should i make a new program around the visuals
What python module should i use for the visuals (i know pygame is that suitable)
Can i have some form of general idea on how to write this (Code examples maybe?)
Here is my existing code:
Client:
import socket, threading
#Setup The Variables
WindowTitle = 'Chat 2.0 - Client'
s = socket.socket()
host = raw_input("Please Enter External IP adress Here: ")
print
host = socket.gethostname()
port = 8008
#Attempted To Connect
print "Conecting..."
print
while True:
try:
s.connect((host, port))
break
except:
pass
print "Connected To " + str(host) + " " + str(port)
print
#Check For Incomming Data
def check_for_data():
while True:
data = s.recv(1024)
if data:
print
print "Other: " + str(data)
print
print "You: "
else:
print "Client closed connection"
s.close()
break
#Send Data
def send_data():
while True:
user_input = raw_input("You: ")
print
s.sendall(user_input)
#Start Threads \ Main Loop
t = threading.Thread(target=send_data)
t.daemon = True
t.start() #1
check_for_data()
s.close
Server:
import socket, threading
#Setup The Variables
WindowTitle = 'Chat 2.0 - Client'
host = socket.gethostname()
port = 8008
s = socket.socket()
s.bind((host, port))
print "Awaiting Connection..."
print
s.listen(5)
c, addr = s.accept()
print "Connection From: " + str(addr)
print
def check_for_data(c):
while True:
data = c.recv(1024)
if data:
print
print "Other: " + str(data)
print
print "You: "
else:
print "Client closed connection"
c.close()
break
def send_data():
while True:
message = raw_input("You: ")
print
c.sendall(message)
#Start Threads \ Main Loop
t = threading.Thread(target=send_data)
t.daemon = True
t.start() #1
check_for_data(c)
c.close()
Have to agree that tkinter is probably the better way to go here. For a chat program, pygame's sprites/rects/surfaces all have little use. However, tkinter has buttons and labels and other similar things built in that would suit your needs a bit better. Btw, to make your life with socket easier, look into the makefile method. The makefile method allows for much easier use. I recommend looking at Socket.error [Error 10060] for a description of how to use it and its uses. It's not necessary, just makes life easier :)
Edit:
"Should I layer the visuals over the existing program or should i make a new program around the visuals"
Not quite sure what you mean here by "existing program." When it comes to what you should code, split up your logic and user interface stuff. So have a module that handles the sending and receiving of messages, and another that handles the display.
"What python module should i use for the visuals (i know pygame is that suitable)"
Probably tkinter. I only have experience in tkinter and pygame, but of the two, you probably want tkinter for this. I explained why in the first paragraph.
"Can i have some form of general idea on how to write this (Code examples maybe?)"
Assuming you use tkinter, look into stringvars, they may or may not be useful for you. As for the structure of your program, I'm not exactly sure what you want so I can't help you there. But do start simple. For example, get messages to send between programs, and print them out. Then have the messages show up on a window.. Make a way for the user to type in message via GUI (look into tkinter entry widget!). Best of luck you!
Edit 2: To answer your question about how to position button. Here is some code from my last project where I had to use a button to do something.
button_frame = tkinter.Frame(master = self.option_window)
button_frame.grid(row = 5, column = 1)
ok_button = tkinter.Button(master = button_frame, text = 'OK',
font = DEFAULT_FONT, command = self.on_ok_clicked)
The position of the button is based off of where I did the button_frame.grid(....). To organize your tkinter window, I recommend using grid and not pack.
Oh, and self.option_window was a tkinter.Tk() object in my case.

Categories