-
As of now, what I understood when using ssh is the following my_server = sh.ssh.bake("-i", "priv_key", "[email protected]")
print(my_server("ifconfig"))
print(my_server("whoami")) This though will open two separate sessions for execution of each command, which makes it difficult to run a chain of commands within the same session. What would be the correct way to run multiple commands in the same session? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Long running ssh sessions is not really what sh is designed for, though it can be done, with significant effort. You're better off using something like https://github.com/fabric/fabric |
Beta Was this translation helpful? Give feedback.
-
Thank you for the suggestion, the amount of open issues in this repo scares me, what about using a context manager as suggested here: #592? |
Beta Was this translation helpful? Give feedback.
-
This is what I ultimately came up with: from dataclasses import dataclass, field
from time import sleep
from typing import Any
import sh
@dataclass(slots=True)
class MasterSlaveSsh:
master: Any = field(
init=False,
default_factory=lambda: sh.ssh.bake(
"-o", "ControlMaster=yes", "-o", "ControlPath=~/.ssh/control-10.0.0.1_root", "-i", "priv_key", "[email protected]"
),
)
slave: Any = field(
init=False,
default_factory=lambda: sh.ssh.bake("-o", "ControlPath=~/.ssh/control-10.0.0.1_root", "-i", "priv_key", "[email protected]"),
)
def __enter__(self) -> slave:
is_connected: bool = False
def assert_connected(line):
nonlocal is_connected
if line.strip() == "sleeping...":
is_connected = True
self.master = self.master(
'touch /root/heartbeat; while [ -f "/root/heartbeat" ]; do echo "sleeping..."; sleep 3; done;', _bg=True, _out=assert_connected
)
while not is_connected:
sleep(1)
print("Connected")
return self.slave
def __exit__(self, exc_type, exc_val, exc_tb):
print(self.slave.rm("-v", "/root/heartbeat"))
self.master.wait()
with MasterSlaveSsh() as ssh:
print(ssh("echo 1 Doing work; sleep 3;"))
print(ssh("echo 2 Doing work; sleep 3;"))
print(ssh("echo 3 Doing work; sleep 3;")) If you have any better ideas, do let me know, this way at least it uses the same connection - the shell/environment is still not the same per session though, maybe using screen would be most elegant for fixing that. |
Beta Was this translation helpful? Give feedback.
This is what I ultimately came up with: