Ejemplo n.º 1
0
    def GetSshInfo(self, get):
        port = public.get_ssh_port()

        pid_file = '/run/sshd.pid'
        if os.path.exists(pid_file):
            pid = int(public.readFile(pid_file))
            status = public.pid_exists(pid)
        else:
            import system
            panelsys = system.system()

            version = panelsys.GetSystemVersion()
            if os.path.exists('/usr/bin/apt-get'):
                if os.path.exists('/etc/init.d/sshd'):
                    status = public.ExecShell(
                        "service sshd status | grep -P '(dead|stop)'|grep -v grep"
                    )
                else:
                    status = public.ExecShell(
                        "service ssh status | grep -P '(dead|stop)'|grep -v grep"
                    )
            else:
                if version.find(' 7.') != -1 or version.find(
                        ' 8.') != -1 or version.find('Fedora') != -1:
                    status = public.ExecShell(
                        "systemctl status sshd.service | grep 'dead'|grep -v grep"
                    )
                else:
                    status = public.ExecShell(
                        "/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep"
                    )

    #       return status;
            if len(status[0]) > 3:
                status = False
            else:
                status = True
        isPing = True
        try:
            file = '/etc/sysctl.conf'
            conf = public.readFile(file)
            rep = r"#*net\.ipv4\.icmp_echo_ignore_all\s*=\s*([0-9]+)"
            tmp = re.search(rep, conf).groups(0)[0]
            if tmp == '1': isPing = False
        except:
            isPing = True

        data = {}
        data['port'] = port
        data['status'] = status
        data['ping'] = isPing
        return data
Ejemplo n.º 2
0
    def connect(self):
        '''
            @name 连接服务器
            @author hwliang<2020-08-07>
            @return dict{
                status: bool 状态
                msg: string 详情
            }
        '''
        if not self._host: return returnMsg(False, 'WRONG_CONN_ADDR')

        if not self._user: self._user = '******'
        if not self._port: self._port = 22
        self.is_local()

        if self._host in ['127.0.0.1', 'localhost']:
            self._port = public.get_ssh_port()

        num = 0
        while num < 5:
            num += 1
            try:
                self.debug(public.getMsg('RECONN_TIMES', (num, )))
                if self._rep_ssh_config: time.sleep(0.1)
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(2 + num)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 8192)
                sock.connect((self._host, self._port))
                break
            except Exception as e:
                if num == 5:
                    self.set_sshd_config(True)
                    self.debug(public.getMsg('RECONN_FAILED', (e, )))
                    if self._host in ['127.0.0.1', 'localhost']:
                        return returnMsg(
                            False, 'CONN_FAIL',
                            ("Authentication failed ," + self._user + "@" +
                             self._host + ":" + str(self._port), ))
                    return returnMsg(False, 'CONN_FAIL1',
                                     (self._host, self._port))
                else:
                    time.sleep(0.2)

        import paramiko

        self._tp = paramiko.Transport(sock)

        try:
            self._tp.start_client()
            if not self._pass and not self._pkey:
                self.set_sshd_config(True)
                return public.returnMsg(False, 'SSH_LOGIN_INFO_ERR',
                                        (self._host, str(self._port)))
            self._tp.banner_timeout = 60
            if self._pkey:
                self.debug(public.getMsg('AUTH_PRI_KEY'))
                if sys.version_info[0] == 2:
                    try:
                        self._pkey = self._pkey.encode('utf-8')
                    except:
                        pass
                    p_file = BytesIO(self._pkey)
                else:
                    p_file = StringIO(self._pkey)
                try:
                    pkey = paramiko.RSAKey.from_private_key(p_file)
                except:
                    try:
                        p_file.seek(0)
                        pkey = paramiko.Ed25519Key.from_private_key(p_file)
                    except:
                        try:
                            p_file.seek(0)
                            pkey = paramiko.ECDSAKey.from_private_key(p_file)
                        except:
                            p_file.seek(0)
                            pkey = paramiko.DSSKey.from_private_key(p_file)
                self._tp.auth_publickey(username=self._user, key=pkey)
            else:
                self.debug(public.getMsg('AUTH_PASSWD'))
                self._tp.auth_password(username=self._user,
                                       password=self._pass)
        except Exception as e:
            if self._old_conf:
                s_file = '/www/server/panel/config/t_info.json'
                if os.path.exists(s_file): os.remove(s_file)
            self.set_sshd_config(True)
            self._tp.close()
            e = str(e)
            if e.find('Authentication failed') != -1:
                self.debug(public.getMsg('AUTH_FAIL', (str(e), )))
                return returnMsg(False, 'SSH_LOGIN_ERR1',
                                 (str(e + "," + self._user + "@" + self._host +
                                      ":" + str(self._port)), ))
            if e.find('Bad authentication type; allowed types') != -1:
                self.debug(public.getMsg('AUTH_FAIL', (str(e), )))
                if self._host in ['127.0.0.1', 'localhost'
                                  ] and self._pass == 'none':
                    return returnMsg(
                        False, 'USER_OR_PASSWD_ERR',
                        (str("Authentication failed ," + self._user + "@" +
                             self._host + ":" + str(self._port)), ))
                return returnMsg(False, 'SSH_LOGIN_ERR2', (str(e)))
            if e.find('Connection reset by peer') != -1:
                self.debug(public.getMsg('SSH_LOGIN_ERR3'))
                return returnMsg(False, 'SSH_LOGIN_ERR3')
            if e.find('Error reading SSH protocol banner') != -1:
                self.debug('SSH_LOGIN_ERR10')
                return returnMsg(False,
                                 public.getMsg('SSH_LOGIN_ERR4', (str(e), )))
            if not e:
                self.debug('SSH_LOGIN_ERR11')
                return returnMsg(False, "SSH_LOGIN_ERR5")
            err = public.get_error_info()
            self.debug(err)
            return returnMsg(False,
                             public.getMsg("SSH_LOGIN_ERR6", (str(err), )))

        self.debug('SSH_LOGIN_INFO3')
        self._ssh = self._tp.open_session()
        self._ssh.get_pty(term='xterm', width=100, height=34)
        self._ssh.invoke_shell()
        self._connect_time = time.time()
        self._last_send = []
        from BTPanel import request
        self._client = public.GetClientIp() + ':' + str(
            request.environ.get('REMOTE_PORT'))
        public.WriteLog(self._log_type, 'SSH_LOGIN',
                        (self._host, str(self._port)))
        self.history_send("LOGIN_SUCCESS2")
        self.set_sshd_config(True)
        self.debug('SSH_LOGIN_INFO2')
        return returnMsg(True, 'CONNECTION_SUCCEEDED')
Ejemplo n.º 3
0
    def is_local(self):
        '''
            @name 处理本地连接
            @author hwliang<2020-08-07>
            @ps 如果host为127.0.0.1或localhost,则尝试自动使用publicKey登录
            @return void
        '''

        if self._pass: return
        if self._pkey: return
        if self._host in ['127.0.0.1', 'localhost']:
            try:
                self._port = public.get_ssh_port()
                self.set_sshd_config()
                s_file = '/www/server/panel/config/t_info.json'
                if os.path.exists(s_file):
                    ssh_info = json.loads(
                        public.en_hexb(public.readFile(s_file)))
                    self._host = ssh_info['host'].strip()
                    if 'username' in ssh_info:
                        self._user = ssh_info['username']
                    if 'pkey' in ssh_info:
                        self._pkey = ssh_info['pkey']
                    if 'password' in ssh_info:
                        self._pass = ssh_info['password']
                    self._old_conf = True
                    return

                login_user = self.get_login_user()
                if self._user == 'root' and login_user == 'root':
                    id_rsa_file = ['/root/.ssh/id_rsa', '/root/.ssh/id_rsa_bt']
                    for ifile in id_rsa_file:
                        if os.path.exists(ifile):
                            self._pkey = public.readFile(ifile)
                            host_path = self._save_path + self._host
                            if not os.path.exists(host_path):
                                os.makedirs(host_path, 384)
                            return

                if not self._pass or not self._pkey or not self._user:
                    home_path = '/home/' + login_user
                    if login_user == 'root':
                        home_path = '/root'
                    self._user = login_user
                    id_rsa_file = [
                        home_path + '/.ssh/id_rsa',
                        home_path + '/.ssh/id_rsa_bt'
                    ]
                    for ifile in id_rsa_file:
                        if os.path.exists(ifile):
                            self._pkey = public.readFile(ifile)
                            return

                    self._pass = '******'
                    return
                    # _ssh_ks = home_path + '/.ssh'
                    # if not  os.path.exists(_ssh_ks):
                    #     os.makedirs(_ssh_ks,384)
                    # os.system("ssh-keygen -t rsa -P '' -f {}/.ssh/id_rsa |echo y".format(home_path))
                    # pub_file = home_path + '/.ssh/id_rsa.pub'
                    # az_file = home_path + '/.ssh/authorized_keys'
                    # rsa_file = home_path + '/.ssh/id_rsa'
                    # public.ExecShell('cat {} >> {} && chmod 600 {} {}'.format(pub_file, az_file, az_file,rsa_file))
                    # os.remove(pub_file)
                    # public.ExecShell("chown -R {}:{} {}".format(self._user,self._user,_ssh_ks))
                    # public.ExecShell("chmod -R 600 {}".format(_ssh_ks))
                    # self._pkey = public.readFile(rsa_file)

            except:
                return