简体   繁体   English

Paramiko只连接到IP地址而不是Python中的主机名?

[英]Paramiko only connects to IP address not hostname in Python?

I have function like this in python: 我在python中有这样的功能:

def test_ssh(host, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=username, password=password)

Problem is: test_ssh('127.0.0.1', 'root', 'hello') works 问题是: test_ssh('127.0.0.1', 'root', 'hello')有效

But test_ssh('localhost', 'root', 'hello') doesn't work 但是test_ssh('localhost', 'root', 'hello')不起作用

Error I get is: 我得到的错误是:

ssh: Could not resolve hostname localhost: Name or service not known

What's causing this? 是什么导致了这个? Thanks 谢谢

尝试给ssh.connect(hostname=host, username=username, password=password)

Since my comments werent making much sense (putting them all together) (assuming your OS is Linux) - 由于我的评论没有多大意义(将它们放在一起)(假设您的操作系统是Linux) -

Reason for your error - 你错误的原因 -

ssh: Could not resolve hostname localhost: Name or service not known ssh:无法解析主机名localhost:名称或服务未知

Is - DNS resolution of HOSTNAME is not providing proper IP (comment#1) 是 - HOSTNAME的DNS解析没有提供适当的IP(注释#1)

Test with this command (terminal)- 使用此命令测试(终端) -

host localhost 主机 localhost

What you can try - 你能尝试什么 -

Edit /etc/hosts file, put in the IP and Hostname in this file. 编辑/ etc / hosts文件,在此文件中输入IP和主机名。 That ought to resolve your Hostname and IP Like This - 那应该解决你的主机名和IP这样 -

#IP hostname [[alias1] [...]] #IP hostname [[alias1] [...]]
127.0.0.1 localhost 127.0.0.1 localhost
172.22.0.9 mymachine.home mymachine 172.22.0.9 mymachine.home mymachine

Lastly an awesome link - http://bit.ly/IHhA1R 最后一个很棒的链接 - http://bit.ly/IHhA1R

EDIT 编辑

Possible workflow - 工作流程 -

  • User Registers, enters HOSTNAME 用户注册,进入HOSTNAME
  • We run command (with python we can use os.subprocess or os.popen) - 我们运行命令(使用python我们可以使用os.subprocess或os.popen) -

bash$ dig HOSTNAME bash $挖掘HOSTNAME

  • Fetch the IP of the HOSTNAME 获取HOSTNAME的IP
  • Try Connection to HOST with IP instead of the HOSTNAME 尝试使用IP而不是HOSTNAME连接到HOST

Always use the same workflow to get Latest IP of the HOSTNAME provided by the user, connect using IP instead of HOSTNAME 始终使用相同的工作流程来获取用户提供的HOSTNAME的最新IP,使用IP而不是HOSTNAME进行连接

Actually this can even not work when host can be resolved. 实际上,当主机可以解决时,这甚至不起作用。

First try: 第一次尝试:

import socket
socket.getaddrinfo('google.com', None)
socket.getaddrinfo('localhost', None)

If google.com returns tuple with address and localhost also returns correctly - then your system setup is correct. 如果google.com返回带有地址的元组并且localhost也正确返回 - 那么您的系统设置是正确的。 I do not know why but I had this issue and passing socket.getaddrinfo(host, None)[0][1][4] worked. 我不知道为什么,但我有这个问题,并传递socket.getaddrinfo(host, None)[0][1][4]工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM