Dùng paramiko.SSHClient kết nối một lần, gọi exec_command() nhiều lần cho các lệnh khác nhau.
Ví dụ
from paramiko import SSHClient
with SSHClient() as ssh:
ssh.load_system_host_keys()
ssh.connect('user@server', key_filename='~/.ssh/id_rsa')
commands = ['ls -la', 'df -h', 'uptime', 'whoami']
for cmd in commands:
stdin, stdout, stderr = ssh.exec_command(cmd)
print(f'=== {cmd} ===')
for line in stdout:
print(line.rstrip())
err = stderr.read().decode()
if err:
print(f'STDERR: {err}')
Lưu ý
- Mỗi
exec_commandmở channel mới, thực thi độc lập. - Để chạy lệnh tương tác (interactive shell), dùng
invoke_shell(). - Đóng kết nối sau khi xong (context manager tự lo).