def is_expired(host): expire_date = host.get("expire_date") if datetime.strptime(str(expire_date), "%Y%m%d") < datetime.now(): logger.info("{} was expired, expire date: {}".format( host, expire_date)) return True return False
def retrieve_all(self): if os.path.exists(self.local_dir): shutil.rmtree(self.local_dir) os.mkdir(self.local_dir) targets = self.get_targets() for target in targets: with open(os.path.join(self.local_dir, target[0]), "wb+") as f: f.write(self.retrieve(target[2])) logger.info("retrieve {} successfully".format(target[2]))
def get_targets(self): targets = [] response = self.session.get(self.url, timeout=30, verify=False) if response.ok: for item in response.json(): if item.get("type") == 'file': targets.append( (item.get("name"), item.get("type"), item.get("url"))) logger.info("find targets {}".format(targets)) return targets
def __init__(self, url, local_dir=None): self.session = requests.session() self.url = url if local_dir is None: self.local_dir = os.path.join(tempfile.gettempdir(), SSH_CONFIG_TMP_DIR) else: self.local_dir = local_dir logger.info("use dir {} for downloading ssh pub key configs".format( self.local_dir))
def dump(self): if os.path.exists(self.local_dir): shutil.rmtree(self.local_dir) os.mkdir(self.local_dir) for k, v in self.data.items(): with open(os.path.join(self.local_dir, k), "w+") as f: f.writelines(v) logger.info( "build and dump authorized_keys for user {} successfully". format(k))
def run(self): NetSource(self.url).retrieve_all() Builder().build() for file in os.listdir( os.path.join(tempfile.gettempdir(), SSH_AUTH_BUILD_DIR)): auth = AuthorizedKeys( os.path.join(tempfile.gettempdir(), SSH_AUTH_BUILD_DIR, file), file) auth.update() logger.info( "update authorized_keys file for user {} successfully".format( file))
def update(self): home = self.home_dir() if home is None: logger.warn("{} is not a valid user".format(self.user)) return old_file = os.path.join(home, SSH_AUTH_FILE_NAME) if not os.path.exists(old_file): os.makedirs(os.path.dirname(old_file), exist_ok=True) with open(old_file, "wb+") as _: pass logger.info("create {} successfully".format(old_file)) shutil.copyfile(self.new_file, old_file) logger.info("update {}".format(old_file))
def __init__(self, filename=None, local_dir=None): if filename is None: self.filename = os.path.join(tempfile.gettempdir(), SSH_CONFIG_TMP_DIR) else: self.filename = filename if local_dir is None: self.local_dir = os.path.join(tempfile.gettempdir(), SSH_AUTH_BUILD_DIR) else: self.local_dir = local_dir logger.info("use dir {} for building authorized_keys file".format( self.local_dir)) self.data = {} self.config = load_config(self.filename)
def verify_config(self): NetSource(self.url).retrieve_all() load_config(os.path.join(tempfile.gettempdir(), SSH_CONFIG_TMP_DIR)) logger.info("verification pass!")