def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
python类AuthenticationException()的实例源码
def test_login_false_username_ssh(self, credentials):
"""Verify AuthenticationException in case Incorrect username for ssh object.
"""
ssh_conn = clissh.CLISSH(credentials[0])
with pytest.raises(paramiko.AuthenticationException):
ssh_conn = clissh.CLISSH(credentials[0])
ssh_conn.login(ssh_conn.randstr(30), credentials[2], timeout=5)
def test_login_false_username_telnet(self, credentials):
"""Verify AuthenticationException in case Incorrect username for telnet object.
"""
telnet_conn = clitelnet.TelnetCMD(credentials[0])
with pytest.raises(CLIException):
telnet_conn = clitelnet.TelnetCMD(credentials[0])
telnet_conn.login(telnet_conn.randstr(30), credentials[2], timeout=5)
def test_login_false_userpass_ssh(self, credentials):
"""Verify AuthenticationException in case Incorrect password for ssh object.
"""
ssh_conn = clissh.CLISSH(credentials[0])
with pytest.raises(paramiko.AuthenticationException):
ssh_conn = clissh.CLISSH(credentials[0])
ssh_conn.login(credentials[1], ssh_conn.randstr(30), timeout=5)
def test_login_false_userpass_telnet(self, credentials):
"""Verify AuthenticationException in case Incorrect password for telnet object.
"""
telnet_conn = clitelnet.TelnetCMD(credentials[0])
with pytest.raises(CLIException):
telnet_conn = clitelnet.TelnetCMD(credentials[0])
telnet_conn.login(credentials[1], telnet_conn.randstr(30), timeout=5)
# Negative tests for nns module isn't implemented, because nns module always in 'login' mode
def host_contactable(self, address):
try:
# TODO: Better way to check this?
result = self._ssh_address(
address,
"echo 'Checking if node is ready to receive commands.'",
expected_return_code=None
)
except socket.error:
logger.debug("Unknown socket error when checking %s" % address)
return False
except paramiko.AuthenticationException, e:
logger.debug("Auth error when checking %s: %s" % (address, e))
return False
except paramiko.SSHException, e:
logger.debug("General SSH error when checking %s: %s" % (address, e))
return False
except EOFError:
logger.debug("Connection unexpectedly killed while checking %s" % address)
return False
if not result.rc == 0:
# Wait, what? echo returned !0? How is that possible?
logger.debug("exit status %d from echo on %s: inconceivable!" % (result.rc, address))
return False
return True
def _try_ssh_cmd(self, agent_ssh, auth_args, cmd):
from chroma_core.services.job_scheduler.agent_rpc import AgentException
try:
return agent_ssh.ssh(cmd, auth_args = auth_args)
except (AuthenticationException, SSHException):
raise
except Exception, e:
# Re-raise wrapped in an AgentException
raise AgentException(agent_ssh.address,
"Unhandled exception: %s" % e,
", ".join(auth_args),
'\n'.join(traceback.format_exception(*(sys.exc_info()))))
def seek_for_pigrows_click(self, e):
print("seeking for pigrows...")
number_of_tries_per_host = 1
pi_link_pnl.target_ip = self.tb_ip.GetValue()
pi_link_pnl.target_user = self.tb_user.GetValue()
pi_link_pnl.target_pass = self.tb_pass.GetValue()
if pi_link_pnl.target_ip.split(".")[3] == '':
pi_link_pnl.target_ip = pi_link_pnl.target_ip + '0'
start_from = pi_link_pnl.target_ip.split(".")[3]
lastdigits = len(str(start_from))
hostrange = pi_link_pnl.target_ip[:-lastdigits]
#Iterate through the ip_to_test and stop when pigrow is found
for ip_to_test in range(int(start_from)+1,255):
host = hostrange + str(ip_to_test)
pi_link_pnl.target_ip = self.tb_ip.SetValue(host)
seek_attempt = 1
log_on_test = False
while True:
print("Trying to connect to " + host)
try:
ssh.connect(host, username=pi_link_pnl.target_user, password=pi_link_pnl.target_pass, timeout=3)
print("Connected to " + host)
log_on_test = True
box_name = self.get_box_name()
print("Pigrow Found; " + str(box_name))
self.set_link_pi_text(log_on_test, box_name)
return box_name #this just exits the loop
except paramiko.AuthenticationException:
print("Authentication failed when connecting to " + str(host))
except Exception as e:
print("Could not SSH to " + host + " because:" + str(e))
seek_attempt += 1
# check if final attempt and if so stop trying
if seek_attempt == number_of_tries_per_host + 1:
print("Could not connect to " + host + " Giving up")
break #end while loop and look at next host
def _connect(self,ip,port,user,sock=None):
sshClient = paramiko.SSHClient()
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
tries = 0
sshtry = state.sshtry
sshTimeOut = state.sshTimeOut
while True:
try:
tries += 1
sshClient.connect(ip,int(port),user,timeout=sshTimeOut,sock=sock,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"])
sshClient = sshClient
return sshClient
except paramiko.BadHostKeyException, e:
raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e)
except (
paramiko.AuthenticationException,
paramiko.PasswordRequiredException,
paramiko.SSHException
), e:
msg = str(e)
#if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner':
if e.__class__ is paramiko.SSHException and msg.startswith('Error reading SSH protocol banner'):
#print "WARNNING: reconnect ip:%s %s"%(self.ip,msg)
if tries < sshtry:
time.sleep(1)
continue
else:
raise Exception(e)
else:
raise Exception(e)
except Exception,e:
if str(e) == "timed out" and tries < sshtry:
#print "Warnning %s:%s,retries ..."%(ip,str(e))
time.sleep(1)
continue
raise e
def __init__(self,ip,port=22,user="astd"):
self.ip = ip
self.port = port
self.user = user
sshClient = paramiko.SSHClient()
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
tries = 0
sshtry = state.sshtry
while True:
try:
tries += 1
sshClient.connect(ip,port,user,timeout=5,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"])
self.sshClient = sshClient
self.transport = sshClient.get_transport()
break
except paramiko.BadHostKeyException, e:
raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e)
except (
paramiko.AuthenticationException,
paramiko.PasswordRequiredException,
paramiko.SSHException
), e:
msg = str(e)
if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner':
if tries < sshtry:
continue
else:
raise Exception(e)
else:
raise Exception(e)
except Exception,e:
raise Exception(e)
def connect(self):
sshClient = paramiko.SSHClient()
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
tries = 0
sshtry = state.sshtry
while True:
try:
tries += 1
sshClient.connect(self.ip,self.port,self.user,timeout=15,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"])
self.sshClient = sshClient
self.transport = sshClient.get_transport()
break
except paramiko.BadHostKeyException, e:
raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e)
except (
paramiko.AuthenticationException,
paramiko.PasswordRequiredException,
paramiko.SSHException
), e:
msg = str(e)
#if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner':
if e.__class__ is paramiko.SSHException and msg.startswith('Error reading SSH protocol banner'):
#print "WARNNING: ip:%s %s"%(self.ip,msg)
if tries < sshtry:
time.sleep(1)
continue
else:
raise Exception(e)
else:
raise Exception(e)
except Exception,e:
raise Exception(e)
def _connect_ssh(self):
"""Open a new SSH connection using Paramiko."""
try:
self.printer.verbose("[SSH] Connecting ({}:{})...".format(self._ip, self._port))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self._ip, port=self._port, username=self._username, password=self._password,
allow_agent=self._pub_key_auth, look_for_keys=self._pub_key_auth)
self.printer.notify("[SSH] Connected ({}:{})".format(self._ip, self._port))
return ssh
except paramiko.AuthenticationException as e:
raise Exception('Authentication failed when connecting to %s. %s: %s' % (self._ip, type(e).__name__, e.message))
except paramiko.SSHException as e:
raise Exception('Connection dropped. Please check your connection with the device, '
'and reload the module. %s: %s' % (type(e).__name__, e.message))
except Exception as e:
raise Exception('Could not open a connection to %s. %s - %s' % (self._ip, type(e).__name__, e.message))
def ssh_connect(username, password, stat = 0):
ssh = paramiko.SSHClient();
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, port=22, username=username, password=password)
except paramiko.AuthenticationException:
stat = 1
except socket.error, e:
stat = 2
ssh.close()
return stat
#Main Code
def test_set_credential(self):
self.conf["racadm"] = {}
self.conf["racadm"]["username"] = "admin"
self.conf["racadm"]["password"] = "fake"
# Start service
node = model.CNode(self.conf)
node.init()
node.precheck()
node.start()
# Check process
str_result = run_command(PS_RACADM, True,
subprocess.PIPE, subprocess.PIPE)[1]
assert "racadmsim test 0.0.0.0 10022 admin fake" in str_result
# Connect with wrong credential
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
self.ssh.connect('127.0.0.1',
username='admin',
password='admin',
port=10022)
except paramiko.AuthenticationException:
assert True
else:
assert False
# Connect with correct credential
self.ssh.connect('127.0.0.1',
username='admin',
password='fake',
port=10022)
self.channel = self.ssh.invoke_shell()
# Test racadmsim is working
self.channel.send("racadm help"+chr(13))
time.sleep(1)
str_output = read_buffer(self.channel)
assert "hwinventory" in str_output