欢迎访问宙启技术站
智能推送

使用pexpect.pxssh模块在Python中实现SSH跳板机自动登录和执行命令

发布时间:2023-12-26 06:54:49

在Python中,可以使用pexpect.pxssh模块来实现SSH跳板机的自动登录和执行命令。pexpect.pxssh是pexpect模块的一个子模块,专门用于处理SSH连接。

首先,我们需要安装pexpect模块。可以使用以下命令安装:

pip install pexpect

下面是一个使用pexpect.pxssh模块实现SSH跳板机自动登录和执行命令的例子:

import pexpect

# 定义跳板机的相关信息
bastion_host = 'bastion.example.com'  # 跳板机的IP地址或域名
bastion_port = 22  # 跳板机的SSH端口
bastion_user = 'admin'  # 跳板机的用户名
bastion_password = 'password'  # 跳板机的密码

# 定义目标主机的相关信息
target_host = 'target.example.com'  # 目标主机的IP地址或域名
target_port = 22  # 目标主机的SSH端口
target_user = 'admin'  # 目标主机的用户名
target_password = 'password'  # 目标主机的密码

# 创建跳板机连接
bastion_ssh = pexpect.pxssh.pxssh()
bastion_ssh.login(bastion_host, bastion_user, password=bastion_password)

# 创建目标主机连接
target_ssh = pexpect.pxssh.pxssh()
target_ssh.login(target_host, target_user, password=target_password, ssh_key=bastion_ssh)

# 在目标主机上执行命令
target_ssh.sendline('ls -l')
target_ssh.prompt()
output = target_ssh.before.decode('utf-8')

# 输出命令结果
print(output)

# 关闭连接
target_ssh.logout()
bastion_ssh.logout()

在上述例子中,我们首先创建了一个跳板机连接,使用bastion_ssh.login方法登录跳板机。然后,我们创建了目标主机的连接,使用target_ssh.login方法登录目标主机,并通过传递跳板机连接对象给ssh_key参数来建立跳板机隧道。随后,我们可以使用target_ssh.sendline方法发送要执行的命令,并使用target_ssh.prompt方法等待命令执行完成。最后,我们通过target_ssh.before属性来获取命令的输出结果,并对其进行解码和输出。

需要注意的是,为了确保密码的安全性,我们可以从命令行参数、配置文件或其他安全方式中获取密码,而不是直接在代码中硬编码密码。

总结来说,使用pexpect.pxssh模块可以很方便地实现SSH跳板机的自动登录和执行命令。通过定义跳板机和目标主机的相关信息,创建相应的连接对象,我们可以轻松地管理SSH连接并执行命令。