Skip to content

Instantly share code, notes, and snippets.

@laughk
Last active October 26, 2015 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laughk/8f9a43ea0867bfb71dc5 to your computer and use it in GitHub Desktop.
Save laughk/8f9a43ea0867bfb71dc5 to your computer and use it in GitHub Desktop.
py27-cli-with-loggin
# -*- coding:utf-8 -*-
import sys, os
import datetime
from subprocess import Popen, PIPE
from fabric.api import run, sudo, get, put, execute, env
def _ping():
run('uname -n;id')
def main():
env.hosts = '10.0.12.51'
execute(_ping)
class user(object):
def __init__(self):
self._set_username()
self.start_time = datetime.datetime.now()
def _set_username(self):
_username = os.getenv('USER')
_sudo_username = os.getenv('SUDO_USER')
if _username == 'root' and _sudo_username:
self.username = _sudo_username
else:
self.username = _username
def get_username(self):
return self.username
def get_start_time(self):
return self.start_time
class teeLogger(object):
def __init__(self, logfile):
import re
self.logfile = logfile
self.logdir = re.sub(r'[^/]+$', '', logfile)
self._make_logdir()
def _make_logdir(self):
if not os.path.exists(self.logdir):
os.makedirs(self.logdir)
os.chmod(self.logdir, 0777)
def start(self):
with open(self.logfile, 'w') as f:
_command_line = ''.join(sys.argv)
f.write('{0}\n'.format(_command_line))
tee = Popen(['tee', '-a', self.logfile], stdin=PIPE)
os.dup2(tee.stdin.fileno(), sys.stdout.fileno())
os.dup2(tee.stdin.fileno(), sys.stderr.fileno())
if __name__ == '__main__':
u = user()
log_file_name = '/tmp/script-log/{0}-{1}.log'.format(u.get_username(), u.get_start_time().strftime('%Y%m%dT%H%M%S'))
tee = teeLogger(log_file_name)
tee.start()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment