Connect to a host that doesn't answer to ping - python

I am trying to connect to a smtp port to automatically send emails through it. The problem is that when trying to connect to it with python smtplib it gives an error that it can't connect to the host. When trying to run nmap with the command
nmap -T4 -p 25,587,465
I get the following output:
Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
Nmap done: 1 IP address (0 hosts up) scanned in 2.12 seconds
When I add the -Pn option I get the following output:
Host is up.
PORT STATE SERVICE
25/tcp filtered smtp
465/tcp filtered smtps
587/tcp filtered submission
The python script that I have used is:
import smtplib, ssl
port = 465
password = "password"
email = "my#mail"
hostname = "hostname"
context = ssl.create_default_context()
with smtplib.SMTP_SSL(hostname, port, context=context) as server:
server.login(email, password)
And this is the error I get:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I am running the code on a Windows 10 machine and using Python 3.7.5.
Is there any way for me to connect to one of the email ports and send emails through it through python or c/c++?

Related

Sending email(outlook as server) in azure databricks notebook in python?

I tried to configure using localhost. I ran this in my cmd line.
(python -m smtpd -c DebuggingServer -n localhost:1025)
import smtplib, ssl
smtp_server = "localhost"
port = 1025 # For starttls
sender_email = "my outlook email"
password = input("Type your password and press enter: ")
# Create a secure SSL context
context = ssl.create_default_context()
# Try to log in to server and send email
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
print("server connected")
# TODO: Send email here
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
But it is giving "connection refused" error.
To resolve connection refused error, you can try following ways:
Firewall might be blocking access to port 1025
Alternatively, you can try using port 25
As per documentation:
For Enterprise Dev/Test subscriptions, port 25 is blocked by default. It is possible to have this block removed. To request to have the block removed, go to the Cannot send email (SMTP-Port 25) section of the Diagnose and Solve blade in the Azure Virtual Network resource in the Azure portal and run the diagnostic. This will exempt the qualified enterprise dev/test subscriptions automatically.
You can refer to Send emails from Azure Databricks

Create TCP Server accessible on remote networks

A project I am working on has an Android app as a front-end and a Python program that would be used as the back-end.
I want to send data from the Android app (primarily images) to the Python program, do some processing and send the result back to the Android app.
I have found numerous tutorials that suggest using the socket module in python to create the server side, but all tutorials show the server on local network only (For testing purposes I created the client side also in Python, but it would be converted to Java later on)
The server code:
from requests import get
import socket
public_ip = get('https://api.ipify.org').text
print('My public IP address is: {}'.format(public_ip))
# getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
# getting the IP address using socket.gethostbyname() method
local_ip = socket.gethostbyname(hostname)
# printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {local_ip}")
#
HOST = local_ip
PORT = 80 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if not data:
break
conn.sendall(data.encode('utf-8'))
The client code:
import socket
HOST = '…' # I modify it to the server's public IP address, as printed from the server code
PORT = 80 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
with socket.create_connection((HOST, PORT)) as s:
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
Using the code above, if I try using any port other than 80 I get ConnectionRefusedError: [Errno 111] Connection refused. And for port 80, I get TimeoutError: [Errno 110] Connection timed out.
In both cases, I try to connect from a device on another network.
I tried to use the ping command in Windows CMD to check the connection to the server, and I get 'connection refused message'.
I understand that the Firewall is what probably blocks the connection, but I don't know how to bypass it. I added a new rule in the Inbound Rules section (as suggested on other websites) but for no avail… The results were the same.
How can I make the connection between remote devices on different networks?
Thanks in advance ☺
In order to connect to your server using a TCP socket connection, you need to make sure your server can listen on a port on a publically available IP address.
If the External IP address is assigned to your computer directly,
and if you run the server code on that computer, then the TCP port opened by the server code should be available on the internet.
However, IP addresses are often assigned to a modem/router in home networks,
instead of assigning them to any connected device directly.
To find out if your External IP address is assigned to the computer directly you can use tools that your OS support (eg. ipconfig on windows). If you can see the IP address returned by api.ipify.org, then it means your computer is connected directly. You can change your code to connect using publically exposed IP:
HOST = public_ip
If this is successful means your computer is assigned an external address directly. Which is highly unlikely.
There are several workarounds for this problem though:
1) Configure your router to forward port
Configure your router to forward all connections to it's external TCP port, to an internal host in your network which is assigned to your computer. Please find instructions how it is done for your router.
2) Setup a remote proxy
If you don't have permission to change your router settings you can set up a remote proxy listening on the TCP port. While there is a number of ways of doing this, very popular is to set up a remote SSH tunnel, for that you need to have a server with SSH access and an external IP. Run this command:
ssh -R 80:localhost:8080 root#your-ssh-server-host
You can also use a third-party service that exposes your private host on the internet like:
Ngrok (Commercial, with free plans)
Localtunnel (Open Source, can be self-hosted)

TCP Socket not connecting [WinError 10060] - Python

I'm making a chat app using sockets in python, but when I try to connect from a different computer then it says:
C:\Users\James\OneDrive\Documents\Python\Projects\Gui Chat\client.pyw
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
This is the server code for the socket:
host = socket.gethostbyname(hostname)
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
print(f"IP: {server.getsockname()[0]}\nPORT: {server.getsockname()[1]}")
server.listen()
I also have a while True loop accepting all requests:
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
On the client end this is the socket code:
IP = simpledialog.askstring("IP", "Enter IP address", parent=root) # "192.168.1.252" # input("Enter IP: ")
nickname = simpledialog.askstring("Nickname", "Choose a nickname", parent=root)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((IP, 55555))
except Exception as e:
print(e)
The programme asks for the IP address each time, and when I put in the correct IP for the server computer, it comes up with the error above. It works if I try to connect from the same computer, and they are both on the same network. It was working recently, and now it has just stopped working.
UPDATE:
I have set the server ip to 0.0.0.0, I have set up a port forwarding rule, I have checked the firewall and allowed incoming and outgoing connections, and I have run nmap with these results:
Code issues
First try binding server on localhost or 127.0.0.1.
FireWall/Ports issues
Check if your computer's default computer/antivurus
firewall (where server is hosted) allow connections
on your port 55555.
And if computer with client is outside your home network
point to router public IP address and make sure you have
port forwarding setup on router.
Address issues
Are you sure that IP you are writing in client is correct.
Go to your computer with server and check that IP.
Windows:
Go to cmd or Power Shell and type ipconfig, then find
section IPv4 Address and look that address you habe there.
Linux / MacOS
Go to your terminal and type ifconfig -a, and
it should be somewhere there, but I don't have those systems,
so I can't test it for you. If it does't work try to search how to
find that out.

Python on GCE: connection failed because connected host has failed to respond

I've been working on a project that requires a bit of networking between a server (hosted on GCE) and multiple clients. I created a Compute Engine Instance to run a Python script as shown in this video: https://www.youtube.com/watch?v=5OL7fu2R4M8.
Here is my server-side script:
server = socket.gethostbyname(socket.gethostname()) # 10.128.X.XXX which is the Internal IP
print(server)
port = 5555
clients = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((server, port))
s.listen(2)
print("Waiting for connection...")
while True:
conn, addr = s.accept()
print("Connected to: ", addr)
conn.send(str.encode(f"{clients}"))
clients += 1
and here is my client side-script:
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "10.128.0.2"
self.port = 5555
self.addr = (self.server, self.port)
self.id = int(self.connect())
def connect(self):
self.client.connect(self.addr)
return self.client.recv(2048).decode()
network = Network()
print(f"Connected as client {network.id}")
I know this script works because I have tested it with my computer being the server and 1 client, and another computer being the 2nd client. But when I use the GCE as the server, I get this error in the client script:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Could this be because I am using the internal IP address and not the external?
After this, I tried changing the firewall settings (added 'python-socket') of the GCE and this is what they look like:
But the error still persists...
As answered by W_B, I tried to run these commands on my VM and got the following outputs:
From your description it's evident it's the connection problem.
First of all you have to check if the firewall rule you created is still there. If it's "too broad" and allows for very wide access then it might be removed automatically even without you knowing it. It's on you'r screenshot but check it again just to be sure.
If it's there select the protocol you're goint to be using (I assume it's TCP) - some protocols are always blocked by default by GCP (you can't change this) so creating a rule with "any protocol" allowed is risky. Also - put one or two target IP's (not all inside this VPC) - this is not a must but improves security of your network.
Second - make sure port 5555 you're trying to connect to is accessible from other computers. You can scan the target host with nmap -p 5554 put.server.ip.here
You can scan it from the Internet or other VM's in the same VPC network.
You should get something like this:
root#localhost:~$ nmap -p 443 192.168.1.6
Starting Nmap 7.70 ( https://nmap.org ) at 2020-06-25 17:12 UTC
Nmap scan report for 192.168.1.6
Host is up (0.00091s latency).
PORT STATE SERVICE
443/tcp open https
Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds
If you see 5555/tcp filtered freeciv this means that something blocks the port.
Run nmap on the server (I assume you run some version of Linux) and if you don't want to install any non-essencial software you can use sudo netstat -tulpn | grep LISTEN to get a list of open ports (5555 should be on the list).
Also make sure firewall on your server doesn't block this port. You can use iptables for that.

socket.error: [Errno 10060] while sending an email with Python

I am learning Python and wanted to try a small python script where I can send email with that script.
My Code:
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login("youremailusername", "password")
msg = "Hello! Test Script For Sending an email"
server.sendmail("you#gmail.com", "target#example.com", msg)
Error Message:
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Can some one please help me what with problem?
the network you're on might be blocking that port (587) for outgoing connections, or Google might be blocking your IP address. If you're on a VPS, you can check the firewall settings for your system and see if you can open it.

Categories