Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_utils_ssh_connect_exception(mock_connect, mock_sleep, mock_time):
"""Test exception raised connecting to ssh."""
mock_connect.side_effect = paramiko.ssh_exception.SSHException('ERROR!')
mock_sleep.return_value = None
mock_time.side_effect = [0, 0, 2]
with pytest.raises(IpaSSHException) as error:
ipa_utils.get_ssh_client(
LOCALHOST,
'tests/data/ida_test',
timeout=1
)
assert str(error.value) == 'Attempt to establish SSH connection failed.'
assert mock_connect.call_count > 0
arg_parser.add_argument('hostname', type=str)
arg_parser.add_argument('--port', type=int, default=22)
arg_parser.add_argument('username', type=str)
args = arg_parser.parse_args()
sock = socket.socket()
try:
sock.connect((args.hostname, args.port))
except socket.error:
print '[-] Failed to connect'
sys.exit(1)
transport = paramiko.transport.Transport(sock)
try:
transport.start_client()
except paramiko.ssh_exception.SSHException:
print '[-] Failed to negotiate SSH transport'
sys.exit(2)
try:
transport.auth_publickey(args.username, paramiko.RSAKey.generate(2048))
except InvalidUsername:
print '[*] Invalid username'
sys.exit(3)
except paramiko.ssh_exception.AuthenticationException:
print '[+] Valid username'
socket.socket = socks.socksocket
socket.getaddrinfo = getaddrinfo
while 1:
try:
paramiko_logger = logging.getLogger("paramiko.transport")
paramiko_logger.disabled = True
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if timeout_sec is not None:
ssh.connect(target, username='', password='',
timeout=timeout_sec, port=port)
else:
ssh.connect(target, username='', password='', port=port)
exit = 0
break
except paramiko.ssh_exception.AuthenticationException as ssherr:
if 'Authentication failed.' in str(ssherr):
return
else:
exit += 1
if exit is retries:
error(messages(language, "ssh_connection_failed").format(
target, port, str(num), str(total)))
try:
__log_into_file(ports_tmp_filename,
'a', str(port), language)
except:
pass
break
except:
exit += 1
if exit is 3:
file_dst = req['action']['createImage']['path']
else:
img_name= createImage['source']['path']
index=img_name.rfind('/')
file_dst = self.get_notused_filename(img_name[:index+1] + createImage['name'] + '.qcow2')
self.copy_file(file_orig, file_dst)
qemu_info = self.qemu_get_info(file_orig)
if 'backing file' in qemu_info:
for k,v in self.localinfo['files'].items():
if v==qemu_info['backing file']:
self.qemu_change_backing(file_dst, k)
break
image_status='ACTIVE'
break
except paramiko.ssh_exception.SSHException as e:
image_status='ERROR'
error_text = e.args[0]
print self.name, "': create_image(",server_id,") ssh Exception:", error_text
if "SSH session not active" in error_text and retry==0:
self.ssh_connect()
except Exception as e:
image_status='ERROR'
error_text = str(e)
print self.name, "': create_image(",server_id,") Exception:", error_text
#TODO insert a last_error at database
self.db_lock.acquire()
self.db.update_rows('images', {'status':image_status, 'progress': 100, 'path':file_dst},
{'uuid':req['new_image']['uuid']}, log=True)
self.db_lock.release()
remote_script = resource_string('cstar.resources', 'scripts/remote_job.sh')
wrapper = remote_script.decode("utf-8") % (env_str,)
self.write_command(wrapper, "%s/wrapper" % (dir,))
cmd = """
cd %s
nohup ./wrapper
""" % (self.escape(dir),)
stdin, stdout, stderr = self.client.exec_command(cmd, timeout=timeout)
stdout.channel.recv_exit_status()
real_output = self.read_file(dir + "/stdout")
real_error = self.read_file(dir + "/stderr")
real_status = int(self.read_file(dir + "/status"))
return ExecutionResult(cmd, real_status, real_output, real_error)
except (ConnectionResetError, paramiko.ssh_exception.SSHException):
raise BadSSHHost("SSH connection to host %s was reset" % (self.hostname,))
def _handle_paramiko_exceptions(command=None):
try:
yield
except paramiko.ssh_exception.NoValidConnectionsError as e:
raise TargetNotRespondingError('Connection lost: {}'.format(e))
except paramiko.ssh_exception.AuthenticationException as e:
raise TargetStableError('Could not authenticate: {}'.format(e))
except paramiko.ssh_exception.BadAuthenticationType as e:
raise TargetStableError('Bad authentication type: {}'.format(e))
except paramiko.ssh_exception.BadHostKeyException as e:
raise TargetStableError('Bad host key: {}'.format(e))
except paramiko.ssh_exception.ChannelException as e:
raise TargetStableError('Could not open an SSH channel: {}'.format(e))
except paramiko.ssh_exception.PasswordRequiredException as e:
raise TargetStableError('Please unlock the private key file: {}'.format(e))
except paramiko.ssh_exception.ProxyCommandFailure as e:
raise TargetStableError('Proxy command failure: {}'.format(e))
except paramiko.ssh_exception.SSHException as e:
raise TargetTransientError('SSH logic error: {}'.format(e))
except socket.timeout:
def raw_exec_command(self, command: str, env: dict = None, retries: int = 3) -> tuple:
try:
stdin, stdout, stderr = self._ssh.exec_command(command, environment=env, timeout=self._timeout)
except (socket.timeout, paramiko.ssh_exception.SSHException):
Logger.warning('SSH command failed due to timeout, retrying')
self._connect()
return self.raw_exec_command(command, env, retries - 1)
except:
Logger.warning('SSH command not possible to execute')
Logger.warning(format_exc())
time.sleep(1)
self._connect()
return self.raw_exec_command(command, env, retries - 1)
return stdin, stdout, stderr
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
LOG.info("Waiting %s seconds to check %s ssh connection..." % (initial_wait, host.hostname))
sleep(initial_wait)
for x in range(retries):
try:
LOG.info("Login attempt number %i on %s " % (x+1,host.hostname))
ssh.connect(host.hostname, port=port,
username=username, password=password,
timeout= None, allow_agent= True,
look_for_keys= True, compress= False
)
return True
except (paramiko.ssh_exception.BadHostKeyException,
paramiko.ssh_exception.AuthenticationException,
paramiko.ssh_exception.SSHException, socket.error) as e:
LOG.warning("We caught an exception: %s ." % (e))
LOG.info("Wating %i seconds to try again..." % ( interval + 30))
sleep(interval)
sleep(30)
finally:
ssh.close()
def waitForConnect(self, maxtries=200, timeout=60):
start = time()
tries = 0
while not self.connected:
logger.debug("Connect attempt %s..." % tries)
def clearKeys(err):
self.client.get_host_keys().clear()
logger.debug("Clearing host keys...")
return OK(None)
state = self.connect() \
.catchError(paramiko.ssh_exception.BadHostKeyException, clearKeys) \
.catchError(paramiko.ssh_exception.SSHException, lambda err: OK(None)) \
.catchError(socket.error, lambda err: OK(None))
if state.isFail():
return state
if time() - start > timeout:
return Fail(LinkConnectTimeoutExceeded("Timeout exceeded"))
if tries >= maxtries:
return Fail(LinkRetriesExceeded("Max retries exceeded"))
tries += 1
sleep(0.8)
end = time()
logger.debug("Connect time: %ss" % (end - start))
self.connected = True
return OK(self)
session.packetizer.REKEY_BYTES = pow(2, 48)
session.packetizer.REKEY_PACKETS = pow(2, 48)
session.start_client()
if use_keys:
if try_key_auth(session, username):
return session
else:
raise Exception('Cannot authenticate using keys')
session.auth_password(username, password)
return session
except socket.gaierror as err:
raise Exception('Connection error: {}'.format(err.strerror))
except ssh_exception.BadAuthenticationType:
raise Exception('Cannot authenticate')