繁体   English   中英

如何运行位于 AWS EC2 服务器上的 python 脚本?

[英]How do I run a python script that is located on the AWS EC2 server?

我想在我的计算机上使用 python 代码来运行位于服务器上的 python 脚本(EC2 ubuntu 18)。 我知道您可以为此使用 boto,但我没有找到一个完整的示例,它可以在这里编写为服务器,我们像这样连接到它,我们像这样执行脚本。

您可以使用 AWS SSM 或 lambda function 来执行此操作。

请参阅 @mokugo-devops对 AWS SSM 的回答

或参考此 lambda function 方法

#requires paramiko package
#paramiko package is available at:
# https://github.com/pranavmalaviya2/COVID-19-Live-Data-board/tree/master/lambda%20functions/SSH_lambda-Deployment-package

import json
import boto3
import paramiko
import time

def lambda_handler(event, context):
    # boto3 client
    client = boto3.client('ec2')
    s3_client = boto3.client('s3')
    
    # getting instance information
    describeInstance = client.describe_instances()
    
    # downloading pem file from S3 
    s3_client.download_file('bucket-name','key-name.pem', '/destination/folder/new-key-name.pem')

    # reading pem file and creating key object
    key = paramiko.RSAKey.from_private_key_file("/destination/folder/new-key-name.pem")
    # an instance of the Paramiko.SSHClient
    ssh_client = paramiko.SSHClient()
    # setting policy to connect to unknown host
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # connect using ec2 instance ID if requires
    ssh_client.connect(hostname="12.12.12.12", username="ubuntu", pkey=key)

    # command list
    commands = [
        "python script.py",
        "python script2.py",
        "aws s3 cp --recursive source/ s3://destination-bucket/",
    ]

    # executing list of commands within server
    print("Starting execution")
    for command in commands:
        print("Executing command: " + command)
        stdin , stdout, stderr = ssh_client.exec_command(command)
        print(stdout.read())
        print(stderr.read())
    
    print("finished execution")
    
    return {
        'statusCode': 200,
        'body': json.dumps('Execution Completed')
    }

看看 AWS SSM - 运行命令

从本地 Python 脚本中,您可以运行send-command

您可以:

要执行此操作,您需要确保目标实例已安装SSM 代理,并且该实例具有具有正确权限的角色。 示例命令

import boto3
client = boto3.client('ssm')

client.send_command(
    InstanceIds=[
        'i-01234567',
    ],
    DocumentName='AWS-RunShellScript',
    Parameters={
        'commands': [
            'python3 /home/ec2-user/main.py',
        ]
    }
)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM