paramiko - 登录主机不需要密码[重复]

问题描述 投票:0回答:1

如果 ssh 服务器不需要密码,我如何登录 ssh 服务器。

在(此处)powershell 上,以下工作正常:

ssh root@myMachine
root@myMachine$: 

无需密码,只需简单的登录和机器的问候。

我的Python代码如下所示:

import paramiko
client = paramiko.SSHClient()
print("connecting...")
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname="xxx.xxx.xxx.xxx", port=XX)

# Error:
# >       raise SSHException("No authentication methods available")
# E       paramiko.ssh_exception.SSHException: No authentication methods available

该错误是由

paramiko/client.py
中的案例选择引起的,它根本不存在未提供密码的情况,并且它的工作方式与此类似。如果我提供密码,身份验证就会失败。

我怎样才能告诉paramiko只登录而不需要密码?

好吧...想出了一些办法...你可以乘坐交通工具去。

t = paramiko.Transport(("localhost", 2022))
t.connect()
t.auth_none("root")
x = t.open_session()
noting_returned = x.exec_command("touch /tmp/huhu.txt")

然而,通道在每个命令后关闭,我看不到如何检索标准输出/错误/返回值等的方法。

  • 我可以使用现有传输作为 SSHClient 的源吗?
  • 这是预期的方法吗?
python ssh paramiko
1个回答
0
投票

以下解决方案是由 @Martin Prikryl 和链接知识的创建者提供的两个来源的总结。

我怎样才能告诉paramiko只登录而不需要密码?

底层的东西不会返回标准输出,只有上层函数在执行一些io之后才会返回。

import paramiko

    host = "localhost"
    port = 2022
    username = "root"
    password = None

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # Workaround for no authentication:
    # https://github.com/paramiko/paramiko/issues/890#issuecomment-906893725
    try:
        client.connect(host, port=port, username=username, password=password)
    # except paramiko.ssh_exception.AuthenticationException as e:
    except paramiko.ssh_exception.SSHException as e:
        if not password:
            client.get_transport().auth_none(username)
        else:
            raise e

    # Now we can interact with the client as usual
    stdin, stdout, stderr = client.exec_command("ls /")
    lines = stdout.readlines()
    print(lines)
© www.soinside.com 2019 - 2024. All rights reserved.