Best Python code snippet using autotest_python
usbmux.py
Source:usbmux.py
...139 self.loop = loop140 self.mux_socket_path = mux_socket_path141 self.mux_socket_port = mux_socket_port142 self._attach_notify = QueueNotify(loop=loop)143 async def _connect_transport(self, protocol_factory):144 if sys.platform in ('win32', 'cygwin'):145 return await self.loop.create_connection(protocol_factory, host='127.0.0.1', port=self.mux_socket_port)146 else:147 result = await self.loop.create_unix_connection(protocol_factory, self.mux_socket_path)148 return result149 async def connect(self):150 '''Opens a connection to the USBMux daemon on the local machine.151 :func:`connect_to_usbmux` provides a convenient wrapper to this method.152 '''153 self._waiter = asyncio.Future(loop=self.loop)154 await self._connect_transport(lambda: self)155 await self._waiter156 def connection_made(self, transport):157 super().connection_made(transport)158 self.send_msg(159 MessageType='Listen',160 ClientVersionString='pyusbmux',161 ProgName='pyusbmux'162 )163 def connection_lost(self, exc):164 super().connection_lost(exc)165 if not self._waiter.done():166 self._waiter.set_exception(exc)167 def msg_received(self, msg):168 mt = msg.get('MessageType')169 if mt == 'Result':170 if msg['Number'] == 0:171 self._waiter.set_result(None)172 else:173 self._waiter.set_exception(ConnectionFailed())174 elif mt == 'Attached':175 device_id = msg['Properties']['DeviceID']176 self.attached[device_id] = msg['Properties']177 self.device_attached(device_id, msg['Properties'])178 self._attach_notify.notify((ACTION_ATTACHED, device_id, msg['Properties']))179 elif mt == 'Detached':180 device_id = msg['DeviceID']181 if device_id in self.attached:182 props = self.attached[device_id]183 del(self.attached[device_id])184 self._attach_notify.notify((ACTION_DETACHED, device_id, props))185 self.device_detached(device_id)186 async def connect_to_device(self, protocol_factory, device_id, port):187 '''Open a TCP connection to a port on a device.188 Args:189 protocol_factory (callable): A callable that returns an asyncio.Protocol implementation190 device_id (int): The id of the device to connect to191 port (int): The port to connect to on the target device192 Returns:193 (dict, asyncio.Transport, asyncio.Protocol): The device information,194 connected transport and protocol.195 Raises:196 A USBMuxError subclass instance such as ConnectionRefused197 '''198 waiter = asyncio.Future(loop=self.loop)199 connector = USBMuxConnector(device_id, port, waiter)200 transport, switcher = await self._connect_transport(lambda: _ProtoSwitcher(self.loop, connector))201 # wait for the connection to succeed or fail202 await waiter203 app_protocol = switcher.switch_protocol(protocol_factory)204 device_info = self.attached.get(device_id) or {}205 return device_info, transport, app_protocol206 async def wait_for_serial(self, serial, timeout=DEFAULT_MAX_WAIT):207 '''Wait for a device with the specified serial number to attach.208 Args:209 serial (string): Serial number of the device to wait for.210 timeout (float): The maximum amount of time in seconds to wait for a211 matching device to be connected.212 Set to None to wait indefinitely, or -1 to only check currently213 connected devices.214 Returns:...
paramiko_host.py
Source:paramiko_host.py
...89 """Return a socket for use in instantiating a paramiko transport. Does90 not have to be a literal socket, it can be anything that the91 paramiko.Transport constructor accepts."""92 return self.hostname, self.port93 def _connect_transport(self, pkey):94 for _ in xrange(self.CONNECT_TIMEOUT_RETRIES):95 transport = paramiko.Transport(self._connect_socket())96 completed = threading.Event()97 transport.start_client(completed)98 completed.wait(self.CONNECT_TIMEOUT_SECONDS)99 if completed.isSet():100 self._check_transport_error(transport)101 completed.clear()102 transport.auth_publickey(self.user, pkey, completed)103 completed.wait(self.CONNECT_TIMEOUT_SECONDS)104 if completed.isSet():105 self._check_transport_error(transport)106 if not transport.is_authenticated():107 transport.close()108 raise paramiko.AuthenticationException()109 return transport110 logging.warning("SSH negotiation (%s:%d) timed out, retrying",111 self.hostname, self.port)112 # HACK: we can't count on transport.join not hanging now, either113 transport.join = lambda: None114 transport.close()115 logging.error("SSH negotation (%s:%d) has timed out %s times, "116 "giving up", self.hostname, self.port,117 self.CONNECT_TIMEOUT_RETRIES)118 raise error.AutoservSSHTimeout("SSH negotiation timed out")119 def _init_transport(self):120 for path, key in self.keys.iteritems():121 try:122 logging.debug("Connecting with %s", path)123 transport = self._connect_transport(key)124 transport.set_keepalive(self.KEEPALIVE_TIMEOUT_SECONDS)125 self.transport = transport126 self.pid = os.getpid()127 return128 except paramiko.AuthenticationException:129 logging.debug("Authentication failure")130 else:131 raise error.AutoservSshPermissionDeniedError(132 "Permission denied using all keys available to ParamikoHost",133 utils.CmdResult())134 def _open_channel(self, timeout):135 start_time = time.time()136 if os.getpid() != self.pid:137 if self.pid is not None:...
common.py
Source:common.py
...57 self.scp = None58 self.cmd_timeout = cmd_timeout59 self.allocate_pty = True60 self.hostkey_change_cb = hostkey_change_cb61 def _connect_transport(self, transport, username=None, password=None):62 if not username:63 username = self.username64 if not password:65 password = self.password66 try:67 transport.start_client()68 except paramiko.SSHException:69 raise ConnectionError("SSH negotiation failed")70 hostkeys = HostKeys()71 hostkey_file = os.path.expanduser('~/.ssh/known_hosts')72 hostkeys.load(hostkey_file)73 server_hostkey_name = ("[%s]:%d" % (self.hostname, self.port) if74 self.port != 22 else self.hostname)75 server_hostkey_type = transport.host_key.get_name()76 try:77 # Raises KeyError if no host key is present78 expected_key = hostkeys[server_hostkey_name][server_hostkey_type]79 if expected_key != transport.host_key:80 if self.hostkey_change_cb():81 raise KeyError82 else:83 raise SSHException("SSH host key changed to %s" %84 binascii.hexlify(transport.host_key.get_fingerprint()))85 except KeyError:86 hostkeys.add(server_hostkey_name, server_hostkey_type, transport.host_key)87 hostkeys.save(hostkey_file)88 try:89 transport.auth_password(username, password)90 # double check, auth_password should already raise the exception91 if not transport.is_authenticated():92 raise paramiko.AuthenticationException()93 except paramiko.AuthenticationException:94 raise LoginFailedException("SSH login failed for user %s" % username)95 def _make_transport(self):96 try:97 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)98 if self.timeout:99 sock.settimeout(self.timeout)100 sock.connect((self.hostname, self.port))101 return paramiko.Transport(sock)102 except (paramiko.SSHException, socket.timeout), e:103 raise ConnectionError("SSH socket failed: %s" % str(e))104 def open_console_channel(self):105 self.chan = self.transport.open_session()106 self.chan.settimeout(self.timeout)107 if self.allocate_pty:108 self.chan.get_pty()109 self.chan.invoke_shell()110 self.interact = pexpect.SSHClientInteraction(self.chan, timeout=self.cmd_timeout)111 def open_scp_channel(self):112 self.scp = scp.SCPClient(self.transport, socket_timeout=self.cmd_timeout)113 def connect(self, username, password, open_command_channel=True,114 open_scp_channel=False):115 self.username = username116 self.password = password117 self.transport = self._make_transport()118 self._connect_transport(self.transport)119 # Note: opening multiple channels is not supported by many embedded devices!120 if open_command_channel:121 self.open_console_channel()122 if open_scp_channel:123 self.open_scp_channel()124 def close(self):125 if self.chan:126 self.chan.close()127 if self.transport:128 self.transport.close()129 def verify_login(self, username, password):130 transport = None131 try:132 transport = self._make_transport()133 self._connect_transport(transport, username, password)134 except LoginFailedException:135 return False136 else:137 return transport.is_authenticated()138 finally:139 if transport:140 transport.close()141class NetworkDeviceRemoteControl(SSHRemoteControl):142 def __init__(self, *args, **kwargs):143 super(NetworkDeviceRemoteControl, self).__init__(*args, **kwargs)144 self.allocate_pty = False145 # set to True to prevent ctx_term_setup terminal setup/teardown146 self.terminal_setup = False147 self._date_format = ""...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!