Ejemplo n.º 1
0
def beacon_message():
    """
    Returns the message for sending as a beacon.
    """
    hostname = gethostname()
    beacon_time = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
    hiddensshd_hostname = _get_hiddensshd_hostname()
    message = """Hostname: {}
Time: {}
Uptime: {}
""".format(hostname, beacon_time, uptime())
    if hiddensshd_hostname is not False:
        message += 'HiddenSSH Hostname: {}'.format(hiddensshd_hostname)
    else:
        message += 'No HiddenSSH hostname found.'
    return message
def get_system_summary_str():
    SECURITY_UPDATES_COUNT_COMMAND = 'apt list --upgradable 2>/dev/null | grep "\-security" | wc -l'

    security_updates_count = sh.bash('-c', SECURITY_UPDATES_COUNT_COMMAND)

    last_week_logins = get_last_week_logins()
    last_week_logins_str = ''
    for i, login_dict in enumerate(last_week_logins):
        last_week_logins_str += 'User: {}\n'.format(login_dict['user'])
        ip = login_dict['ip']
        if ip != None:
            last_week_logins_str += 'IP: {}\n'.format(ip)
        last_week_logins_str += 'Date: {}\n'.format(login_dict['date'])
        if i < len(last_week_logins) - 1:
            last_week_logins_str += '--\n'

    available_space_str = ''
    for i, line in enumerate(sh.df('-h', '--total')):
        line = line.strip().split()
        if line[0] != 'Filesystem':
            if line[5] == '-':
                line[5] = 'TOTAL'
            available_space_str += '{} {}\n'.format(line[4], line[5])

    uptime_str = sh.uptime('-p')

    return \
'''\
⏳🖥️ *UPTIME*: {}

🔔📋 *SECURITY UPDATES AVAILABLE*: {}

💻 *LAST WEEK LOGINS*
`{}`

💽 *% DISK USAGE*
`{}`\
'''.format(uptime_str.strip(), security_updates_count.strip(), last_week_logins_str.strip(), available_space_str.strip())
Ejemplo n.º 3
0
def lock_dest(dest, name='backup.lock'):
  '''
  Create a lock directory in the destination directory. Raises an IOError if the
  lock could not be acquired, i.e. the destination directory is already locked.
  If the directory was locked before system boot, the directory is re-locked for
  this run, since the prior process couldn't still be running after a shutdown!

  Returns a function that removes the lock directory when called.
  '''

  # attempt to make a lock directory
  lock_dir = os.path.join(dest, name)
  info_path = os.path.join(lock_dir, 'info')

  # see if a lock already exists by trying to read the file for it
  try:
    logging.debug('Looking for existing lock directory...')

    data = None
    with open(info_path, 'r') as info_file:
      data = json.load(info_file)

    # figure out when the system booted and when the directory was locked
    boot_time = time.mktime(
        time.strptime(uptime(since=True).strip(), '%Y-%m-%d %H:%M:%S'))
    lock_time = time.mktime(time.strptime(data['start_time'], TIME_FORMAT))

    # remove the lock directory if it was created before the system booted,
    # since that process couldn't possibly still be running.
    if boot_time > lock_time:
      logging.info('Removing old lock directory (locked on %s, booted on %s)...',
          time.strftime(TIME_FORMAT, time.localtime(lock_time)),
          time.strftime(TIME_FORMAT, time.localtime(boot_time)))

      shutil.rmtree(lock_dir)
    else:
      logging.debug('Lock file exists and is still valid (locked on %s)',
          time.strftime(TIME_FORMAT, time.localtime(lock_time)))

  except FileNotFoundError:
    # do nothing since there was presumably no existing lock directory
    logging.debug('No old lock directory found')
    pass

  try:
    os.mkdir(lock_dir)

    # write some useful info to our file, so others can see our status while
    # we're running and so this program can determine if the lock has "expired",
    # i.e. the system rebooted while the directory was still locked.
    with open(info_path, 'w') as info_file:
      json.dump({
        'pid': os.getpid(),
        'start_time': time.strftime(TIME_FORMAT),
      }, info_file, indent='  ', sort_keys=True)
  except FileExistsError as e:
    raise IOError("Could not acquire lock in '" + dest + "'")

  # return a function that will remove the lock directory when called
  # TODO: there's probably a race condition in here somewhere... fix it!
  return lambda: (
    os.path.exists(info_path) and
    os.path.exists(lock_dir) and
    shutil.rmtree(lock_dir)
  )
Ejemplo n.º 4
0
 def ui_command_uptime(self):
     """ uptime - Tell how long the system has been running.. """
     print sh.uptime()
Ejemplo n.º 5
0
 def sysInfo(self):
     mLoad = re.sub(".*averages: ", "", sh.uptime().strip()).split(" ")[0]
     mVersion = sh.uname("-r").strip()
     return mVersion + " <" + mLoad + ">"