如何运行位于AWS EC2服务器上的python脚本? [英] How do I run a python script that is located on the AWS EC2 server?

查看:106
本文介绍了如何运行位于AWS EC2服务器上的python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在计算机上使用python代码运行服务器上的python脚本(EC2 ubuntu 18).我知道您可以使用boto来实现此功能,但是我找不到在其中编写服务器的完整示例,我们以这种方式连接至该服务器,并以这种方式执行脚本.

I want to use python code on my computer to run a python script that is located on the server (EC2 ubuntu 18). I understand that you can use boto for this, but I didn't find a full-fledged example where it would be written here is the server, we connect to it like this, we execute the script like this.

推荐答案

您可以通过使用AWS SSM或lambda函数来实现.

You can do so by using AWS SSM or lambda function.

请参阅@ mokugo-devops的 AWS SSM的答案

Refer to @mokugo-devops 's answer for AWS SSM

或参阅此以获取lambda函数方法

or Refer to this for lambda function approach

#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 EC2服务器上的python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆