How to execute multiple commands with Paramiko?
To execute multiple commands in Paramiko, you can use the exec_command() method of SSHClient. Here is an example code:
import paramiko
# 创建SSH客户端
client = paramiko.SSHClient()
# 添加远程主机的SSH密钥
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接到远程主机
client.connect(hostname='hostname', username='username', password='password')
# 执行多个命令
commands = ['command1', 'command2', 'command3']
for command in commands:
stdin, stdout, stderr = client.exec_command(command)
# 打印命令的输出
print(stdout.read().decode())
# 关闭SSH连接
client.close()
In the code above, an SSH client is created and connected to a remote host using the connect() method. Multiple commands are then executed in sequence using the exec_command() method, and the output of each command is printed using stdout.read().decode(). Finally, the SSH connection is closed using the close() method.