[Ubuntu] paramiko module to implement python SSH client: interactive and non-interactive

[Ubuntu] paramiko module to implement python SSH client: interactive and non-interactive

Table of contents

1 The difference between exec_command and invoke_shell

2 Use of exec_command and invoke_shell

(1)exec_command

(2)invoke_shell

1 The difference between exec_command and invoke_shell

Use the paramiko module in python to implement the python SSH client. When interacting with the SSH server, you need to pay attention to the difference between interactive and non-interactive .

Only execute a single command and then disconnect the link. You can use non-interactive mode. To execute multiple commands, or to determine the subsequent command to be executed based on the previous output results, you need to use interactive mode.

Execution in exec_command mode does not have the ability to persist, that is, each run is a new environment, which can be understood as just sending the command as a parameter. invoke_shell is executed using SSH shell channel and has persistence capabilities.

2 Use of exec_command and invoke_shell

(1)exec_command

import paramiko

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh_client.connect(host, port, username, password, timeout=10)
stdin, stdout, stderr = ssh_client.exec_command("cd /home/test/; python3 test.py")  
print(stdout_.read().decode('utf-8'))
ssh_client.close()

pass

(2)invoke_shell

import paramiko

import time

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh_client.connect(host, port, username, password, timeout=10)

run_channel = ssh_client.invoke_shell()
run_channel.send('cd /home/test/ \n')
run_channel.send('python3 test.py \n')

while not run_channel.recv_ready():
    time.sleep(1)

output = ''
while run_channel.recv_ready():
    output += run_channel.recv(1024).decode()
print(output)

ssh_client.close()

pass

Guess you like

Origin blog.csdn.net/wss794/article/details/130728131
Recommended