首页 > 解决方案 > 当不使用 Channel.exec_command() 时,我可以在不事先调用 Channel.get_pty() 的情况下调用 Channel.invoke_shell()

问题描述

我已经多次阅读 Paramiko 文档。我仍然无法找到我遇到的问题的答案:

为什么不提前打电话就不能channel.invoke_shell()打电话?channel.get_pty()– 这是我对文档的理解——channel.get_pty()如果我想使用channel.exec_command(). 但是,如果我想使用带有channel.send()or的交互式 shell 怎么办channel.recv()?它是强制性的吗?

这是我的尝试:

client = paramiko.SSHClient()

# Set SSH key parameters to auto accept unknown hosts
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the host
client.connect(hostname=hostname, username=username, password=password)
channel = client.get_transport().open_session()
channel.invoke_shell() # ---> Channel closed Exception here
channel.send(cmd + "\r")

有了这个我得到paramiko.ssh_exception.SSHException: Channel closed。如果我在它工作channel.get_pty()之前打电话。invoke_shell()我只想使用交互式外壳而不是终端语义。可能吗?

链接日志:

plink.exe -T -v user@host -pw password interactive-tool.exe
Looking up host "host" for SSH connection
Connecting to host port 22
We claim version: SSH-2.0-PuTTY_Release_0.72
Remote version: SSH-2.0-OpenSSH_for_Windows_7.7
Using SSH protocol version 2
No GSSAPI security context available
Doing ECDH key exchange with curve Curve25519 and hash SHA-256 (unaccelerated)
Server also has ecdsa-sha2-nistp256/ssh-rsa host keys, but we don't know any of them
Host key fingerprint is:
ssh-ed25519 255 xx:xx:xx:xx
Initialised AES-256 SDCTR (AES-NI accelerated) outbound encryption
Initialised HMAC-SHA-256 (unaccelerated) outbound MAC algorithm
Initialised AES-256 SDCTR (AES-NI accelerated) inbound encryption
Initialised HMAC-SHA-256 (unaccelerated) inbound MAC algorithm
Attempting keyboard-interactive authentication
Using username "user".
Server refused keyboard-interactive authentication
Sent password
Access granted
Access granted. Press Return to begin session.
Opening main session channel
Opened main channel
Started a shell/command

标签: pythonshellsshparamikowindows-server-2016

解决方案


你可以打电话Channel.invoke_shell()而不打电话Channel.get_pty()

如果它不起作用,那是您的服务器的限制,而不是 JSch 的限制。
你已经从你之前的问题中知道它是这样的。

在 Windows 10 Pro 1903 上使用我的 Win32-OpenSSH 7.7,我可以毫无问题地使用没有 TTY 的 shell 会话:

C:\>echo ipconfig | plink -T username@localhost -pw password
Using username "username".
Microsoft Windows [Version 10.0.18362.356]
(c) 2019 Microsoft Corporation. All rights reserved.

username@COMPUTERNAME C:\Users\username>ipconfig 

Windows IP Configuration


Ethernet adapter Ethernet 2:

...

推荐阅读