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()
相关推荐
金銀銅鐵10 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1115 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0017 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵19 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf19 小时前
Agent 流程编排
后端·python·agent
copyer_xyf20 小时前
Agent RAG
后端·python·agent
copyer_xyf20 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf20 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python