or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-execution.mdconfiguration.mddevice-connection.mdexceptions.mdfacts.mdfilesystem.mdindex.mdoperational-tables.mdsoftware.md

filesystem.mddocs/

0

# File System Operations

1

2

File system and transfer utilities for secure file operations, including SCP and FTP transfers, directory operations, file management, and shell session management for advanced file system operations.

3

4

## Capabilities

5

6

### File System Utility Class

7

8

The FS utility provides comprehensive file system operations including directory management, file operations, and storage information retrieval.

9

10

```python { .api }

11

class FS:

12

def __init__(self, dev):

13

"""

14

Initialize FS utility bound to a device.

15

16

Parameters:

17

- dev (Device): Device object to bind to

18

"""

19

```

20

21

### Secure Copy (SCP) Operations

22

23

The SCP utility provides secure file transfer capabilities for copying files to and from Junos devices over SSH connections.

24

25

```python { .api }

26

class SCP:

27

def __init__(self, dev):

28

"""

29

Initialize SCP utility bound to a device.

30

31

Parameters:

32

- dev (Device): Device object to bind to

33

"""

34

35

def put(self, local_file, remote_path='.', progress=None):

36

"""

37

Copy local file to remote device using SCP.

38

39

Parameters:

40

- local_file (str): Local file path to upload

41

- remote_path (str): Remote directory or file path

42

- progress (callable): Progress callback function

43

44

Returns:

45

- bool: True if transfer successful

46

47

Raises:

48

- ScpError: SCP transfer failed

49

- FileNotFoundError: Local file not found

50

"""

51

52

def get(self, remote_file, local_path='.', progress=None):

53

"""

54

Copy remote file from device to local system using SCP.

55

56

Parameters:

57

- remote_file (str): Remote file path to download

58

- local_path (str): Local directory or file path

59

- progress (callable): Progress callback function

60

61

Returns:

62

- bool: True if transfer successful

63

64

Raises:

65

- ScpError: SCP transfer failed

66

"""

67

```

68

69

### FTP Operations

70

71

The FTP utility provides FTP file transfer capabilities for devices that support FTP file transfers.

72

73

```python { .api }

74

class FTP:

75

def __init__(self, dev):

76

"""

77

Initialize FTP utility bound to a device.

78

79

Parameters:

80

- dev (Device): Device object to bind to

81

"""

82

83

def put(self, local_file, remote_path='.', progress=None):

84

"""

85

Upload local file to device using FTP.

86

87

Parameters:

88

- local_file (str): Local file path to upload

89

- remote_path (str): Remote directory or file path

90

- progress (callable): Progress callback function

91

92

Returns:

93

- bool: True if transfer successful

94

95

Raises:

96

- FtpError: FTP transfer failed

97

"""

98

99

def get(self, remote_file, local_path='.', progress=None):

100

"""

101

Download remote file from device using FTP.

102

103

Parameters:

104

- remote_file (str): Remote file path to download

105

- local_path (str): Local directory or file path

106

- progress (callable): Progress callback function

107

108

Returns:

109

- bool: True if transfer successful

110

111

Raises:

112

- FtpError: FTP transfer failed

113

"""

114

```

115

116

### Shell Session Management

117

118

The StartShell utility provides shell session management for advanced file system operations and command execution outside of the NETCONF session.

119

120

```python { .api }

121

class StartShell:

122

def __init__(self, dev):

123

"""

124

Initialize StartShell utility bound to a device.

125

126

Parameters:

127

- dev (Device): Device object to bind to

128

"""

129

130

def open(self, **kwargs):

131

"""

132

Open shell session on the device.

133

134

Parameters:

135

- **kwargs: Shell session parameters

136

137

Returns:

138

- bool: True if shell session opened successfully

139

140

Raises:

141

- ConnectError: Shell session failed to open

142

"""

143

144

def close(self):

145

"""

146

Close shell session.

147

148

Returns:

149

- bool: True if shell session closed successfully

150

"""

151

152

def run(self, command, timeout=None):

153

"""

154

Execute command in shell session.

155

156

Parameters:

157

- command (str): Shell command to execute

158

- timeout (int): Command timeout in seconds

159

160

Returns:

161

- tuple: (status, output) where status is True/False and output is command result

162

163

Raises:

164

- ShellTimeoutError: Command execution timed out

165

"""

166

```

167

168

### Utility Binding

169

170

Bind file system utilities to Device instances to enable file operations.

171

172

```python { .api }

173

# Binding utilities to device

174

dev.bind(fs=FS) # File system operations

175

dev.bind(scp=SCP) # Secure copy operations

176

dev.bind(ftp=FTP) # FTP operations

177

dev.bind(shell=StartShell) # Shell operations

178

179

# Access bound utilities

180

dev.scp.put('/local/file.txt', '/var/tmp/')

181

dev.fs.method() # File system operations

182

```

183

184

## Usage Examples

185

186

### Basic SCP File Transfer

187

188

```python

189

from jnpr.junos import Device

190

from jnpr.junos.utils.scp import SCP

191

192

dev = Device(host='router1.example.com', user='admin', passwd='secret')

193

dev.open()

194

195

# Bind SCP utility

196

dev.bind(scp=SCP)

197

198

# Upload file to device

199

local_file = '/home/user/config-backup.txt'

200

remote_path = '/var/tmp/'

201

202

try:

203

result = dev.scp.put(local_file, remote_path)

204

if result:

205

print("File uploaded successfully")

206

else:

207

print("File upload failed")

208

except Exception as e:

209

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

210

211

# Download file from device

212

remote_file = '/var/log/messages'

213

local_path = '/home/user/device-logs/'

214

215

try:

216

result = dev.scp.get(remote_file, local_path)

217

if result:

218

print("File downloaded successfully")

219

except Exception as e:

220

print(f"SCP download error: {e}")

221

222

dev.close()

223

```

224

225

### SCP with Progress Tracking

226

227

```python

228

from jnpr.junos import Device

229

from jnpr.junos.utils.scp import SCP

230

231

def scp_progress(filename, size, sent):

232

"""Progress callback for SCP operations."""

233

percent = (sent / size) * 100

234

print(f"Transferring {filename}: {percent:.1f}% ({sent}/{size} bytes)")

235

236

dev = Device(host='router1.example.com', user='admin', passwd='secret')

237

dev.open()

238

dev.bind(scp=SCP)

239

240

# Upload large file with progress tracking

241

large_file = '/home/user/large-backup.tgz'

242

243

dev.scp.put(

244

large_file,

245

'/var/tmp/',

246

progress=scp_progress

247

)

248

249

dev.close()

250

```

251

252

### Multiple File Operations

253

254

```python

255

from jnpr.junos import Device

256

from jnpr.junos.utils.scp import SCP

257

import os

258

259

dev = Device(host='router1.example.com', user='admin', passwd='secret')

260

dev.open()

261

dev.bind(scp=SCP)

262

263

# Upload multiple configuration files

264

config_files = [

265

'/home/user/configs/interfaces.conf',

266

'/home/user/configs/protocols.conf',

267

'/home/user/configs/policies.conf'

268

]

269

270

for config_file in config_files:

271

if os.path.exists(config_file):

272

filename = os.path.basename(config_file)

273

print(f"Uploading {filename}...")

274

275

result = dev.scp.put(config_file, '/var/tmp/')

276

if result:

277

print(f" {filename} uploaded successfully")

278

else:

279

print(f" {filename} upload failed")

280

else:

281

print(f" {config_file} not found")

282

283

dev.close()

284

```

285

286

### FTP File Transfer

287

288

```python

289

from jnpr.junos import Device

290

from jnpr.junos.utils.ftp import FTP

291

292

dev = Device(host='router1.example.com', user='admin', passwd='secret')

293

dev.open()

294

295

# Bind FTP utility

296

dev.bind(ftp=FTP)

297

298

# Upload file using FTP

299

local_file = '/home/user/firmware.img'

300

301

try:

302

result = dev.ftp.put(local_file, '/var/tmp/')

303

if result:

304

print("FTP upload successful")

305

except Exception as e:

306

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

307

308

dev.close()

309

```

310

311

### Shell Session Operations

312

313

```python

314

from jnpr.junos import Device

315

from jnpr.junos.utils.start_shell import StartShell

316

317

dev = Device(host='router1.example.com', user='admin', passwd='secret')

318

dev.open()

319

320

# Bind shell utility

321

dev.bind(shell=StartShell)

322

323

try:

324

# Open shell session

325

dev.shell.open()

326

327

# Execute shell commands

328

status, output = dev.shell.run('ls -la /var/tmp/')

329

if status:

330

print("Directory listing:")

331

print(output)

332

333

# Check disk space

334

status, output = dev.shell.run('df -h')

335

if status:

336

print("Disk usage:")

337

print(output)

338

339

# Create directory

340

status, output = dev.shell.run('mkdir -p /var/tmp/backups')

341

if status:

342

print("Directory created successfully")

343

344

except Exception as e:

345

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

346

finally:

347

# Always close shell session

348

dev.shell.close()

349

350

dev.close()

351

```

352

353

### Backup and Restore Operations

354

355

```python

356

from jnpr.junos import Device

357

from jnpr.junos.utils.scp import SCP

358

from jnpr.junos.utils.config import Config

359

import datetime

360

361

def backup_configuration(dev, backup_dir):

362

"""Backup device configuration."""

363

hostname = dev.facts['hostname']

364

timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')

365

366

# Get configuration

367

config_xml = dev.rpc.get_config(format='xml')

368

config_text = dev.rpc.get_config(format='text')

369

370

# Save configurations locally

371

xml_file = f"{backup_dir}/{hostname}_config_{timestamp}.xml"

372

text_file = f"{backup_dir}/{hostname}_config_{timestamp}.txt"

373

374

with open(xml_file, 'w') as f:

375

f.write(str(config_xml))

376

377

with open(text_file, 'w') as f:

378

f.write(str(config_text))

379

380

print(f"Configuration backed up to {xml_file} and {text_file}")

381

return xml_file, text_file

382

383

dev = Device(host='router1.example.com', user='admin', passwd='secret')

384

dev.open()

385

dev.bind(scp=SCP)

386

dev.bind(cu=Config)

387

388

# Backup configuration

389

backup_files = backup_configuration(dev, '/home/user/backups')

390

391

# Upload backup to device for remote storage

392

for backup_file in backup_files:

393

dev.scp.put(backup_file, '/var/tmp/backups/')

394

print(f"Backup uploaded: {backup_file}")

395

396

dev.close()

397

```

398

399

### Log File Collection

400

401

```python

402

from jnpr.junos import Device

403

from jnpr.junos.utils.scp import SCP

404

import os

405

406

dev = Device(host='router1.example.com', user='admin', passwd='secret')

407

dev.open()

408

dev.bind(scp=SCP)

409

410

# Define log files to collect

411

log_files = [

412

'/var/log/messages',

413

'/var/log/chassisd',

414

'/var/log/rpd',

415

'/var/log/dcd'

416

]

417

418

# Create local directory for logs

419

hostname = dev.facts['hostname']

420

log_dir = f'/home/user/logs/{hostname}'

421

os.makedirs(log_dir, exist_ok=True)

422

423

# Download log files

424

for log_file in log_files:

425

try:

426

filename = os.path.basename(log_file)

427

local_path = os.path.join(log_dir, filename)

428

429

print(f"Downloading {log_file}...")

430

result = dev.scp.get(log_file, local_path)

431

432

if result:

433

print(f" Downloaded to {local_path}")

434

else:

435

print(f" Failed to download {log_file}")

436

437

except Exception as e:

438

print(f" Error downloading {log_file}: {e}")

439

440

print(f"Log collection completed. Files saved to {log_dir}")

441

442

dev.close()

443

```

444

445

### Error Handling

446

447

```python

448

from jnpr.junos import Device

449

from jnpr.junos.utils.scp import SCP

450

from jnpr.junos.exception import ScpError

451

452

dev = Device(host='router1.example.com', user='admin', passwd='secret')

453

dev.open()

454

dev.bind(scp=SCP)

455

456

local_file = '/home/user/test-file.txt'

457

remote_path = '/var/tmp/'

458

459

try:

460

result = dev.scp.put(local_file, remote_path)

461

print("File transfer successful")

462

463

except ScpError as e:

464

print(f"SCP transfer failed: {e}")

465

466

except FileNotFoundError:

467

print(f"Local file not found: {local_file}")

468

469

except PermissionError:

470

print("Permission denied - check file permissions")

471

472

except Exception as e:

473

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

474

475

dev.close()

476

```

477

478

## Types

479

480

```python { .api }

481

# File path types

482

LocalPath = str # Local file or directory path

483

RemotePath = str # Remote file or directory path

484

485

# Progress callback type

486

ProgressCallback = callable # Function(filename, size, sent) for progress updates

487

488

# Transfer result type

489

TransferResult = bool # True if transfer successful

490

491

# Shell command types

492

ShellCommand = str # Shell command string

493

ShellOutput = str # Shell command output

494

ShellStatus = bool # Shell command execution status

495

496

# Shell result type

497

ShellResult = tuple[bool, str] # (status, output) tuple

498

```