Skip to content

ssh_exec

SSHSession

Persistent SSH connection for multi-command workflows.

Holds a single live asyncssh.SSHClientConnection that is opened via :meth:connect and closed via :meth:close. Commands, background jobs, and SFTP transfers all reuse the same TCP connection.

Source code in wintermute/ai/utils/ssh_exec.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
class SSHSession:
    """Persistent SSH connection for multi-command workflows.

    Holds a single live ``asyncssh.SSHClientConnection`` that is opened via
    :meth:`connect` and closed via :meth:`close`.  Commands, background jobs,
    and SFTP transfers all reuse the same TCP connection.
    """

    def __init__(
        self,
        target_alias: str,
        username: str | None = None,
        password: str | None = None,
        port: int | None = None,
    ) -> None:
        self._connect_kwargs = _build_connect_kwargs(
            target_alias, username, password, port
        )
        self._conn: asyncssh.SSHClientConnection | None = None

    async def connect(self) -> None:
        """Open the persistent SSH connection."""
        self._conn = await asyncssh.connect(**self._connect_kwargs)

    async def close(self) -> None:
        """Close the persistent SSH connection."""
        if self._conn is not None:
            self._conn.close()
            await self._conn.wait_closed()
            self._conn = None

    def _require_conn(self) -> asyncssh.SSHClientConnection:
        """Return the live connection or raise."""
        if self._conn is None:
            raise RuntimeError("SSHSession is not connected — call connect() first")
        return self._conn

    def is_connected(self) -> bool:
        """Return ``True`` if the underlying connection is still alive."""
        if self._conn is None:
            return False
        try:
            # Accessing the transport attribute probes connection liveness.
            transport = self._conn.get_extra_info("transport")
            return transport is not None
        except (asyncssh.Error, OSError):
            return False

    async def run(self, command: str) -> JSONObject:
        """Execute *command* on the persistent connection.

        Returns:
            ``{exit_code, stdout, stderr}``
        """
        conn = self._require_conn()
        try:
            result = await conn.run(command, check=False)
            exit_status: int = (
                result.exit_status if result.exit_status is not None else -1
            )
            return {
                "exit_code": exit_status,
                "stdout": result.stdout or "",
                "stderr": result.stderr or "",
            }
        except (asyncssh.Error, OSError) as e:
            return {"error": str(e)}

    async def run_background(self, command: str) -> str:
        """Launch *command* in the background via ``nohup``.

        The remote process writes its exit code, stdout, and stderr to
        well-known files under ``/tmp/wm_job_<job_id>.*`` so that
        :meth:`poll_job` can retrieve results later.

        Returns:
            A short UUID4 ``job_id``.
        """
        conn = self._require_conn()
        job_id = uuid.uuid4().hex[:12]
        wrapped = (
            f"nohup sh -c '{command} "
            f">/tmp/wm_job_{job_id}.out "
            f"2>/tmp/wm_job_{job_id}.err; "
            f"echo $? >/tmp/wm_job_{job_id}.rc' &"
        )
        await conn.run(wrapped, check=False)
        return job_id

    async def poll_job(self, job_id: str) -> JSONObject:
        """Check whether a background job has finished.

        Returns:
            ``{status: "running"}`` while the job is in progress, or
            ``{status: "done"|"error", exit_code, stdout, stderr}`` once
            the rc sentinel file exists.
        """
        conn = self._require_conn()
        rc_check = await conn.run(
            f"cat /tmp/wm_job_{job_id}.rc 2>/dev/null", check=False
        )
        rc_text = (rc_check.stdout or "").strip()
        if not rc_text:
            return {"status": "running"}

        stdout_res = await conn.run(
            f"cat /tmp/wm_job_{job_id}.out 2>/dev/null", check=False
        )
        stderr_res = await conn.run(
            f"cat /tmp/wm_job_{job_id}.err 2>/dev/null", check=False
        )
        exit_code = int(rc_text)
        status = "done" if exit_code == 0 else "error"
        return {
            "status": status,
            "exit_code": exit_code,
            "stdout": stdout_res.stdout or "",
            "stderr": stderr_res.stdout or "",
        }

    async def upload(self, local_path: str, remote_path: str) -> JSONObject:
        """Upload a local file to the remote host via SFTP."""
        if not os.path.exists(local_path):
            return {
                "error": f"Local file not found: {local_path}. Check your tools directory."
            }
        conn = self._require_conn()
        try:
            async with conn.start_sftp_client() as sftp:
                await sftp.put(local_path, remote_path)
            return {"result": f"Successfully uploaded {local_path} to {remote_path}"}
        except (asyncssh.Error, OSError) as e:
            return {"error": str(e)}

    async def download(self, remote_path: str, local_path: str) -> JSONObject:
        """Download a file from the remote host via SFTP."""
        conn = self._require_conn()
        try:
            async with conn.start_sftp_client() as sftp:
                await sftp.get(remote_path, local_path)
            return {"result": f"Successfully downloaded {remote_path} to {local_path}"}
        except (asyncssh.Error, OSError) as e:
            return {"error": str(e)}

close() async

Close the persistent SSH connection.

Source code in wintermute/ai/utils/ssh_exec.py
 99
100
101
102
103
104
async def close(self) -> None:
    """Close the persistent SSH connection."""
    if self._conn is not None:
        self._conn.close()
        await self._conn.wait_closed()
        self._conn = None

connect() async

Open the persistent SSH connection.

Source code in wintermute/ai/utils/ssh_exec.py
95
96
97
async def connect(self) -> None:
    """Open the persistent SSH connection."""
    self._conn = await asyncssh.connect(**self._connect_kwargs)

download(remote_path, local_path) async

Download a file from the remote host via SFTP.

Source code in wintermute/ai/utils/ssh_exec.py
209
210
211
212
213
214
215
216
217
async def download(self, remote_path: str, local_path: str) -> JSONObject:
    """Download a file from the remote host via SFTP."""
    conn = self._require_conn()
    try:
        async with conn.start_sftp_client() as sftp:
            await sftp.get(remote_path, local_path)
        return {"result": f"Successfully downloaded {remote_path} to {local_path}"}
    except (asyncssh.Error, OSError) as e:
        return {"error": str(e)}

is_connected()

Return True if the underlying connection is still alive.

Source code in wintermute/ai/utils/ssh_exec.py
112
113
114
115
116
117
118
119
120
121
def is_connected(self) -> bool:
    """Return ``True`` if the underlying connection is still alive."""
    if self._conn is None:
        return False
    try:
        # Accessing the transport attribute probes connection liveness.
        transport = self._conn.get_extra_info("transport")
        return transport is not None
    except (asyncssh.Error, OSError):
        return False

poll_job(job_id) async

Check whether a background job has finished.

Returns:

Type Description
JSONObject

{status: "running"} while the job is in progress, or

JSONObject

{status: "done"|"error", exit_code, stdout, stderr} once

JSONObject

the rc sentinel file exists.

Source code in wintermute/ai/utils/ssh_exec.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
async def poll_job(self, job_id: str) -> JSONObject:
    """Check whether a background job has finished.

    Returns:
        ``{status: "running"}`` while the job is in progress, or
        ``{status: "done"|"error", exit_code, stdout, stderr}`` once
        the rc sentinel file exists.
    """
    conn = self._require_conn()
    rc_check = await conn.run(
        f"cat /tmp/wm_job_{job_id}.rc 2>/dev/null", check=False
    )
    rc_text = (rc_check.stdout or "").strip()
    if not rc_text:
        return {"status": "running"}

    stdout_res = await conn.run(
        f"cat /tmp/wm_job_{job_id}.out 2>/dev/null", check=False
    )
    stderr_res = await conn.run(
        f"cat /tmp/wm_job_{job_id}.err 2>/dev/null", check=False
    )
    exit_code = int(rc_text)
    status = "done" if exit_code == 0 else "error"
    return {
        "status": status,
        "exit_code": exit_code,
        "stdout": stdout_res.stdout or "",
        "stderr": stderr_res.stdout or "",
    }

run(command) async

Execute command on the persistent connection.

Returns:

Type Description
JSONObject

{exit_code, stdout, stderr}

Source code in wintermute/ai/utils/ssh_exec.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
async def run(self, command: str) -> JSONObject:
    """Execute *command* on the persistent connection.

    Returns:
        ``{exit_code, stdout, stderr}``
    """
    conn = self._require_conn()
    try:
        result = await conn.run(command, check=False)
        exit_status: int = (
            result.exit_status if result.exit_status is not None else -1
        )
        return {
            "exit_code": exit_status,
            "stdout": result.stdout or "",
            "stderr": result.stderr or "",
        }
    except (asyncssh.Error, OSError) as e:
        return {"error": str(e)}

run_background(command) async

Launch command in the background via nohup.

The remote process writes its exit code, stdout, and stderr to well-known files under /tmp/wm_job_<job_id>.* so that :meth:poll_job can retrieve results later.

Returns:

Type Description
str

A short UUID4 job_id.

Source code in wintermute/ai/utils/ssh_exec.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
async def run_background(self, command: str) -> str:
    """Launch *command* in the background via ``nohup``.

    The remote process writes its exit code, stdout, and stderr to
    well-known files under ``/tmp/wm_job_<job_id>.*`` so that
    :meth:`poll_job` can retrieve results later.

    Returns:
        A short UUID4 ``job_id``.
    """
    conn = self._require_conn()
    job_id = uuid.uuid4().hex[:12]
    wrapped = (
        f"nohup sh -c '{command} "
        f">/tmp/wm_job_{job_id}.out "
        f"2>/tmp/wm_job_{job_id}.err; "
        f"echo $? >/tmp/wm_job_{job_id}.rc' &"
    )
    await conn.run(wrapped, check=False)
    return job_id

upload(local_path, remote_path) async

Upload a local file to the remote host via SFTP.

Source code in wintermute/ai/utils/ssh_exec.py
195
196
197
198
199
200
201
202
203
204
205
206
207
async def upload(self, local_path: str, remote_path: str) -> JSONObject:
    """Upload a local file to the remote host via SFTP."""
    if not os.path.exists(local_path):
        return {
            "error": f"Local file not found: {local_path}. Check your tools directory."
        }
    conn = self._require_conn()
    try:
        async with conn.start_sftp_client() as sftp:
            await sftp.put(local_path, remote_path)
        return {"result": f"Successfully uploaded {local_path} to {remote_path}"}
    except (asyncssh.Error, OSError) as e:
        return {"error": str(e)}

download_file_async(target_alias, remote_path, local_path, username=None, password=None, port=None) async

Download a file from a remote host via SFTP over asyncssh.

Leverages ~/.ssh/config for host aliases, proxy jumps, and key management when target_alias matches a configured host entry.

Source code in wintermute/ai/utils/ssh_exec.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
async def download_file_async(
    target_alias: str,
    remote_path: str,
    local_path: str,
    username: str | None = None,
    password: str | None = None,
    port: int | None = None,
) -> JSONObject:
    """Download a file from a remote host via SFTP over asyncssh.

    Leverages ``~/.ssh/config`` for host aliases, proxy jumps, and key
    management when *target_alias* matches a configured host entry.
    """
    kwargs = _build_connect_kwargs(target_alias, username, password, port)
    try:
        async with asyncssh.connect(**kwargs) as conn:
            async with conn.start_sftp_client() as sftp:
                await sftp.get(remote_path, local_path)
        return {"result": f"Successfully downloaded {remote_path} to {local_path}"}
    except (asyncssh.Error, OSError) as e:
        return {"error": str(e)}

run_command_async(target_alias, command, username=None, password=None, port=None) async

Execute a command on a remote host via asyncssh.

Leverages ~/.ssh/config for host aliases, proxy jumps, and key management when target_alias matches a configured host entry.

Source code in wintermute/ai/utils/ssh_exec.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
async def run_command_async(
    target_alias: str,
    command: str,
    username: str | None = None,
    password: str | None = None,
    port: int | None = None,
) -> JSONObject:
    """Execute a command on a remote host via asyncssh.

    Leverages ``~/.ssh/config`` for host aliases, proxy jumps, and key
    management when *target_alias* matches a configured host entry.
    """
    kwargs = _build_connect_kwargs(target_alias, username, password, port)
    try:
        async with asyncssh.connect(**kwargs) as conn:
            result = await conn.run(command, check=False)
            exit_status: int = (
                result.exit_status if result.exit_status is not None else -1
            )
            if exit_status != 0:
                return {
                    "exit_code": exit_status,
                    "stderr": result.stderr or "",
                    "stdout": result.stdout or "",
                }
            return {
                "exit_code": 0,
                "stdout": result.stdout or "",
            }
    except (asyncssh.Error, OSError) as e:
        return {"error": str(e)}

upload_file_async(target_alias, local_path, remote_path, username=None, password=None, port=None) async

Upload a local file to a remote host via SFTP over asyncssh.

Leverages ~/.ssh/config for host aliases, proxy jumps, and key management when target_alias matches a configured host entry.

Source code in wintermute/ai/utils/ssh_exec.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
async def upload_file_async(
    target_alias: str,
    local_path: str,
    remote_path: str,
    username: str | None = None,
    password: str | None = None,
    port: int | None = None,
) -> JSONObject:
    """Upload a local file to a remote host via SFTP over asyncssh.

    Leverages ``~/.ssh/config`` for host aliases, proxy jumps, and key
    management when *target_alias* matches a configured host entry.
    """
    if not os.path.exists(local_path):
        return {
            "error": f"Local file not found: {local_path}. Check your tools directory."
        }

    kwargs = _build_connect_kwargs(target_alias, username, password, port)
    try:
        async with asyncssh.connect(**kwargs) as conn:
            async with conn.start_sftp_client() as sftp:
                await sftp.put(local_path, remote_path)
        return {"result": f"Successfully uploaded {local_path} to {remote_path}"}
    except (asyncssh.Error, OSError) as e:
        return {"error": str(e)}