Automate `lxc-attach` through ssh with Python

2024/9/21 3:25:23

Question:

How do I automate this process, and include all of the password prompts?

Machine 1> ssh user2@machine2password:
Machine 2> lxc-attach -n 0x1000
Container> ssh user3@machine3password:
Machine 3> get_temperature.shtemperature is 65C

Background:

I am running some automated scripts on a computer (Machine 1) with several other test systems cascaded from this one. Only the first computer has internet access and stable state. Anything can be installed here and the automation is mostly python.

The other test systems are not connected to the internet, are shutdown unexpectedly, and have their memory wiped often. Because of this, any settings I change or ssh keys I load outside of this automated script are not retained. I am just testing the hardware; none of this will be in production anywhere, and I don't have any way to change the state it is reset to.

Diagram of Cascaded System

Attempt:

I have tried to solve this running paramiko on Machine 1. I can connect to Machine 2, but I have no way to answer the password prompt when connecting to Machine 3 from the Machine 2. This is what I have tried:

import paramikossh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect('192.168.2.2', port=22, username='user2', password='pass2')
print("connect to machine 2")channel = ssh.invoke_shell()
channel_data = ''
go = 1while True: if channel.recv_ready():channel_data = str(channel.recv(9999))print('Channel Data: ', channel_data)else:continueif channel_data.endswith("~ >'"):if go == 1:channel.send('lxc-attach -n 0x1000')channel.send('\n')go += 1else: channel.send('ssh [email protected]')print("sending ssh command")elif 'assword:' in channel_data:channel.send('pass3')channel.send('\n')print("put the pass")breakstdin, stdout, stderr = ssh.exec_command('pwd')
print(stdout)

Next I tried using fabric to jump from one host to another. If I try to open a connection to Machine 3 or 4 with gateway settings, this exits with the error: ChannelException(2, 'Connect failed'). If I try to run the lxc-attach command first, it just hangs forever.

import fabricmachine2 = fabric.Connection('192.168.2.2', user='user2', connect_kwargs={"password": "pass2"})
result = machine2.run('hostname')
print('machine2 hostname', result)
result = machine2.run('lxc-attach -n 0x1000')
print('machine2 lxc ', result)machine3 = fabric.Connection('192.168.3.2', user='user3', gateway=machine2, connect_kwargs={"password": "pass3"})
machine4 = fabric.Connection('192.168.4.2', user='user4', gateway=machine3, connect_kwargs={"password": "pass4"})result = machine3.run('hostname')
print('machine3 hostname', result)

Meta:

These similar questions about automating password entries:

  • Shell script to automate SSH login using password
  • Automate SSH login under windows

Are answered with "dont".

Martin pointed me toward jump hosting, but I haven't gotten it to work. For this topic, most questions seem to point back to this one:

  • Nested SSH using Python Paramiko

I believe that my problem is trying to jump host through the container. It seems the lxc-attach command opens a raw shell that doesn't get passed back.

Is there a way to spawn a shell that acts more like it's interactive counterparts? I tried pexpect, but Machine 1 is Windows, so it doesn't work. The commands on the Pexpect Windows Documentation exit with module 'pexpect' has no attribute 'popen_spawn'.

Answer

Pexpect doesn't work in Windows.

I created a new 'Machine 1' with Linux and the following code works:

child = pexpect.spawn(f'ssh {m2.user}@{m2.ip}')
child.expect('assword:')
child.sendline(m2.pswd)
child.sendline('\n')
print('Note: p2 sent')
child.expect(m2.prompt)
child.sendline('hostname')
print('Out: ', child.before)child.expect(m2.prompt)
child.sendline('lxc-attach -n 0x1000')
child.sendline('\n')
print('Note: attach sent')
child.expect(container.prompt)
child.sendline('hostname')
print('Out: ', child.before)child.expect(container.prompt)
child.sendline(f'ssh {m3.user}@{m3.ip}')
child.expect('assword:')
child.sendline(m3.pswd)
print('Note: p3 sent')
# child.expect(pexpect.EOF)
child.expect_exact(m3.prompt)
child.sendline('hostname')
child.expect_exact(m3.prompt)
print('Before: ', child.before)child.sendline(f'ssh {m4.ip}')
print('Note: M4 connected')
child.expect_exact(m4.prompt)
child.sendline('hostname')
child.expect_exact(m4.prompt)
print('Host: ', child.before)
https://en.xdnf.cn/q/119249.html

Related Q&A

Value of a key in a Python dictinary is not updating [duplicate]

This question already has answers here:Appending a dictionary to a list - I see a pointer like behavior(3 answers)Python The appended element in the list changes as its original variable changes(1 answ…

Python - __init__() missing 1 required positional argument:

Im kinda new to python and I cant get past this error: Traceback (most recent call last):File "***", line 63, in <module>bst = Node() TypeError: __init__() missing 1 required positional…

discord py - Custom command prefix doesnt work (no command run)

i have a problem that i cant solve. Im trying to add a prefix switcher for all guilds, that uses my bot. So Ive done that, but currently no command gets triggered and I cant find a solution since hours…

How to use sep parameter in .format?

I just started learning python and Im experimenting new things. isim = input("Name:") soyad = input("Surname:") yaş = input("Age:") edu = input("Education:") ge…

Python table classification

I have different type of data for example:4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1I need output:U1: [[4.5, 3.5], [4.5, 6], [5, 7], [7, 6.5]] U2: [[4.5, 10.5], [3.5, 10.5]…

python json.loads / json.load truncates nested json objects?

given the following code: import json foo = {"root":"cfb-score","children":{"gamecode":{"attribute":"global-id"},"gamestate":{&quo…

How to make an encrypted executable file

I have made a tool/program on Ubuntu written in Python. I want to give this to my friend to test on his PC, but I dont want to share the source code.This program has many folders and many .py files. Is…

Organizing pythonic dictionaries for a JSON schema validation

Scenario: I am trying to create a JSON schema validator in python. In this case, I am building a dictionary which contain the information that will be used for the validation.Code:import json import os…

Scraping a specific website with a search box and javascripts in Python

On the website https://sray.arabesque.com/dashboard there is a search box "input" in html. I want to enter a company name in the search box, choose the first suggestion for that name in the d…

Uppercasing letters after ., ! and ? signs in Python

I have been searching Stack Overflow but cannot find the proper code for correcting e.g."hello! are you tired? no, not at all!"Into:"Hello! Are you tired? No, not at all!"