且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Amazone 的 EC2 实例中运行代码?

更新时间:2023-11-22 20:08:16

这是将 Python 脚本从本地移动到 EC2 实例并运行它的一个非常简单的过程.

Here's a very simple procedure to move your Python script from local to EC2 Instance and run it.

> 1. scp -i <filepath to Pem> <filepath to Py File> ec2-user@<Public DNS>.compute-1.amazonaws.com:<filepath in EC2 instance where you want
> your file to be>
> 2. Cd to to the directory in EC2 containing the file. Type Python <Filename.py> There it executed.

这里有一个具体的例子,适合喜欢循序渐进的事物的人:

Here's a concrete examples for those who likes things shown step-by-step:

  1. 在您的本地目录中,使用以下代码创建一个 python 脚本:print("Hello AWS")
  2. 假设您已经设置了 AWS 并且您想在 EC2 中运行此脚本,您需要将您的文件 SCP(安全复制协议)到 EC2 中的目录.举个例子:

    - 我的 pem 文件路径是 ~/Desktop/random.pem.
    - 我的 py 文件路径是 ~/Desktop/hello_aws.py
    - 我的公共 DNS 是 ec22-34-12-888
    - 我希望我的脚本所在的 ec2 目录在/home/ec2-user
    - 所以我在本地终端中运行的完整命令是:

      - My filepath to pem is ~/Desktop/random.pem.
      - My filepath to py file is ~/Desktop/hello_aws.py
      - My public DNS is ec22-34-12-888
      - The ec2 directory where I want my script to be is in /home/ec2-user
      - So the full command I run in my local terminal is:

      scp -i ~/Desktop/random.pem ~/Desktop/hello_aws.py ec2-user@ec2-34-201-49-170.compute-1.amazonaws.com:/home/ec2-user>

      scp -i ~/Desktop/random.pem ~/Desktop/hello_aws.py ec2-user@ec2-34-201-49-170.compute-1.amazonaws.com:/home/ec2-user

  1. 现在 ssh 到您的 ec2 实例,cd 到/home/ec2-user(或您放置文件的任何位置)和 Python hello_aws.py