gpt4 book ai didi

Python ssh2 与 linux 的连接

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:17 27 4
gpt4 key购买 nike

我正在尝试使用 ssh2 和 Python 从我的笔记本电脑(本地)到我的专用机器执行一些命令。当我尝试使用 ls 命令显示所有文件时,我总是收到此消息。

>     Linux v2 5.2.13-gs-md #5213 SMP Sun Sep 8 01:47:29 CEST 2019 x86_64
>
> The programs included with the Debian GNU/Linux system are free software;
> the exact distribution terms for each program are described in the
> individual files in /usr/share/doc/*/copyright.
>
> Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
> permitted by applicable law.

这是我的代码。

import socket, time
from ssh2.session import Session

host = '11.22.33.44.55'
user = 'root'
password = 'itssecret'

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 2244))

session = Session()
session.handshake(sock)
session.userauth_password(user, password)

channel = session.open_session()
channel.shell()

channel.write("cd /")
channel.write("ls")
time.sleep(1)


size, data = channel.read()
print(data.decode())

channel.close()

即使我只尝试 cd/ 我也有相同的输出。

最佳答案

channel.write("cd /")
channel.write("ls")

这只是将 cd/ls 写入 session 。如果您登录到一个 SSH session 并按下 cd/ls 很可能在您按下 enter 之前什么都不会发生,然后您就不会执行您想要的两个命令。

您可以发送换行符,但更好的是使用库的内置系统发送命令,并验证命令是否完成,以及连接本身是否干净地关闭:

channel.execute('cd /')
channel.execute('ls')
channel.wait_eof()
channel.close()
channel.wait_closed()

关于Python ssh2 与 linux 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142598/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com