【Ubuntu】paramiko模块来实现python SSH客户端:交互式和非交互式

【Ubuntu】paramiko模块来实现python SSH客户端:交互式和非交互式

目录

1 exec_command和invoke_shell的区别

2 exec_command和invoke_shell的使用

(1)exec_command

(2)invoke_shell

1 exec_command和invoke_shell的区别

使用python中的paramiko模块来实现python SSH客户端,与SSH服务器交互时,需要注意有交互式非交互式的区别。

只执行单条命令,之后就断开链接,可以使用非交互方式。执行多条命令,或者基于前面的输出结果来判断后续要执行的命令,需要使用交互式方式。

扫描二维码关注公众号,回复: 16977113 查看本文章

exec_command方式执行,不具备持久化的能力,也就是每次运行都是一次全新的环境,可以理解为把命令当作参数发送出去而已。invoke_shell使用的是SSH shell channel的方式执行,具备持久化能力。

2 exec_command和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

猜你喜欢

转载自blog.csdn.net/wss794/article/details/130728131