1

我想在 python 代码中使用 session-manager-plugin。

代码编写如下

import boto3
from boto3.session import Session
import subprocess

AWS_REGION = "ap-northeast-1"
AWS_PROFILE = "default"
INSTANCE_ID = "i-XXXXX"

ssm = boto3.client('ssm')

response = ssm.start_session(
    Target=INSTANCE_ID,
    DocumentName='AWS-StartPortForwardingSession',
    Parameters={
        'portNumber': ['3389'],
        'localPortNumber': ['13389'],
    }
)

parameters = "{'DocumentName': 'AWS-StartPortForwardingSession', 'Target': "+INSTANCE_ID+", 'Parameters': {'portNumber': ['3389'], 'localPortNumber': ['13389']}}"

def start_aws_ssm_plugin(create_session_response, parameters, profile, region):
    arg0 = '"' + 'session-manager-plugin' + '"'
    arg1 = '"' + str(create_session_response).replace('\'', '\\"') + '"'
    arg2 = region
    arg3 = 'StartSession'
    arg4 = profile
    arg5 = '"' + str(parameters).replace('\'', '\\"') + '"'
    arg6 = 'https://ssm.{region}.amazonaws.com'.format(region=region)

    command = arg0 + ' ' + arg1 + ' ' + arg2 + ' ' + arg3 + ' ' + arg4 + ' ' + arg5 + ' ' + arg6

    pid = subprocess.Popen(command).pid
    return pid

start_aws_ssm_plugin(response, parameters, AWS_PROFILE, AWS_REGION)

但是,代码出现错误。

panic: interface conversion: interface {} is nil, not string

goroutine 1 [running]:
github.com/aws/SSMCLI/src/sessionmanagerplugin/session.ValidateInputAndStartSession(0xc00010c000, 0x7, 0x8, 0x14c2380, 0xc000006018)

我参考“https://stackoverflow.com/questions/65963897/how-do-i-use-the-results-of-an-ssm-port-forwarding-session-started-with-ruby/”编写了代码66043222#66043222"

如果您有任何信息,请告诉我。

谢谢

4

2 回答 2

0

据我所知,您需要调用 start-session 端点来获取 streamurl、sessionid 和令牌。然后调用 session-manager-plugin 转发 tty。

https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartSession.html

于 2021-06-03T03:54:44.597 回答
0

您似乎搞砸了引用两个 json arg 字符串。这适用于 Windows10:

import boto3
ssm = boto3.client('ssm')
instance_id = "i-XXXXX"
ssm_response = ssm.start_session(
    Target=instance_id,
    DocumentName='AWS-StartPortForwardingSession',
    Parameters={"portNumber": ["8080"], "localPortNumber": ["9999"]}
)
cmd = [
    'C:/Program Files/Amazon/SessionManagerPlugin/bin/session-manager-plugin.exe',
    json.dumps(ssm_response),
    'eu-central-1',  # client region
    'StartSession',
    'default',  # profile name from aws credentials/config files
    json.dumps(dict(Target=instance_id)),
    'https://ssm.eu-central-1.amazonaws.com'  # endpoint for ssm service

]
subprocess.run(cmd)

https://github.com/aws/session-manager-plugin/blob/mainline/src/sessionmanagerplugin/session/session.go很有帮助。

于 2021-12-11T00:10:38.517 回答