0
請幫我改正我的腳本。我的腳本檢查主機的ssh登錄並根據結果顯示成功/失敗。當我給出錯誤的主機名時它失敗。python3.5 paramiko因主機名失敗
代碼是以下:
[[email protected] 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()
它正常工作時,正確的用戶名/密碼給出:
[[email protected] 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
時,給出了錯誤的密碼,它工作正常。我已經在腳本中將密碼更改爲錯誤密碼,並表示連接失敗。
[email protected] script]# python3 param.py
Checking hostname :test2
Connection Failed
現在我的問題是,當我將主機名更改爲doenot存在時,paramiko失敗並彈出大量錯誤。
[[email protected] 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.0