python 登录 ssh 并输入多行命令简单示例

import paramiko
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.5', username='root', password='toor')
channel = ssh.invoke_shell()
channel.settimeout(9000)

# 发送
channel.send("ls".encode())

# 接收
while not channel.recv_ready():
    time.sleep(0.1)
result = channel.recv(1024000).decode()
time.sleep(0.1)
while channel.recv_ready():
    result += channel.recv(1024000).decode()
    time.sleep(0.1)
print(result)

# 后面可重复发送和接收的操作

# 最后关闭ssh连接
ssh.close()

posted @ 2024-10-28 18:06  mariocanfly  阅读(45)  评论(0编辑  收藏  举报