简体   繁体   English

使用 Python 套接字连接 AWS EC2 实例

[英]Connecting AWS EC2 instance using Python Socket

Server.py (Running on my aws ec2 instance) Server.py(在我的 aws ec2 实例上运行)

import socket

s = socket.socket()
host = socket.gethostbyaddr('aws.ec2.public.ip')[0]
port = 12345
s.bind((host, port))

s.listen(5)
while True:
   c, addr = s.accept()
   print('Got connection from', addr)
   c.send('Thank you for connecting'.encode())
   c.close()

Client.py (Running on my local pc) Client.py(在我的本地电脑上运行)

import socket

s = socket.socket()
host = socket.gethostbyaddr('aws.ec2.public.ip')[0]
port = 12345

s.connect((host, port))
print(s.recv(1024).decode())
s.close()

All inbound & outbound TCP traffic granted授予所有入站和出站 TCP 流量

The Server code shows no error.服务器代码显示没有错误。 But the Client code says但是客户代码说

Traceback (most recent call last):
  File "/Users/sohamjain/Desktop/client.py", line 7, in <module>
    s.connect((host, port))
TimeoutError: [Errno 60] Operation timed out
>>> 

Connecting to the EC2 instance via rdp client works perfectly通过 rdp 客户端连接到 EC2 实例完美运行

When I run both these scripts on local host they seem to work fine.当我在本地主机上运行这两个脚本时,它们似乎工作正常。 But in case of AWS EC2 Instance, it does not.但在 AWS EC2 实例的情况下,它不会。 Where did I go wrong?我在哪里 go 错了?

I have just encountered your situation:我刚遇到你的情况:

As Chris Williams mentioned in a reply to your question, you cannot use the public IP address when binding the listening socket on the EC2 instance.正如 Chris Williams 在回答您的问题时提到的那样,在 EC2 实例上绑定侦听套接字时,您不能使用公共 IP 地址。 Change that to use the private IP and it should work.将其更改为使用私有 IP 并且它应该可以工作。

Also make sure you enable traffic for the port you are binding from AWS security groups.还要确保从 AWS 安全组为您绑定的端口启用流量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python使用Fabric连接到EC2实例 - Python using Fabric to connect to an EC2 instance 使用Python在AWS EC2上发送电子邮件 - Sending email on AWS EC2 using Python 如何使用BOTO3 Python检索与AWS EC2实例相关的所有快照? - How to retrieve all snapshots related to a AWS EC2 instance using BOTO3 Python? AWS Lambda 使用 python boto3 列出 EC2 实例 ID - AWS Lambda to list EC2 instance id using python boto3 如何使用 Python 在 AWS EC2 实例上将文件/目录从 linux 远程复制到 windows? - How to copy files/directories remotely from linux to windows on AWS EC2 instance using Python? 如何/我可以使用 python 3 设置一个实例以使用已经为 AWS ec2 制作的实例 - How/Can I set up an instance to use an already made for AWS ec2 using python 3 如何使用 python selenium 从 aws 网站提取 ec2 实例详细信息,例如名称、memory - How to extract ec2 instance details like name, memory from aws website using python selenium 使用 aws cli 或 python 从 ec2 实例中删除安全组 - Removing security group from ec2 instance using aws cli or python 如何在 aws ec2 实例上安装 python3.6 - How to install python3.6 on aws ec2 instance 通过 AWS lambda 在 EC2 实例上执行 python 脚本 - Execute python script on EC2 instance via AWS lambda
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM