【Ubuntu】paramiko模块来实现python SSH客户端:交互式和非交互式
目录
1 exec_command和invoke_shell的区别
2 exec_command和invoke_shell的使用
1 exec_command和invoke_shell的区别
使用python中的paramiko模块来实现python SSH客户端,与SSH服务器交互时,需要注意有交互式和非交互式的区别。
只执行单条命令,之后就断开链接,可以使用非交互方式。执行多条命令,或者基于前面的输出结果来判断后续要执行的命令,需要使用交互式方式。
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