python - 无法使用 paramiko 模块 ssh 到远程服务器

标签 python linux ssh paramiko

我正在尝试使用 python paramiko 模块通过 ssh 连接到远程服务器。我需要动态包含 key 文件。我的代码如下。

import getpass
import paramiko

server = raw_input("What is the server name? ")
username = raw_input("Enter the username: ")
passphrase = getpass.getpass(prompt="Enter your passphrase: ")
key = '/home/%s/.ssh/id_rsa' % username

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, username=username, password=passphrase, key_filename=key)
stdin, stdout, stderr = ssh.exec_command('df -h')
print stdout.readlines()
ssh.close()

如果我直接提供关键路径而不是使用变量,我就可以使用代码。

我得到的错误是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 237, in connect
    for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known`enter code here`

最佳答案

好像你这里有一些 dns 错误,在这里粘贴我的脚本以获取 ssh 状态,这正在处理所有异常(至少我到目前为止已经注意到)

#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
locke1 = threading.Lock()
q = Queue()

#Check the login
def check_hostname(host_name, pw_r):
    with locke1:
        print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
        file_output = open('output_file','a')
        file_success = open('success_file','a')
        file_failed = open('failed_file','a')
        file_error = open('error_file','a')
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
          ssh.connect(host_name, username='root', password=pw_r, timeout=5)
          #print ("Success")
          file_success.write(str(host_name+"\n"))
          file_success.close()
          file_output.write("success: "+str(host_name+"\n"))
          file_output.close()

          # printing output if required from remote machine
          #stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
          #for line in stdout.readlines():
           # print (line.strip())

        except paramiko.SSHException:
                # print ("error")
                file_failed.write(str(host_name+"\n"))
                file_failed.close()
                file_output.write("failed: "+str(host_name+"\n"))
                file_output.close()
                #quit()
        except paramiko.ssh_exception.NoValidConnectionsError:
                #print ("might be windows------------")
                file_output.write("failed: " + str(host_name + "\n"))
                file_output.close()
                file_failed.write(str(host_name+"\n"))
                file_failed.close()
                #quit()
        except socket.gaierror:
          #print ("wrong hostname/dns************")
          file_output.write("error: "+str(host_name+"\n"))
          file_output.close()
          file_error.write(str(host_name + "\n"))
          file_error.close()

        except socket.timeout:
           #print ("No Ping %%%%%%%%%%%%")
           file_output.write("error: "+str(host_name+"\n"))
           file_output.close()
           file_error.write(str(host_name + "\n"))
           file_error.close()

        ssh.close()


def performer1():
    while True:
        hostname_value = q.get()
        check_hostname(hostname_value,pw_sent)
        q.task_done()

if __name__ == '__main__':

    print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")

    f = open('output_file', 'w')
    f.write("-------Output of all hosts-------\n")
    f.close()
    f = open('success_file', 'w')
    f.write("-------Success hosts-------\n")
    f.close()
    f = open('failed_file', 'w')
    f.write("-------Failed hosts-------\n")
    f.close()
    f = open('error_file', 'w')
    f.write("-------Hosts with error-------\n")
    f.close()

    with open("input_file") as f:
        hostname1 = f.read().splitlines()

#Read the standard password from the user
    pw_sent=getpass.getpass("Enter the Password:")
    start_time1 = time.time()

    for i in hostname1:
        q.put(i)
    #print ("all the hostname : "+str(list(q.queue)))
    for no_of_threads in range(10):
        t = threading.Thread(target=performer1)
        t.daemon=True
        t.start()

    q.join()
    print ("Check output files for results")
    print ("completed task in" + str(time.time()-start_time1) + "seconds")

关于python - 无法使用 paramiko 模块 ssh 到远程服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31490998/

相关文章:

shell - 如何设置ssh超时时间?

visual-studio-code - VS Code SSH Remote 上的“localhost”可在本地计算机上访问

python - 关于在 Android 应用程序中使用带有 kivy 的 python 套接字

Python numexpr 模块未找到

linux - 在linux中将三行转换为一行

php - 如何在mac/usr/bin/nohup上执行

bash - 带有/空格+ ssh的变量

python - 如何使用 beautifulsoup4 选择除某个 html 元素之外的所有内容?

python - 从 Ruby/Python 调用 C++ 类函数

python - ./stack.sh 安装 Openstack 失败