Telnet login for Huawei Devices
557029
def telnet_login(
        self,
        pri_prompt_terminator=r"]\s*$",
        alt_prompt_terminator=r">\s*$",
        username_pattern=r"(?:user:|username|login|user name)",
        pwd_pattern=r"assword",
        delay_factor=1,
        max_loops=20,
    ):
        """"""

        delay_factor = self.select_delay_factor(delay_factor)
        password_change_prompt = re.escape("Change now? [Y/N]")
        combined_pattern = r"({}|{}|{})".format(
            pri_prompt_terminator, alt_prompt_terminator, password_change_prompt
        )

        output = ""
        return_msg = ""
        i = 1
        while i <= max_loops:
            try:
                # Search for username pattern / send username
                output = self.read_until_pattern(pattern=username_pattern)
                return_msg += output

                self.write_channel(self.username + self.TELNET_RETURN)

                # Search for password pattern, / send password
                output = self.read_until_pattern(pattern=pwd_pattern)
                return_msg += output

                self.write_channel(self.password + self.TELNET_RETURN)

                # Search for router prompt, OR password_change prompt
                output = self.read_until_pattern(pattern=combined_pattern)
                return_msg += output

                if re.search(password_change_prompt, output):
                    self.write_channel("N" + self.TELNET_RETURN)
                    output = self.read_until_pattern(pattern=combined_pattern)
                    return_msg += output

                return return_msg
            except EOFError:
                self.remote_conn.close()
                msg = "Login failed: {}".format(self.host)
                raise NetMikoAuthenticationException(msg)

        # Last try to see if we already logged in
        self.write_channel(self.TELNET_RETURN)
        time.sleep(0.5 * delay_factor)
        output = self.read_channel()
        return_msg += output
        if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(
            alt_prompt_terminator, output, flags=re.M
        ):
            return return_msg

        self.remote_conn.close()
        msg = "Login failed: {}".format(self.host)
        raise NetMikoAuthenticationException(msg)
600254
def auth_tls(self, mount_point='cert', use_token=True):
        
        return self.login('/v1/auth/{0}/login'.format(mount_point), use_token=use_token)
582903
@Override
    public void onConnect(final int rst, final HuaweiApiClient client) {
        //需要在子线程中执行获取push状态的操作
        ThreadUtil.INST.excute(new Runnable() {
            @Override
            public void run() {
                if (client == null || !ApiClientMgr.INST.isConnect(client)) {
                    HMSAgentLog.e("client not connted");
                    onGetPushStateResult(rst);
                } else {
                    HuaweiPush.HuaweiPushApi.getPushState(client);
                    onGetPushStateResult(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS);
                }
            }
        });
    }
334865
function middleware (node, config) {
    let token = config.credentials.token;
    let now = Date.now();

    return wechat (token, function(req, res, next) {

        let data = botmgr.buildMessageFlow({ message : req.weixin }, {
            userId:     'message.FromUserName',
            convId:     'message.FromUserName',
            inputType:  'message.MsgType',
            source:     'wechat'
        });

        switch (req.weixin.MsgType) {
            case "text":
                data.payload = req.weixin.Content;
                break;
            case "image":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentUrl: req.weixin.PicUrl, 
                    contentType: "image",
                    contentId: req.weixin.MediaId
                });
                break;
            case "voice":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "audio",
                    contentFormat: req.weixin.Format,
                    contentId: req.weixin.MediaId
                });
                break;
            case "video":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "video",
                    contentThumbId: req.weixin.ThumbMediaId,
                    contentId: req.weixin.MediaId
                });
                break;
            case "location":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "location",
                    contentLoc: {
                        label: req.weixin.Label,
                        latitude: req.weixin.Location_X,
                        longitude: req.weixin.Location_Y,
                        scale: req.weixin.Scale
                    }
                });
                break;
            case "link":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "link",
                    contentLink: {
                        title: req.weixin.Title,
                        description: req.weixin.Description,
                        url: req.weixin.Url
                    }
                });
                break;
            case "event":
                if (req.weixin.Event === "location_select") { res.status(200).end(); return; }
                else if (req.weixin.Event.match(/pic/)) WAIT_MESSAGES = req.weixin.SendPicsInfo.Count;
            
                data.payload = req.weixin.EventKey || "";
                let obj = { contentType: "event",
                            contentEvent: (req.weixin.ScanCodeInfo) ? req.weixin.ScanCodeInfo : {}};
                if (req.weixin.SendPicsInfo) obj.contentEvent = req.weixin.SendPicsInfo;
                data.message.attachments.push(obj);
                break;
            default:
                data.payload = "";
                break;
        }

        res.status(200).end();

        if (WAIT_MESSAGES > 0) {
            WAIT_QUEUE.push(data);
            WAIT_MESSAGES--;
            return;
        }

        if (WAIT_QUEUE.length > 0) {
            WAIT_QUEUE.push(data);

            if (WAIT_QUEUE[0].message.Event.match(/pic/)) {
                data = WAIT_QUEUE[0];
                data.message.attachments = [];
                for (let i = 1; i < WAIT_QUEUE.length; i++) {
                    data.message.attachments.push({
                        contentUrl: WAIT_QUEUE[i].message.PicUrl, 
                        contentType: "image",
                        contentId: WAIT_QUEUE[i].message.MediaId
                    });
                }
            } 
            else {    
                data = WAIT_QUEUE[1];
                data.payload = WAIT_QUEUE[0].payload;
            }
            WAIT_QUEUE = [];
        }

        // Handle Prompt
        let address = botmgr.getUserAddress(data)
        if (!address || address.carrier !== 'wechat') return false;

        let convId  = botmgr.getConvId(data)
        if (botmgr.hasDelayedCallback(convId, data.message)) return;

        api.getUser({openid: convId, lang:'en'}, 
            (err, result) => { 
                if (err) { node.error(err); return; }
                data.user.profile = result;
                return node.send(data);
            });  
    });
}
936796
def open(self, *args, **kwargs):
        
        Telnet.open(self, *args, **kwargs)
        if self.force_ssl:
            self._start_tls()
352928
def connect(self):
        """"""
        self._client = Telnet(self.hostname, self.port)
        self.closed = False
        query = {
            "MPRPC": self.VERSION,
            "AUTH": {
                "USERNAME": self.username,
                "PASSWORD": self.password
            }
        }
        queryb = self.encoder(query)
        if self.debug is True:
            print("send auth {}".format(queryb))
        self._client.write(queryb)
        self.remote_info = self._responsehandler()
1109062
def enable(self, enable_password):
        """"""
        if self.device.prompt[-1] == '#':
            self.log("Device is already in privileged mode")
            return

        events = [self.password_re, self.device.prompt_re, pexpect.TIMEOUT, pexpect.EOF]
        transitions = [
            (self.password_re, [0], 1, partial(a_send_password, enable_password), 10),
            (self.password_re, [1], -1, ConnectionAuthenticationError("Incorrect enable password",
                                                                      self.device.hostname), 0),
            (self.device.prompt_re, [0, 1, 2, 3], -1, a_expected_prompt, 0),
            (pexpect.TIMEOUT, [0, 1, 2], -1, ConnectionAuthenticationError("Unable to get privileged mode",
                                                                           self.device.hostname), 0),
            (pexpect.EOF, [0, 1, 2], -1, ConnectionError("Device disconnected"), 0)
        ]
        self.device.ctrl.send_command(self.enable_cmd)
        fsm = FSM("IOS-ENABLE", self.device, events, transitions, timeout=10, max_transitions=5)
        fsm.run()
        if self.device.prompt[-1] != '#':
            raise ConnectionAuthenticationError("Privileged mode not set", self.device.hostname)
1079693
@Override
    public void onConnect(int rst, HuaweiApiClient client) {
        if (client == null || !ApiClientMgr.INST.isConnect(client)) {
            HMSAgentLog.e("client not connted");
            onPushTokenResult(rst, null);
            return;
        }

        PendingResult<TokenResult> tokenResult = HuaweiPush.HuaweiPushApi.getToken(client);
        tokenResult.setResultCallback(new ResultCallback<TokenResult>() {
            @Override
            public void onResult(TokenResult result) {
                if (result == null) {
                    HMSAgentLog.e("result is null");
                    onPushTokenResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
                    return;
                }

                Status status = result.getStatus();
                if (status == null) {
                    HMSAgentLog.e("status is null");
                    onPushTokenResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null);
                    return;
                }

                int rstCode = status.getStatusCode();
                HMSAgentLog.d("status=" + status);
                // 需要重试的错误码，并且可以重试
                if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID
                        || rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) {
                    retryTimes--;
                    connect();
                } else {
                    onPushTokenResult(rstCode, result);
                }
            }
        });
    }
26291
def authenticate(self, driver):
        """"""
        #              0                     1                    2                  3
        events = [driver.press_return_re, driver.password_re, self.device.prompt_re, pexpect.TIMEOUT]

        transitions = [
            (driver.press_return_re, [0, 1], 1, partial(a_send, "\r\n"), 10),
            (driver.password_re, [0], 1, partial(a_send_password, self._acquire_password()),
             _C['first_prompt_timeout']),
            (driver.password_re, [1], -1, a_authentication_error, 0),
            (self.device.prompt_re, [0, 1], -1, None, 0),
            (pexpect.TIMEOUT, [1], -1,
             ConnectionError("Error getting device prompt") if self.device.is_target else partial(a_send, "\r\n"), 0)
        ]

        self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re)))
        fsm = FSM("SSH-AUTH", self.device, events, transitions, init_pattern=self.last_pattern, timeout=30)
        return fsm.run()
782946
private HuaweiApiClient resetApiClient(){
        if (context == null) {
            HMSAgentLog.e("HMSAgent not init");
            return null;
        }

        synchronized (APICLIENT_LOCK) {
            if (apiClient != null) {
                // 对于老的apiClient，1分钟后才丢弃，防止外面正在使用过程中这边disConnect了
                disConnectClientDelay(apiClient, 60000);
            }

            HMSAgentLog.d("reset client");

            // 这种重置client，极端情况可能会出现2个client都回调结果的情况。此时可能出现rstCode=0，但是client无效。
            // 因为业务调用封装中都进行了一次重试。所以不会有问题
            HuaweiIdSignInOptions signInOptions = new
                    HuaweiIdSignInOptions.Builder(HuaweiIdSignInOptions.DEFAULT_SIGN_IN).requestAccessToken().requestOpenId().requestUnionId().build();
            apiClient = new HuaweiApiClient.Builder(context)
                    .addApi(HuaweiPay.PAY_API)
                    .addApi(HuaweiGame.GAME_API)
                    .addApi(HuaweiSns.API)
                    .addApi(HuaweiId.SIGN_IN_API, signInOptions)
                    .addApi(HuaweiPush.PUSH_API)
                    .addConnectionCallbacks(INST)
                    .addOnConnectionFailedListener(INST)
                    .build();
            return apiClient;
        }
    }
79305
@Override
    public void onConnect(int rst, HuaweiApiClient client) {

        HMSAgentLog.d("onConnect:" + rst);

        Activity activityCur = ActivityMgr.INST.getLastActivity();

        if (activityCur != null && client != null) {
            client.checkUpdate(activityCur, this);
        } else if (activity != null && client != null){
            client.checkUpdate(activity, this);
        } else {
            // 跟SE确认：activity 为 null ， 不处理 | Activity is null and does not need to be processed
            HMSAgentLog.e("no activity to checkUpdate");
            onCheckUpdateResult(HMSAgent.AgentResultCode.NO_ACTIVITY_FOR_USE);
            return;
        }
    }
273387
def login(self, username, passwd_hash, webapi_key, country_code=1):
        """"""
        self.client = Client(self.webapi_url)
        self.ArrayOfLong = self.client.get_type('ns0:ArrayOfLong')  # this should be done by zeep...
        ver_key = self.client.service.doQuerySysStatus(1, 1, webapi_key)['verKey']
        return self.client.service.doLoginEnc(username, passwd_hash,
                                              country_code, webapi_key,
                                              ver_key)['sessionHandlePart']
1177274
private void startConnect() {

        // 触发一次连接将重试次数减1
        curLeftResolveTimes--;

        HMSAgentLog.d("start thread to connect");
        ThreadUtil.INST.excute(new Runnable() {
            @Override
            public void run() {
                HuaweiApiClient client =  getApiClient();

                if (client != null) {
                    HMSAgentLog.d("connect");
                    Activity curActivity = ActivityMgr.INST.getLastActivity();

                    // 考虑到有cp后台需要调用接口，HMSSDK去掉了activity不能为空的判断。这里只是取当前activity，可能为空
                    timeoutHandler.sendEmptyMessageDelayed(APICLIENT_TIMEOUT_HANDLE_MSG, APICLIENT_CONNECT_TIMEOUT);
                    client.connect(curActivity);
                } else {
                    HMSAgentLog.d("client is generate error");
                    onConnectEnd(HMSAgent.AgentResultCode.RESULT_IS_NULL);
                }
            }
        });
    }
356377
def obtain_hosting_device_credentials_from_config():
    
    cred_dict = get_specific_config('cisco_hosting_device_credential')
    attr_info = {
        'name': {'allow_post': True, 'allow_put': True,
                 'validate': {'type:string': None}, 'is_visible': True,
                 'default': ''},
        'description': {'allow_post': True, 'allow_put': True,
                        'validate': {'type:string': None},
                        'is_visible': True, 'default': ''},
        'user_name': {'allow_post': True, 'allow_put': True,
                      'validate': {'type:string': None},
                      'is_visible': True, 'default': ''},
        'password': {'allow_post': True, 'allow_put': True,
                     'validate': {'type:string': None},
                     'is_visible': True, 'default': ''},
        'type': {'allow_post': True, 'allow_put': True,
                 'validate': {'type:string': None}, 'is_visible': True,
                 'default': ''}}
    credentials = {}
    for cred_uuid, kv_dict in cred_dict.items():
        # ensure cred_uuid is properly formatted
        cred_uuid = uuidify(cred_uuid)
        verify_resource_dict(kv_dict, True, attr_info)
        credentials[cred_uuid] = kv_dict
    return credentials
431675
def open(self, **params):
        
        logger.info('opening telnet')
        self.port = params['port']
        self.ip = params['ip']
        self.tn = None
        self._init()
1227912
async def device_info():
    """"""
    async with aiohttp.ClientSession() as session:
        ghlocalapi = NetworkScan(LOOP, session)
        result = await ghlocalapi.scan_for_units(IPRANGE)
        print(result)
531979
def get_device(self):
        
        addr = self.address
        servers = [server for server in pyrax.cloudservers.list()
                if addr in server.networks.get("private", "")]
        try:
            return servers[0]
        except IndexError:
            return None