Пример #1
0
 def set_selected_packages(self):
     to_install = []
     to_remove = []
     if self.options[10].get_state() is True:
         if is_installed('popularity-contest') is False:
             to_install.append('popularity-contest')
     else:
         if is_installed('popularity-contest') is True:
             to_remove.append('popularity-contest')
     return to_install, to_remove
Пример #2
0
 def set_selected(self):
     to_install = []
     to_remove = []
     for index in range(0, len(self.packages)):
         if self.options[index].get_state() is True:
             if is_installed(self.packages[index][2]) is False:
                 to_install.append(self.packages[index][2])
         else:
             if is_installed(self.packages[index][2]) is True:
                 to_remove.append(self.packages[index][2])
     return to_install, to_remove
Пример #3
0
 def exec_plugin(self,p):
   result = ''
   if is_installed('gksudo'):
       result = os.popen('gksudo "nsaway -p '+p+'"').read()
   elif is_installed('pkexec'):
       result = os.popen('pkexec nsaway -p '+p).read()
   # Send the notify
   if result != '':
     subprocess.call(["notify-send", "-i",ICON_FILE,'NSAway',result])
     if "No problem detected" in result:
       update_tray_icon(self,'good')
     else:
       update_tray_icon(self,'alert')
Пример #4
0
 def exec_plugin(self, p):
     result = ''
     if is_installed('gksudo'):
         result = os.popen('gksudo "nsaway -p ' + p + '"').read()
     elif is_installed('pkexec'):
         result = os.popen('pkexec nsaway -p ' + p).read()
     # Send the notify
     if result != '':
         subprocess.call(["notify-send", "-i", ICON_FILE, 'NSAway', result])
         if "No problem detected" in result:
             update_tray_icon(self, 'good')
         else:
             update_tray_icon(self, 'alert')
Пример #5
0
    def __set_ui(self):
        handycolumn = Handy.Column()
        handycolumn.set_maximum_width(700)
        handycolumn.set_margin_top(24)
        self.add(handycolumn)

        box = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
        handycolumn.add(box)

        label0 = Gtk.Label(_('Applications'))
        label0.set_name('special')
        label0.set_alignment(0, 0.5)
        box.add(label0)

        listbox0 = Gtk.ListBox()
        box.add(listbox0)

        self.options = {}
        for index in range(0, len(self.packages)):
            self.options[index] = Gtk.Switch()
            self.options[index].set_valign(Gtk.Align.CENTER)
            listbox0.add(
                SettingRow(self.packages[index][0], self.packages[index][1],
                           self.options[index]))
            self.options[index].set_state(is_installed(
                self.packages[index][2]))
Пример #6
0
def generate_book_pdf(book_json_or_file, cover_img_file=False):
    if not is_installed("wkhtmltopdf"):
        log.warning(
            "wkhtmltopdf needs to be installed and added to PATH to generate "
            "pdf files")
        return

    book_json = get_or_read_json(book_json_or_file)
    filepath = get_book_pretty_filepath(book_json)
    filename = get_book_pretty_filename(book_json, ".pdf")
    pdf_file = os.path.join(filepath, filename)
    if os.path.exists(pdf_file):
        log.debug(f"Pdf file for {book_json['slug']} already exists, not "
                  "generating...")
        return pdf_file

    # generates the html file if it doesn't already exists
    html_file = os.path.join(get_book_pretty_filepath(book_json),
                             get_book_pretty_filename(book_json, ".html"))
    if not os.path.exists(html_file):
        generate_book_html(book_json_or_file, cover_img_file)

    log.debug(f"Generating .pdf for {book_json['slug']}")
    pdf_command = f'wkhtmltopdf --quiet "{html_file}" "{pdf_file}"'
    os.system(pdf_command)
    return pdf_file
Пример #7
0
def setup_mail_notification(admin_mail, sender_domain, relay):
    """Setup postfix as satellite system to send root mails to the admin"""
    # TODO more tests, so far tested on 14.04 only
    if not utils.is_installed('postfix'):
        sudo('debconf-set-selections <<< "postfix postfix/main_mailer_type '
             'string Satellite system"')
        sudo('debconf-set-selections <<< "postfix postfix/relayhost '
             'string {relay}"'.format(relay=relay))
        sudo('debconf-set-selections <<< "postfix postfix/mailname '
             'string {mailname}"'.format(mailname=sender_domain))
        utils.apt_get_update()
        sudo('apt-get install postfix -y')
    else:
        sudo('echo "{mailname}" > /etc/mailname'.format(mailname=sender_domain))
        sed('/etc/postfix/main.cf', '^relayhost.*',
            'relayhost = {relay}'.format(relay=relay), use_sudo=True)
        sudo('service postfix restart')
    for line in open(os.path.join(LUCHIZZ_DIR,
                                  'files/aliases')).read().split('\n'):
        try:
            if line.split()[0] == 'root:':
                line = line.format(admin_mail=admin_mail)
                sed('/etc/aliases', 'root:.*', line, use_sudo=True)
            if not contains('/etc/aliases', line.split()[0]):
                append('/etc/aliases', line, use_sudo=True)
        except IndexError:
            pass
    sudo('newaliases')
Пример #8
0
def luchizz_motd():
    """Restyle of the message of the day with useful informations"""
    if not utils.is_installed('toilet'):
        utils.apt_get_update()
        sudo('apt-get install toilet -y')
    if not utils.is_installed('landscape-common'):
        # this works only for ubuntu if not available nothing happens
        with settings(ok_ret_codes=(0, 100)):
            utils.apt_get_update()
            sudo('apt-get install landscape-common -y')
    motd_files_path = os.path.join(LUCHIZZ_DIR, 'files/motd/*')
    put(motd_files_path, '/etc/update-motd.d/', use_sudo=True)
    sudo('chown root: /etc/update-motd.d/*')
    sudo('chmod 755 /etc/update-motd.d/*')
    # remove ubuntu help url in motd
    sudo('rm -f /etc/update-motd.d/10-help-text')
Пример #9
0
def setup():
	if not is_installed("git"):
		install("git")

	if get_config("user.name") == None:
		set_config("user.name", prompt("Enter Git username:"******"user.email") == None:
		set_config("user.email", prompt("Enter Git email:"))
Пример #10
0
def setup_etckeeper():
    if not is_installed('etckeeper'):
        sudo('apt-get install git etckeeper -y')
        comment('/etc/etckeeper/etckeeper.conf', 'VCS="bzr"', use_sudo=True)
        uncomment('/etc/etckeeper/etckeeper.conf', 'VCS="git"', use_sudo=True)
        sudo('etckeeper init')
        sudo('etckeeper commit -m "Initial commit."')
    else:
        print("skip, etckeeper is already installed!")
Пример #11
0
def setup():
	if not is_installed("vim"):
		install("vim")

	if not exists("~/.vim"):
		github.clone("vimfiles", "~/.vim")

	if not exists("~/.vimrc"):
		run("ln ~/.vim/vimrc ~/.vimrc")
Пример #12
0
def setup_etckeeper():
    """Setup etckeeper tool with git backend"""
    if not utils.is_installed('etckeeper'):
        utils.apt_get_update()
        sudo('apt-get install git etckeeper -y')
        comment('/etc/etckeeper/etckeeper.conf', 'VCS="bzr"', use_sudo=True)
        uncomment('/etc/etckeeper/etckeeper.conf', 'VCS="git"', use_sudo=True)
        sudo('etckeeper init')
        sudo('etckeeper commit -m "Initial commit."')
    else:
        print("skip, etckeeper is already installed!")
Пример #13
0
    def install(self, force=True):
        package = self.package
        if not force and is_installed(package):
            print(f"====> Package {package} is already installed!")
            return False

        print(
            f"====> Installing package {package} using installer {self.name}")

        install_command = f"{self.prefix} {package}"
        print(f"=====> running {install_command}")

        code = sub.call(install_command.split())

        if code != 0:
            return False

        return True
Пример #14
0
def setup_shorewall_one_interface():
    # WARNING UNSTABLE
    # FIXME network cut in case interface is not eth0 but em0 for instance :(
    # TODO maybe is better to install also conntrack
    if not is_installed('shorewall'):
        sudo('apt-get install shorewall -y')
        sudo('cp /usr/share/doc/shorewall/examples/one-interface/* '
             '/etc/shorewall/')
        rules = """SSH(ACCEPT)         net             $FW"""
        append('/etc/shorewall/rules', rules, use_sudo=True)
        sed('/etc/default/shorewall', 'startup=0', 'startup=1', use_sudo=True)
        sudo('/sbin/shorewall check')
        try:
            # BETTER TO ASK BEFORE TO PREVENT BEING CUT OFF
            # ~sudo('/sbin/shorewall restart')
            pass
        except socket.error:
            pass
    else:
        print("skip, shorewall is already installed!")
Пример #15
0
 def __load_default_states(self):
     settings = Gio.Settings.new(
         'org.gnome.desktop.privacy')
     self.options[0].set_state(variant_to_value(
         settings.get_user_value('disable-camera')) is True)
     self.options[1].set_state(variant_to_value(
         settings.get_user_value('disable-microphone')) is True)
     self.options[2].set_state(variant_to_value(
         settings.get_user_value('disable-sound-output')) is True)
     self.options[3].set_state(variant_to_value(
         settings.get_user_value('hide-identity')) is True)
     self.options[4].set_state(variant_to_value(
         settings.get_user_value('remember-app-usage')) is False)
     self.options[5].set_state(variant_to_value(
         settings.get_user_value('remember-recent-files')) is False)
     self.options[6].set_state(variant_to_value(
         settings.get_user_value('remove-old-temp-files')) is True)
     self.options[7].set_state(variant_to_value(
         settings.get_user_value('remove-old-trash-files')) is True)
     self.options[8].set_state(variant_to_value(
         settings.get_user_value('report-technical-problems')) is True)
     self.options[9].set_state(variant_to_value(
         settings.get_user_value('send-software-usage-stats')) is True)
     self.options[10].set_state(is_installed('popularity-contest'))
Пример #16
0
 def assert_is_installed(self, pkg):
     self.failUnless(ut.is_installed(pkg),
                     'Cannot find %s in your system' % pkg)
Пример #17
0
 def test_used_packages(self):
     packages = ('xvfb-run', 'mitmdump', 'mysql', cm.CHROME_BINARY)
     for package in packages:
         self.failUnless(ut.is_installed(package), 'Cannot find %s in your system' % package) 
Пример #18
0
def combine_audio(book_json, files, keep_blinks=False, cover_img_file=False):
    if not is_installed("ffmpeg"):
        log.warning(
            "ffmpeg needs to be installed and added to PATH to combine audio "
            "files")
        return

    log.info(f"Combining audio files for {book_json['slug']}")
    filepath = get_book_pretty_filepath(book_json)
    filename = get_book_pretty_filename(book_json, ".m4a")

    files_list = os.path.abspath(os.path.join(filepath, "temp.txt"))
    combined_audio_file = os.path.abspath(os.path.join(filepath, "concat.m4a"))
    tagged_audio_file = os.path.abspath(os.path.join(filepath, filename))

    # ffmpeg fails on windows if the output filepath is longer than 260 chars
    # if len(tagged_audio_file) >= 260:
    #     log.warn("ffmpeg output file longer than 260 characters. Trying "
    #              "shorter filename...")
    #     tagged_audio_file = os.path.abspath(
    #         os.path.join(
    #             filepath, get_book_short_pretty_filename(book_json, ".m4a")))
    #     if len(tagged_audio_file) >= 260:
    #         log.warn("shorter filename still too long! Consider running "
    #                  "the script from a shorter path.")
    #         return

    with open(files_list, "w", encoding="utf-8") as outfile:
        for file in files:
            # escape any quotes for the ffmpeg concat's command file list
            sanitized_file = os.path.abspath(file).replace("'", "'\\''")
            outfile.write(f"file '{sanitized_file}'\n")
    silent = "-nostats -loglevel 0 -y"
    concat_command = (
        f'ffmpeg {silent} -f concat -safe 0 -i "{files_list}" -c copy '
        f'"{combined_audio_file}"')
    os.system(concat_command)
    if cover_img_file:
        cover_embed = (f'-i "{cover_img_file}" -map 0 -map 1 -disposition:v:0 '
                       'attached_pic')
    else:
        cover_embed = ""
    title_metadata = f"-metadata title=\"{book_json['title']}\""
    author_metadata = f"-metadata artist=\"{book_json['author']}\""
    category_metadata = f"-metadata album=\"{book_json['category']}\""
    genre_metadata = '-metadata genre="Blinkist"'
    tag_command = (
        f'ffmpeg {silent} -i "{combined_audio_file}" {cover_embed} -c copy '
        f"{title_metadata} {author_metadata} "
        f"{category_metadata} {genre_metadata}")
    tag_command += f' "{tagged_audio_file}"'
    os.system(tag_command)

    # clean up files
    if os.path.exists(files_list):
        os.remove(files_list)
    if os.path.exists(combined_audio_file):
        os.remove(combined_audio_file)
    if not (keep_blinks):
        log.debug(
            f"Cleaning up individual audio files for {book_json['slug']}")
        for file in files:
            if os.path.exists(file):
                os.remove(os.path.abspath(file))
Пример #19
0
 def assert_is_installed(self, pkg):
     self.failUnless(ut.is_installed(pkg), 'Cannot find %s in your system' % pkg)
Пример #20
0
def main():
    parser = OptionParser("usage: luchizz.py --host hosts [options]",
                          version="luchizz {}".format(__version__))
    parser.add_option("-H", "--hosts", dest="HOSTS",
                      help="comma-separated list of hosts to operate on",
                      type='string', metavar="HOSTS")
    parser.add_option("-p", "--packages-file", dest="PKGS_FILE",
                      help="yaml file for the debian packages you want to "
                      "install via apt-get",
                      type='string', metavar="PKGS_FILE")
    parser.add_option("-d", "--debug", dest="DEBUG",
                      help="all output from fabric", action='store_true',
                      default=False)
    (options, args) = parser.parse_args()

    # Setting up the target hosts
    if options.HOSTS:
        env.host_string = options.HOSTS.split(',')[0]

    # Setting up the default path for the packages yaml
    if not options.PKGS_FILE:
        options.PKGS_FILE = os.path.join(LUCHIZZ_DIR, 'packages.yaml')
    # Make sure the package file exists
    if os.path.isfile(options.PKGS_FILE):
        # get the dictionary from the yaml file
        p = open(options.PKGS_FILE, 'r')
        packages = yaml.load(p.read())
        p.close()
    else:
        print "IOError: packages file not found {}".format(options.PKGS_FILE)
        sys.exit(1)

    # Setting up fabric output for debug
    # FIXME here there are problem with the overrided options context managers
    # needs to be always used probably
    if options.DEBUG:
        to_set = {'aborts': True,
                  'debug': True,
                  'running': True,
                  'status': True,
                  'stderr': True,
                  'stdout': True,
                  'user': True,
                  'warnings': True}
    # Setting up fabric output for normal usage
    else:
        to_set = {'aborts': True,
                  'debug': False,
                  'running': False,
                  'status': False,
                  'stderr': False,
                  'stdout': True,
                  'user': False,
                  'warnings': True}
    # Apply the dictionary structure to the output handler of fabric
    for key in to_set.keys():
        fabric_output[key] = to_set[key]

    print_splash(__version__)
    with quiet():
        check_root()
    print("\nReady to luchizz: {}?\n"
          "CTRL-C to abort\n".format(env.host_string))
    time.sleep(1)

    # Setup etckeeper
    if not is_installed('etckeeper'):
        if query_yes_no("SETUP etckeeper to track changes in /etc "
                        "using git?", 'yes'):
            setup_etckeeper()

    # Luchizz the shell
    if query_yes_no("Do you want to `luchizz` root and all users "
                    "with a home folder in /home?", 'yes'):
        with quiet():
            luchizz_shell()
        # If luchizz shell is applied a dedicated commit is applied
        # 127 return code is in case etckeeper is not installed won't fail
        with settings(ok_ret_codes=(0, 1, 127)), quiet():
            sudo('etckeeper commit -m "luchizzed shell"')

    # Install luchizz scripts
    if query_yes_no("INSTALL luchizz scripts in /usr/local/bin?", 'yes'):
        with quiet():
            luchizz_scripts()

    # Copy ssh keys
    if query_yes_no("CONFIGURE local ssh keys as authorized for "
                    "authentication?", 'yes'):
        with quiet():
            set_authentication_keys()

    # Copy .gitconfig
    if os.path.isfile(os.path.join(os.getenv('HOME'), '.gitconfig')):
        if query_yes_no("CONFIGURE .gitconfig file from the local user?",
                        'yes'):
            with quiet():
                set_gitconfig()

    if query_yes_no("CONFIGURE do you want to luchizz the gitconfig for"
                    "local user?", 'yes'):
            with quiet():
                luchizz_gitconfig()

    # Disable backports
    if query_yes_no("DISABLE backports repositories?", 'yes'):
        with quiet():
            set_disable_backports()

    # Disable automatic installation of suggested and recommended packages
    if query_yes_no("DISABLE automatic installation of recommended packages?",
                    'yes'):
        with quiet():
            set_disable_recommended()

    for pkg_section in packages.keys():
        if query_yes_no("INSTALL {} packages?".format(pkg_section),
                        'yes'):
            install_packages(packages[pkg_section])

    # ~shorewall = query_yes_no("Do you want to install shorewall and setup "
    # ~"as one interface server?""", 'no')
    # ~if shorewall:
    # ~setup_shorewall_one_interface()

    # Catch all commit for etckeeper
    # 127 return code is in case etckeeper is not installed won't fail
    with settings(ok_ret_codes=(0, 1, 127)), quiet():
        sudo('etckeeper commit -m "final luchizz commit"')

    print "\nluchizz done"
    return 0
Пример #21
0
 def update(self):
     for index in range(0, len(self.packages)):
         self.options[index].set_state(is_installed(
             self.packages[index][2]))