0
# Core Operations
1
2
Essential remote and local command execution functions that form the foundation of Fabric's automation capabilities. These operations provide the primary interface for executing shell commands both locally and on remote hosts, with comprehensive support for privileged operations, output capture, and error handling.
3
4
## Capabilities
5
6
### Remote Command Execution
7
8
Execute shell commands on remote hosts with full control over execution environment, output capture, and error handling.
9
10
```python { .api }
11
def run(command, shell=True, pty=True, combine_stderr=None, quiet=False, warn_only=False, stdout=None, stderr=None, timeout=None, shell_escape=None):
12
"""
13
Execute shell command on remote host.
14
15
Args:
16
command (str): Shell command to execute
17
shell (bool): Execute via shell (default: True)
18
pty (bool): Request pseudo-terminal (default: True)
19
combine_stderr (bool): Combine stderr with stdout
20
quiet (bool): Suppress all output (default: False)
21
warn_only (bool): Continue on failure (default: False)
22
stdout (file): File-like object for stdout capture
23
stderr (file): File-like object for stderr capture
24
timeout (int): Command timeout in seconds
25
shell_escape (bool): Escape shell characters
26
27
Returns:
28
_AttributeString: Command output with execution metadata
29
.failed (bool): True if command failed
30
.succeeded (bool): True if command succeeded
31
.return_code (int): Command exit code
32
.command (str): Original command string
33
.real_command (str): Actual executed command
34
.stderr (str): Standard error output
35
"""
36
```
37
38
**Usage Examples:**
39
40
```python
41
from fabric.api import run, env
42
43
# Basic command execution
44
result = run('ls -la')
45
print(result) # Command output
46
print(result.return_code) # Exit code
47
48
# Execute with error handling
49
result = run('some-command', warn_only=True)
50
if result.failed:
51
print(f"Command failed with code {result.return_code}")
52
53
# Capture output to variables
54
output = run('cat /proc/meminfo', quiet=True)
55
if 'MemTotal' in output:
56
print("Found memory information")
57
58
# Set timeout for long-running commands
59
run('backup-database.sh', timeout=3600) # 1 hour timeout
60
```
61
62
### Privileged Command Execution
63
64
Execute commands with superuser privileges using sudo, with support for custom users, groups, and sudo configuration.
65
66
```python { .api }
67
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):
68
"""
69
Execute command with superuser privileges.
70
71
Args:
72
command (str): Shell command to execute
73
shell (bool): Execute via shell (default: True)
74
pty (bool): Request pseudo-terminal (default: True)
75
combine_stderr (bool): Combine stderr with stdout
76
user (str): Target user for command execution (default: root)
77
quiet (bool): Suppress all output (default: False)
78
warn_only (bool): Continue on failure (default: False)
79
stdout (file): File-like object for stdout capture
80
stderr (file): File-like object for stderr capture
81
group (str): Target group for command execution
82
timeout (int): Command timeout in seconds
83
shell_escape (bool): Escape shell characters
84
85
Returns:
86
_AttributeString: Command output with execution metadata
87
"""
88
```
89
90
**Usage Examples:**
91
92
```python
93
from fabric.api import sudo, env
94
95
# Basic privileged command
96
sudo('systemctl restart nginx')
97
98
# Execute as specific user
99
sudo('npm install', user='nodeapp')
100
101
# Execute with specific group
102
sudo('chgrp -R webdev /var/www/', group='webdev')
103
104
# Handle sudo password prompts
105
env.sudo_password = 'mypassword'
106
sudo('apt-get update')
107
108
# Privileged file operations
109
sudo('cp config.json /etc/myapp/')
110
sudo('chmod 644 /etc/myapp/config.json')
111
```
112
113
### Local Command Execution
114
115
Execute commands on the local system where Fabric is running, useful for preprocessing, git operations, and local file management.
116
117
```python { .api }
118
def local(command, capture=False, shell=None):
119
"""
120
Execute command on local system.
121
122
Args:
123
command (str): Shell command to execute
124
capture (bool): Capture output instead of printing (default: False)
125
shell (str): Shell to use for execution
126
127
Returns:
128
_AttributeString: Command output with execution metadata
129
"""
130
```
131
132
**Usage Examples:**
133
134
```python
135
from fabric.api import local, run
136
137
# Basic local command
138
local('git pull origin master')
139
140
# Capture local command output
141
git_status = local('git status --porcelain', capture=True)
142
if git_status:
143
print("Local changes detected")
144
145
# Local preprocessing before remote deployment
146
local('npm run build')
147
run('systemctl reload nginx') # Deploy on remote
148
149
# Use custom shell
150
local('echo $BASH_VERSION', shell='/bin/bash')
151
```
152
153
### Interactive Operations
154
155
Operations that provide user interaction capabilities during task execution.
156
157
```python { .api }
158
def prompt(text, key=None, default='', validate=None):
159
"""
160
Prompt user for input with optional validation.
161
162
Args:
163
text (str): Prompt message to display
164
key (str): Environment key to store result
165
default (str): Default value if no input provided
166
validate (str|callable): Validation pattern or function
167
168
Returns:
169
str: User input value
170
"""
171
172
def reboot(wait=120, command='reboot'):
173
"""
174
Reboot remote system and wait for reconnection.
175
176
Args:
177
wait (int): Seconds to wait before reconnecting (default: 120)
178
command (str): Reboot command to execute (default: 'reboot')
179
"""
180
181
def open_shell(command=None):
182
"""
183
Open interactive shell on remote host.
184
185
Args:
186
command (str): Optional command to execute first
187
"""
188
```
189
190
**Usage Examples:**
191
192
```python
193
from fabric.api import prompt, reboot, open_shell, env
194
195
# Get user input
196
env.branch = prompt('Deploy which branch?', default='master',
197
validate=r'^[a-zA-Z0-9_-]+$')
198
199
# Confirm dangerous operations
200
if prompt('Delete database? (yes/no)', default='no') == 'yes':
201
sudo('dropdb myapp')
202
203
# Reboot and wait for system to come back online
204
reboot(wait=180) # Wait 3 minutes
205
206
# Drop into interactive shell for debugging
207
open_shell()
208
209
# Open shell with initial command
210
open_shell('cd /var/log && tail -f nginx/error.log')
211
```
212
213
### Environment Validation
214
215
Verify that required environment variables and settings are configured before task execution.
216
217
```python { .api }
218
def require(*keys, **kwargs):
219
"""
220
Check for required environment variables.
221
222
Args:
223
*keys: Environment keys that must be set
224
**kwargs: Environment keys with required values
225
226
Raises:
227
SystemExit: If required variables are missing
228
"""
229
```
230
231
**Usage Examples:**
232
233
```python
234
from fabric.api import require, env, task
235
236
@task
237
def deploy():
238
# Ensure required settings are configured
239
require('hosts', 'user', 'key_filename')
240
241
# Require specific values
242
require(warn_only=False, parallel=True)
243
244
# Continue with deployment
245
run('git pull')
246
247
# Set required environment
248
env.hosts = ['server1.example.com', 'server2.example.com']
249
env.user = 'deploy'
250
env.key_filename = '/path/to/deploy_key'
251
```
252
253
## Error Handling and Return Values
254
255
All core operations return `_AttributeString` objects that provide rich metadata about command execution:
256
257
```python
258
result = run('ls /nonexistent')
259
260
# Check execution status
261
if result.failed:
262
print(f"Command failed with exit code: {result.return_code}")
263
print(f"Error output: {result.stderr}")
264
265
if result.succeeded:
266
print("Command completed successfully")
267
268
# Access command information
269
print(f"Original command: {result.command}")
270
print(f"Actual executed command: {result.real_command}")
271
272
# Use as regular string
273
for line in result.splitlines():
274
print(f"Output line: {line}")
275
```
276
277
## Output Control
278
279
Control what gets displayed during command execution:
280
281
```python
282
from fabric.api import run, hide, show, settings
283
284
# Hide all output
285
with hide('everything'):
286
result = run('long-running-command')
287
288
# Show only specific output types
289
with show('stdout'):
290
run('echo "This will be shown"')
291
292
# Combine with other settings
293
with settings(hide('stderr'), warn_only=True):
294
run('command-that-might-fail')
295
```