0

I am new to python, and programming in general, so this question may be due to my simple lack of knowledge

I am running a container on an Ec2 Instance (through ECS). I would like to write a python script which will 'exec' into the containers and then run 'jps' and 'jstat' on the chosen processes.

I have been using paramiko to ssh into the instances with no problem, but I have been unable to use paramiko in order to run the exec command to enter the containers. I don't receive an error message; but the exec command doesn't seem to execute and as such the 'echo hello' (which i've placed here instead of 'jps' and 'jstat' for ease of reading) doesn't output.

Here is the code that i've written:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
private_key = paramiko.RSAKey.from_private_key_file(<keyfilepath>)
for i in range(len(ec2_Ip)):
    ssh.connect(
        f'{ec2_Ip[i]}',
        username='ec2-user',
        pkey=private_key,
        look_for_keys=False,
        allow_agent=False,
        port=22
        )
# for command in command1:
stdin, stdout, stderr = ssh.exec_command("docker ps --format '{{ .ID }}' | sed -n '1p'")
time.sleep(.5)
containerIds.append((stdout.read().decode()))
containerIds = [i.strip('\n') for i in containerIds]
stdin.close()

stdin, stdout, stderr = ssh.exec_command("'docker exec -it <containerIds> /bin/bash' && pwd") #  && echo hello', get_pty=True)
time.sleep(.5)
print(stdout.read().decode())

any help would be greatly appreciated. If you know of a better way to accomplish this goal that would also be really helpful, thanks!

yaniv
  • 1
  • 1
  • 1
    I think you are looking for a docker python API? https://docker-py.readthedocs.io/en/stable/ – dosas Jun 28 '22 at 09:54
  • I've looked through the docker python API, perhaps its my lack of experience, but I'm not sure how to create a client reference when docker is being hosted on an ec2. I couldn't find a solution in the API pages. do you have any suggestions? thanks – yaniv Jun 28 '22 at 11:22
  • In the end I found a far better way to solve this problem, and that is using AWS's new exec command. I highly recommend to anyone looking to do this. – yaniv Jul 03 '22 at 13:32

0 Answers0