python3.5 paramiko失败了主机名

时间:2017-08-24 19:42:38

标签: ssh dns python-3.5 paramiko

请帮我纠正我的剧本。我的脚本检查主机的ssh登录,并根据结果显示成功/失败。当我给出错误的主机名时,它会失败。

代码如下:

[root@test1 script]# cat param.py
import multiprocessing
import paramiko
import random
import threading
import time

host_name = "test2"
print ("Checking hostname :"+str(host_name))
file = open('output_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
        ssh.connect(host_name, username='root', password='test')
        print ("success")
        file.write("success:"+str(host_name+"\n"))
except paramiko.SSHException:
        print ("Connection Failed")
        file.write("failed:"+str(host_name+"\n"))
        quit()
stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
for line in stdout.readlines():
        print (line.strip())
ssh.close()

当给出正确的用户名/密码时,它可以正常工作:

[root@test1 script]# python3 param.py
Checking hostname :test2
success
test2
12:31:49 up 83 days,  2:56,  2 users,  load average: 0.00, 0.01, 0.05

当给出错误的密码时,它可以正常工作。我在脚本中将密码更改为错误的密码,并表示连接按预期失败。

root@test1 script]# python3 param.py
Checking hostname :test2
Connection Failed

现在我的问题是,当我将主机名更改为doenot存在的东西时,paramiko会失败并且会弹出很多错误。

[root@test1 script]# python3 param.py
Checking hostname :invalidtest2
Traceback (most recent call last):
  File "param.py", line 16, in <module>
    ssh.connect(host_name, username='root', password='test')
  File "/root/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 301, in connect
    to_try = list(self._families_and_addresses(hostname, port))
  File "/root/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 199, in _families_and_addresses
    hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  File "/root/usr/local/lib/python3.5/socket.py", line 728, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

如何收到连接失败的消息?我使用的是python3.5

1 个答案:

答案 0 :(得分:0)

将密码保存在脚本本身并不是一个好主意。修改了脚本,以便从文件中获取主机名并将输出写入不同的文件

#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
start_time1 = time.time()
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)
          #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()
        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:")


    for i in hostname1:
        q.put(i)
    #print ("all the hostname : "+str(list(q.queue)))
    for no_of_threads in range(3):
        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")