or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdfile-transfer.mdindex.mdinteractive-shells.mdoutput-handling.mdparallel-operations.mdsingle-host-operations.md

single-host-operations.mddocs/

0

# Single Host SSH Operations

1

2

Connect to and execute commands on individual hosts with the same rich feature set as parallel operations. Ideal for single-host workflows, debugging, or when parallel execution is not needed.

3

4

## Capabilities

5

6

### SSHClient Initialization

7

8

Create an SSH client for connecting to a single host with comprehensive authentication and connection options.

9

10

```python { .api }

11

class SSHClient:

12

def __init__(self, host, user=None, password=None, port=None, pkey=None,

13

alias=None, num_retries=DEFAULT_RETRIES, retry_delay=RETRY_DELAY,

14

allow_agent=True, timeout=None, forward_ssh_agent=False,

15

proxy_host=None, proxy_port=None, proxy_pkey=None,

16

proxy_user=None, proxy_password=None, _auth_thread_pool=True,

17

keepalive_seconds=60, identity_auth=True, ipv6_only=False):

18

"""

19

Create SSH client for single host.

20

21

Parameters:

22

- host (str): Hostname or IP address

23

- user (str, optional): Username for authentication

24

- password (str, optional): Password for authentication

25

- port (int, optional): SSH port number (default: 22)

26

- pkey (str or bytes, optional): Private key file path or key data

27

- alias (str, optional): Host alias for identification

28

- num_retries (int, optional): Connection retry attempts (default: 3)

29

- retry_delay (float, optional): Delay between retries (default: 5)

30

- allow_agent (bool, optional): Use SSH agent authentication (default: True)

31

- timeout (float, optional): Session timeout in seconds

32

- forward_ssh_agent (bool, optional): SSH agent forwarding (default: False)

33

- proxy_host (str, optional): SSH proxy hostname

34

- proxy_port (int, optional): SSH proxy port

35

- proxy_pkey (str or bytes, optional): SSH proxy private key

36

- proxy_user (str, optional): SSH proxy username

37

- proxy_password (str, optional): SSH proxy password

38

- _auth_thread_pool (bool, optional): Use thread pool for authentication (default: True)

39

- keepalive_seconds (int, optional): Keepalive interval (default: 60)

40

- identity_auth (bool, optional): Identity file authentication (default: True)

41

- ipv6_only (bool, optional): IPv6 only mode (default: False)

42

"""

43

```

44

45

Usage examples:

46

47

```python

48

from pssh.clients import SSHClient

49

50

# Simple connection

51

client = SSHClient('server.example.com', user='admin')

52

53

# With private key authentication

54

client = SSHClient('server.example.com', user='admin', pkey='~/.ssh/id_rsa')

55

56

# Through SSH proxy

57

client = SSHClient(

58

'internal-server.example.com',

59

user='admin',

60

proxy_host='bastion.example.com',

61

proxy_user='proxy_user'

62

)

63

64

# With custom port and alias

65

client = SSHClient(

66

'192.168.1.100',

67

port=2222,

68

user='admin',

69

alias='dev-server'

70

)

71

```

72

73

### Single Host Command Execution

74

75

Execute commands on the connected host with options for sudo, user switching, and output handling.

76

77

```python { .api }

78

def run_command(self, command, sudo=False, user=None, use_pty=False,

79

shell=None, encoding='utf-8', timeout=None, read_timeout=None):

80

"""

81

Execute command on the host.

82

83

Parameters:

84

- command (str): Command to execute

85

- sudo (bool, optional): Run command with sudo (default: False)

86

- user (str, optional): Run command as different user

87

- use_pty (bool, optional): Use pseudo-terminal (default: False)

88

- shell (str, optional): Shell to use for command execution

89

- encoding (str, optional): Output encoding (default: 'utf-8')

90

- timeout (float, optional): Command execution timeout

91

- read_timeout (float, optional): Output read timeout

92

93

Returns:

94

HostOutput: Object containing command results and output streams

95

"""

96

```

97

98

Usage examples:

99

100

```python

101

# Basic command execution

102

host_output = client.run_command('ls -la /home')

103

104

# Process output

105

for line in host_output.stdout:

106

print(line)

107

print(f"Exit code: {host_output.exit_code}")

108

109

# Run with sudo

110

host_output = client.run_command('systemctl restart nginx', sudo=True)

111

112

# Run as different user

113

host_output = client.run_command('whoami', user='www-data')

114

115

# Long running command with timeout

116

try:

117

host_output = client.run_command('sleep 30', timeout=10)

118

except Timeout:

119

print("Command timed out")

120

```

121

122

### Session Management

123

124

Manage SSH sessions and channels for more granular control over connections.

125

126

```python { .api }

127

def open_session(self):

128

"""

129

Open a new SSH channel session.

130

131

Returns:

132

ssh2.channel.Channel: New SSH channel for command execution

133

"""

134

135

def close_channel(self, channel):

136

"""

137

Close an SSH channel.

138

139

Parameters:

140

- channel: SSH channel to close

141

"""

142

143

def get_exit_status(self, channel):

144

"""

145

Get exit status from a channel.

146

147

Parameters:

148

- channel: SSH channel to check

149

150

Returns:

151

int or None: Exit status if available, None if not ready

152

"""

153

154

def finished(self, channel):

155

"""

156

Check if command on channel has finished.

157

158

Parameters:

159

- channel: SSH channel to check

160

161

Returns:

162

bool: True if command finished, False otherwise

163

"""

164

```

165

166

Usage example:

167

168

```python

169

# Manual session management

170

channel = client.open_session()

171

channel.execute('long_running_command')

172

173

# Check periodically if finished

174

import time

175

while not client.finished(channel):

176

time.sleep(1)

177

print("Still running...")

178

179

exit_code = client.get_exit_status(channel)

180

client.close_channel(channel)

181

print(f"Command finished with exit code: {exit_code}")

182

```

183

184

### Result Synchronization

185

186

Wait for command completion with timeout handling.

187

188

```python { .api }

189

def wait_finished(self, host_output, timeout=None):

190

"""

191

Wait for command in host_output to complete.

192

193

Parameters:

194

- host_output (HostOutput): Host output object to wait for

195

- timeout (float, optional): Timeout in seconds

196

197

Raises:

198

- Timeout: If timeout is reached before completion

199

"""

200

```

201

202

Usage example:

203

204

```python

205

# Execute and wait for completion

206

host_output = client.run_command('backup_database.sh')

207

208

try:

209

client.wait_finished(host_output, timeout=300) # 5 minute timeout

210

print("Backup completed successfully")

211

print(f"Exit code: {host_output.exit_code}")

212

except Timeout:

213

print("Backup did not complete within 5 minutes")

214

```

215

216

### Advanced Buffer and Output Management

217

218

Manage low-level output buffers and read operations for fine-grained control over command output processing.

219

220

```python { .api }

221

def read_output(self, stdout_buffer, timeout=None):

222

"""

223

Read output from stdout buffer.

224

225

Parameters:

226

- stdout_buffer: Output buffer to read from

227

- timeout (float, optional): Read timeout in seconds

228

229

Returns:

230

generator: Lines from stdout buffer

231

"""

232

233

def read_stderr(self, stderr_buffer, timeout=None):

234

"""

235

Read output from stderr buffer.

236

237

Parameters:

238

- stderr_buffer: Error buffer to read from

239

- timeout (float, optional): Read timeout in seconds

240

241

Returns:

242

generator: Lines from stderr buffer

243

"""

244

245

def read_output_buffer(self, output_buffer, prefix=None, callback=None,

246

callback_args=None, encoding='utf-8'):

247

"""

248

Read from output buffer with optional processing.

249

250

Parameters:

251

- output_buffer: Buffer to read from

252

- prefix (str, optional): Prefix for output lines

253

- callback (callable, optional): Callback function for each line

254

- callback_args (tuple, optional): Arguments for callback function

255

- encoding (str, optional): Text encoding (default: 'utf-8')

256

257

Returns:

258

generator: Processed output lines

259

"""

260

```

261

262

### SFTP Low-Level Operations

263

264

Direct SFTP operations for advanced use cases requiring fine-grained control over file transfers.

265

266

```python { .api }

267

def sftp_put(self, sftp, local_file, remote_file):

268

"""

269

Upload file via SFTP session.

270

271

Parameters:

272

- sftp: Active SFTP session object

273

- local_file (str): Local file path

274

- remote_file (str): Remote destination path

275

"""

276

277

def sftp_get(self, sftp, remote_file, local_file):

278

"""

279

Download file via SFTP session.

280

281

Parameters:

282

- sftp: Active SFTP session object

283

- remote_file (str): Remote file path

284

- local_file (str): Local destination path

285

"""

286

287

def mkdir(self, sftp, directory):

288

"""

289

Create directory via SFTP.

290

291

Parameters:

292

- sftp: Active SFTP session object

293

- directory (str): Directory path to create

294

"""

295

```

296

297

## Error Handling

298

299

The single host client provides comprehensive error handling:

300

301

```python

302

from pssh.exceptions import (

303

UnknownHostError, ConnectionError, AuthenticationError,

304

SessionError, Timeout, PKeyFileError

305

)

306

307

try:

308

client = SSHClient('unreachable-host.example.com')

309

host_output = client.run_command('echo test')

310

except UnknownHostError as e:

311

print(f"Host not found: {e}")

312

except ConnectionError as e:

313

print(f"Connection failed: {e}")

314

except AuthenticationError as e:

315

print(f"Authentication failed: {e}")

316

except SessionError as e:

317

print(f"Session error: {e}")

318

except PKeyFileError as e:

319

print(f"Private key error: {e}")

320

```

321

322

## Authentication Methods

323

324

The SSHClient supports multiple authentication methods:

325

326

```python

327

# Password authentication

328

client = SSHClient('host.example.com', user='admin', password='secret')

329

330

# Private key file authentication

331

client = SSHClient('host.example.com', user='admin', pkey='/path/to/key')

332

333

# Private key data authentication

334

with open('/path/to/key', 'rb') as f:

335

key_data = f.read()

336

client = SSHClient('host.example.com', user='admin', pkey=key_data)

337

338

# SSH agent authentication (default)

339

client = SSHClient('host.example.com', user='admin', allow_agent=True)

340

341

# Disable SSH agent and identity files

342

client = SSHClient(

343

'host.example.com',

344

user='admin',

345

allow_agent=False,

346

identity_auth=False,

347

password='secret'

348

)

349

```

350

351

## Connection Reuse

352

353

For multiple operations on the same host, reuse the client instance to avoid reconnection overhead:

354

355

```python

356

client = SSHClient('host.example.com', user='admin')

357

358

# Multiple operations on same connection

359

host_output1 = client.run_command('uptime')

360

host_output2 = client.run_command('df -h')

361

host_output3 = client.run_command('ps aux | head -10')

362

363

# Process all results

364

for i, output in enumerate([host_output1, host_output2, host_output3], 1):

365

print(f"Command {i} output:")

366

for line in output.stdout:

367

print(f" {line}")

368

```