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()
相关推荐
FishCoderh14 分钟前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅16 分钟前
Python函数入门详解(定义+调用+参数)
python
曲幽1 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时5 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿7 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python