or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-fabric

A Python library and command-line tool for streamlining SSH usage in application deployment and systems administration.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/fabric@1.10.x

To install, run

npx @tessl/cli install tessl/pypi-fabric@1.10.0

0

# Fabric

1

2

Fabric is a Python library and command-line tool that streamlines SSH usage for application deployment and systems administration tasks. It provides a comprehensive suite of operations for executing local or remote shell commands (including sudo), uploading/downloading files, and auxiliary functionality like user input prompting and execution control. The library offers a Pythonic interface to SSH protocol operations at a higher level than direct SSH libraries like Paramiko, enabling developers to create deployment scripts and automation tools through simple Python functions that can be executed via the 'fab' command-line tool across multiple servers simultaneously.

3

4

## Package Information

5

6

- **Package Name**: Fabric

7

- **Language**: Python

8

- **Installation**: `pip install fabric`

9

- **Command Line Tool**: `fab`

10

11

## Core Imports

12

13

```python

14

from fabric.api import *

15

```

16

17

Or import specific functions:

18

19

```python

20

from fabric.api import run, sudo, put, get, env, cd, settings

21

```

22

23

Individual module imports:

24

25

```python

26

from fabric.operations import run, sudo, local, put, get

27

from fabric.context_managers import cd, lcd, settings, hide

28

from fabric.decorators import task, hosts, roles

29

from fabric.state import env, output

30

from fabric.utils import abort, warn, puts

31

```

32

33

Contrib module imports:

34

35

```python

36

from fabric.contrib.files import exists, upload_template, sed, comment, append

37

from fabric.contrib.project import rsync_project, upload_project

38

from fabric.contrib.console import confirm

39

```

40

41

## Basic Usage

42

43

```python

44

from fabric.api import run, sudo, put, env, cd, task

45

46

# Set connection details

47

env.hosts = ['user@example.com']

48

env.key_filename = '/path/to/private/key'

49

50

@task

51

def deploy():

52

# Execute remote commands

53

run('git pull origin master')

54

55

# Use sudo for privileged operations

56

sudo('systemctl restart nginx')

57

58

# Change directories with context manager

59

with cd('/var/www/myapp'):

60

run('npm install')

61

run('npm run build')

62

63

# Upload files

64

put('local/config.json', '/etc/myapp/config.json', use_sudo=True)

65

66

# Run with: fab deploy

67

```

68

69

## Architecture

70

71

Fabric's architecture centers around several key components:

72

73

- **Global Environment (env)**: Central configuration dictionary containing connection settings, execution parameters, and runtime state

74

- **Operations**: Core functions for local/remote command execution, file transfer, and user interaction

75

- **Context Managers**: Temporary state modification tools for directories, settings, and output control

76

- **Decorators**: Function decorators for task definition, host/role specification, and execution control

77

- **State Management**: Global variables and configuration that persist across function calls

78

- **CLI Integration**: Command-line interface for executing tasks across multiple hosts

79

80

This design enables both programmatic use as a library and command-line execution as a deployment tool, with seamless integration between SSH operations and Python control flow.

81

82

## Capabilities

83

84

### Core Operations

85

86

Essential remote and local command execution, including standard shell commands and privileged operations via sudo. These operations form the foundation of Fabric's automation capabilities.

87

88

```python { .api }

89

def run(command, shell=True, pty=True, combine_stderr=None, quiet=False, warn_only=False, stdout=None, stderr=None, timeout=None, shell_escape=None):

90

"""Execute shell command on remote host"""

91

92

def sudo(command, shell=True, pty=True, combine_stderr=None, user=None, quiet=False, warn_only=False, stdout=None, stderr=None, group=None, timeout=None, shell_escape=None):

93

"""Execute command with superuser privileges"""

94

95

def local(command, capture=False, shell=None):

96

"""Execute command on local system"""

97

```

98

99

[Core Operations](./core-operations.md)

100

101

### Context Management

102

103

Temporary state modification tools for managing directories, environment settings, output control, and SSH tunneling. Context managers ensure clean state restoration and enable nested operations.

104

105

```python { .api }

106

def cd(path):

107

"""Context manager for remote directory changes"""

108

109

def lcd(path):

110

"""Context manager for local directory changes"""

111

112

def settings(*args, **kwargs):

113

"""Context manager for temporary environment variable overrides"""

114

115

def hide(*groups):

116

"""Context manager to hide output groups"""

117

118

def shell_env(**kw):

119

"""Context manager to set shell environment variables"""

120

```

121

122

[Context Management](./context-management.md)

123

124

### Task Definition and Execution

125

126

Decorators and functions for defining Fabric tasks, specifying target hosts and roles, and controlling execution patterns including parallel and serial execution modes.

127

128

```python { .api }

129

def task(*args, **kwargs):

130

"""Decorator to mark functions as Fabric tasks"""

131

132

def hosts(*host_list):

133

"""Decorator to specify target hosts for a task"""

134

135

def roles(*role_list):

136

"""Decorator to specify target roles for a task"""

137

138

def execute(task, *args, **kwargs):

139

"""Execute task with host/role resolution"""

140

```

141

142

[Decorators and Tasks](./decorators-tasks.md)

143

144

### File Operations

145

146

File transfer capabilities including basic upload/download operations and advanced file management functions for template rendering, text processing, and project synchronization.

147

148

```python { .api }

149

def put(local_path=None, remote_path=None, use_sudo=False, mirror_local_mode=False, mode=None, use_glob=True, temp_dir=""):

150

"""Upload files to remote host"""

151

152

def get(remote_path, local_path=None, use_sudo=False, temp_dir=""):

153

"""Download files from remote host"""

154

```

155

156

[File Operations](./file-operations.md)

157

158

## Global State and Configuration

159

160

### Environment Dictionary (env)

161

162

```python { .api }

163

env = _AttributeDict()

164

"""Global environment dictionary containing connection and execution settings"""

165

```

166

167

**Key Connection Settings:**

168

- `env.hosts` - List of host strings for task execution

169

- `env.user` - Default username for SSH connections

170

- `env.password` - Default password for SSH connections

171

- `env.key_filename` - Path to SSH private key file(s)

172

- `env.port` - Default SSH port (default: 22)

173

- `env.gateway` - SSH gateway/bastion host configuration

174

175

**Key Execution Settings:**

176

- `env.warn_only` - Continue execution on command failure (default: False)

177

- `env.shell` - Shell command prefix (default: '/bin/bash -l -c')

178

- `env.sudo_prefix` - Sudo command prefix template

179

- `env.parallel` - Enable parallel execution (default: False)

180

- `env.pool_size` - Number of concurrent connections for parallel execution

181

182

### Output Control Dictionary (output)

183

184

```python { .api }

185

output = _AliasDict()

186

"""Output control settings dictionary"""

187

```

188

189

**Output Categories:**

190

- `output.running` - Show "[host] run: command" lines

191

- `output.stdout` - Show command standard output

192

- `output.stderr` - Show command standard error

193

- `output.warnings` - Show warning messages

194

- `output.aborts` - Show abort messages

195

- `output.debug` - Show debug information

196

197

## Exception Classes

198

199

```python { .api }

200

class NetworkError(Exception):

201

"""Network-related errors during SSH operations"""

202

203

class CommandTimeout(Exception):

204

"""Command execution timeout errors"""

205

```

206

207

## Utility Functions

208

209

```python { .api }

210

def abort(msg):

211

"""Abort execution with error message"""

212

213

def warn(msg):

214

"""Print warning message without aborting"""

215

216

def puts(text, show_prefix=None, end="\n", flush=False):

217

"""Managed print function with prefix support"""

218

219

def fastprint(text, show_prefix=False, end="", flush=True):

220

"""Immediate print without buffering"""

221

222

def prompt(text, key=None, default='', validate=None):

223

"""Prompt user for input with validation"""

224

```

225

226

## Return Value Objects

227

228

Operations return enhanced string and list objects with additional attributes:

229

230

```python { .api }

231

class _AttributeString(str):

232

"""String subclass with execution metadata"""

233

# Attributes: .failed, .succeeded, .return_code, .command, .real_command, .stderr

234

235

class _AttributeList(list):

236

"""List subclass for file transfer results"""

237

# Attributes: .failed, .succeeded

238

```