Python实现登录到远程主机,然后在远程主机上继续连接远程主机

实现功能

登录到远程主机,然后在远程主机上继续连接远程主机,执行命令。

python 复制代码
import paramiko  
import time

  
# 第二个远程主机的连接信息(在第一个远程主机上执行SSH连接时使用)  
second_remote_host = '192.168.xx.xxx'  


  
# 创建SSH客户端并连接到第一个远程主机  
ssh = paramiko.SSHClient()  
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动添加主机名和主机密钥到本地HostKeys对象,并保存  
ssh.connect('xx.xx.xx.xx', username='root', password='xxx')  
  
# 在第一个远程主机上执行SSH命令以连接到第二个远程主机  
# 注意:这里我们假设你已经在第一个远程主机上设置了SSH密钥认证到第二个远程主机  
# 或者你可以在命令中指定密码(但这通常不是安全的做法)  
command = f"/opt/sshpass/bin/sshpass -p 密码 ssh 用户名@{second_remote_host} 'ls '"  
stdin, stdout, stderr = ssh.exec_command(command)  

time.sleep(1)
  
# 读取命令输出  
output = stdout.read().decode()  
error = stderr.read().decode()  
  
if error:  
    print(f"Error connecting to {second_remote_host}: {error}")  
else:  
    print(f"Output from {second_remote_host}:\n{output}")  
  
# 关闭连接  
ssh.close()
相关推荐
databook21 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤2 天前
小白必看:QMT里的miniQMT入门教程
后端·python