我试图使我的python模块通过ssh从本地计算机(也通过ssh连接)连接到远程计算机并在其上执行命令。
对于此问题,我使用paramiko软件包,并编写了以下代码:
class SshClient:
def __init__(self, host, port, username, password):
self._host = host
self._port = port
self._username = username
self._password = password
self._client = paramiko.SSHClient()
#self._shell = None
self._transport = None
self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self._to_transport = None
self._opened = False
def open(self):
self._client.connect(self._host, port=self._port, username=self._username, password=self._password)
self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
logger.debug('SSH connection to {}:{} is open'.format(self._host, self._port))
self._opened = True
....
....
def exec_nested_cmd(self, cmd, nested_addr, port, username, password):
"""
Connecting to nested host from original host via ssh.
:param host: nested host address
:param port: nested host ssh port
:param username: nested host username
:param password: nested host password
:return:
"""
if not self._opened:
self.open()
self._transport = self._client.get_transport()
host_tup = (self._host, self._port)
nested_tup = (nested_addr, port,username, password)
nested_channel = self._client.get_transport().open_channel("direct-tcpip", nested_tup, host_tup)
transport = paramiko.Transport(nested_channel)
transport.start_client()
transport.auth_password(username, password)
channel = transport.open_session(timeout=10)
channel.exec_command(cmd)
retcode = channel.recv_exit_status()
buf = ""
while channel.recv_ready():
print(channel.recv(1024))
....
....
然后执行以下行的最后一个过程:
self.ssh = SshClient("10.10.10.200", "2022", "user1", "pass1")
self.ssh.exec_nested_cmd("ls", 10.10.10.201, 22, "user2" , "pass2")
从实际意义上讲,该程序将连接到第一个ssh客户端,并且应该通过ssh在另一个端口中创建从第一个客户端到第二个ssh客户端的会话,然后检索所有命令并将其发送到第二个客户。
运行此命令后,我在缓冲区(正在打印)中得到以下响应:
b“ ========================== \ n如何安装公钥 客户端:\ n1。通过SSH使用密码\ n2登录到客户端。运行命令的ssh键 安装nms'\ n3。插入〜/ .ssh / id_rsa.pub的内容,然后 按Enter \ n ========================== \ n“
这可能是由于我连接到客户端而不提供任何不正确的身份验证凭据(然后它正在搜索公用密钥)引起的。
如何解决此问题?如果我将auth_interactive()
与处理程序一起使用,而不是auth_password()
与处理程序一起使用,这会对程序运行产生什么影响?