Running sudo Commands with Paramiko and Timeouts
Run sudo commands over SSH with Paramiko by requesting a PTY, sending the password at the prompt, and using timeouts to avoid hangs.

Running sudo commands through Paramiko may fail or hang because the SSH channel is not an interactive terminal by default. Paramiko's exec_command opens a channel without a pseudo-TTY, and many sudo configurations expect a terminal for password entry or require one through requiretty. The practical pattern is to request a PTY when needed, send the password after sudo prompts for it, and set explicit timeouts so the script cannot block forever. This article covers the common patterns and explains the tradeoffs between exec_command and invoke_shell.
Why sudo May Need a PTY in Paramiko
When you call exec_command on an SSH client, Paramiko runs the remote command through a non-interactive channel by default. sudo normally reads a password from the controlling terminal unless you pass -S, which tells sudo to read it from standard input. Even with -S, a sudoers setting such as requiretty can prevent sudo from running without a TTY. Without a PTY, sudo may therefore exit with sudo: no tty present and no askpass program specified, or it may wait for input that never arrives.
Requesting a PTY is straightforward:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('host', username='user', password='password')
stdin, stdout, stderr = client.exec_command('sudo -S whoami', get_pty=True)
# The command will wait for a password unless you send it; see the next section.The get_pty=True parameter allocates a pseudo-terminal for the channel. That can satisfy sudo policies that require a TTY and makes sudo behave as it would in an interactive session. -S tells sudo to read the password from standard input, so your script can write it through stdin.
Handling the sudo Password Prompt
Once the PTY is allocated, you must send the password when sudo asks for it. With sudo -S, the prompt is written to stderr on most systems. A common pattern is to read until the prompt appears, then send the password followed by a newline.
import paramiko
import socket
def run_sudo_command(client, command, password):
stdin, stdout, stderr = client.exec_command(f'sudo -S {command}', get_pty=True)
stdout.channel.settimeout(10)
prompt = b''
try:
while b'[sudo] password' not in prompt and b'Password' not in prompt:
chunk = stderr.read(1)
if not chunk:
break
prompt += chunk
except socket.timeout:
raise TimeoutError('sudo password prompt was not received')
stdin.write(password + '\n')
stdin.flush()
output = stdout.read() + stderr.read()
return output.decode()This reads one byte at a time until the prompt appears. The channel timeout prevents an infinite loop if the prompt never arrives. After sending the password, read the rest of the output from stdout and stderr.
Setting a Timeout on the Channel
Paramiko's Channel object has a settimeout method that sets a socket timeout for read operations. This is a simple way to prevent a hang while waiting for output. The timeout applies to each recv or read call, not to the overall command execution.
import socket
import paramiko
client = paramiko.SSHClient()
client.connect('host', username='user', password='password')
stdin, stdout, stderr = client.exec_command('sudo -S whoami', get_pty=True)
stdout.channel.settimeout(10) # seconds
output = b''
try:
while True:
chunk = stdout.read(1)
if not chunk:
break
output += chunk
except socket.timeout:
# No data arrived within the timeout window.
passHere stdout.channel is the underlying channel. If no data arrives within the timeout, read raises socket.timeout on current Paramiko versions; older versions or different wrappers may surface SSHException instead, so catch the exception that matches your environment.
Using invoke_shell for Interactive Sessions
When you need to run multiple sudo commands or interact with the remote shell, invoke_shell is a better fit. It creates an interactive shell session and requests a PTY by default. You can send commands and read output continuously, which is useful when you must react to prompts dynamically.
import paramiko
import socket
client = paramiko.SSHClient()
client.connect('host', username='user', password='password')
shell = client.invoke_shell()
shell.settimeout(10)
# Wait for the shell prompt.
output = b''
try:
while b'$' not in output and b'#' not in output:
chunk = shell.recv(4096)
if not chunk:
break
output += chunk
except socket.timeout:
raise TimeoutError('Shell prompt was not received')
# Send a sudo command and wait for the password prompt.
shell.send('sudo -S whoami\n')
output = b''
try:
while b'[sudo] password' not in output:
chunk = shell.recv(4096)
if not chunk:
break
output += chunk
except socket.timeout:
raise TimeoutError('sudo password prompt was not received')
shell.send(password + '\n')
# Keep reading until the shell prompt returns or a timeout occurs.
output = b''
try:
while b'$' not in output and b'#' not in output:
chunk = shell.recv(4096)
if not chunk:
break
output += chunk
except socket.timeout:
pass
print(output.decode())With invoke_shell, you have full control over the session. The settimeout method works the same way, but you must read continuously to avoid filling the channel buffer. Prompt detection like the $ / # check shown here is illustrative; in a real script, match the actual prompt on the target host.
Enforcing an Overall Command Timeout
A common problem is a sudo command itself runs longer than expected. The channel timeout only affects reads, not the command execution time. To limit total runtime, check elapsed wall-clock time in a read loop.
import socket
import time
import paramiko
def run_with_timeout(client, command, password, timeout=30):
stdin, stdout, stderr = client.exec_command(f'sudo -S {command}', get_pty=True)
stdout.channel.settimeout(1) # short timeout for a responsive loop
start = time.time()
output = b''
while time.time() - start < timeout:
try:
chunk = stdout.read(1)
if not chunk:
break
output += chunk
except socket.timeout:
continue
except paramiko.ssh_exception.SSHException:
continue
else:
raise TimeoutError(f'Command exceeded {timeout} seconds')
return output.decode()This loop reads with a 1-second channel timeout and checks the elapsed time. If the command does not finish before the limit, the while condition becomes false and TimeoutError is raised. If the command completes before that, the loop breaks and returns the accumulated output.
Security Considerations for Password Handling
Password-based sudo automation is less secure than key-based access. For production scripts, prefer SSH keys and configure sudo with NOPASSWD for the exact commands the script needs. If you must use a password, do not hardcode it in the script; load it from an environment variable or a secret manager. Sending the password to sudo -S over stdin keeps it out of the remote command line, but it is still present in memory on both sides of the connection and must be treated as a secret.
Use get_pty=True when the remote sudoers policy requires a TTY or when the command needs interactive sudo behavior. If requiretty is disabled, sudo -S can run without a PTY, but you still need careful prompt and timeout handling.
Choosing Between exec_command and invoke_shell for sudo
The choice depends on the complexity of the remote interaction. exec_command is simpler and more predictable for a single command, but it requires careful handling of the password prompt. invoke_shell is more flexible for interactive sessions, but you must manage the shell prompt and output parsing yourself.
| Criterion | exec_command | invoke_shell |
|---|---|---|
| PTY allocation | Requires get_pty=True if needed | Allocated by default |
| Password prompt | Must read and respond manually | Same, but easier to detect |
| Multiple commands | One command per call | Can send multiple commands |
| Output handling | Separate stdout/stderr streams | Combined output stream |
| Timeout control | Channel timeout per read | Same, but more manual |
| Best for | Simple, scripted sudo commands | Interactive sessions or complex flows |
For most automation tasks, exec_command with get_pty=True and a proper timeout loop is sufficient. If you need to run a sequence of sudo commands and react to prompts, invoke_shell gives you more control, but it also requires more careful state management. In both cases, always set a timeout on the channel to prevent your script from hanging indefinitely when the remote host becomes unresponsive.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.