<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Espace d&#039;Asher256 &#187; Python</title>
	<atom:link href="http://blog.asher256.com/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.asher256.com</link>
	<description></description>
	<lastBuildDate>Sat, 28 Jan 2012 21:45:37 +0000</lastBuildDate>
	<language>fr</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Script Linux: Trouver Facilement le Nom d&#8217;un Fichier Exécutable</title>
		<link>http://blog.asher256.com/script-linux-trouver-facilement-lexecutable-dun-programme/</link>
		<comments>http://blog.asher256.com/script-linux-trouver-facilement-lexecutable-dun-programme/#comments</comments>
		<pubDate>Thu, 08 Jan 2009 10:49:08 +0000</pubDate>
		<dc:creator>Asher256</dc:creator>
				<category><![CDATA[Informatique]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Planet-Libre]]></category>
		<category><![CDATA[Planet-Ubuntu]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Script]]></category>

		<guid isPermaLink="false">http://blog.asher256.com/?p=725</guid>
		<description><![CDATA[Il vous arrive parfois d&#8217;oublier et de vouloir chercher le nom ou le chemin exact vers un fichier exécutable de votre système de fichiers GNU/Linux ? Plusieurs d&#8217;entre vous le savent, il est possible de chercher à coup de ls dans les chemins de la variable d&#8217;environnement $PATH, mais comme toujours, il serait intéressant d&#8217;avoir [...]]]></description>
			<content:encoded><![CDATA[<p>Il vous arrive parfois d&#8217;<strong>oublier</strong> et de vouloir <strong>chercher</strong> le <strong>nom</strong> ou le <strong>chemin</strong> exact vers un <strong>fichier exécutable</strong> de votre <strong>système de fichiers <acronym title="GNU is Not UNIX">GNU</acronym>/Linux</strong> ?</p>
<p><img class="alignnone size-full wp-image-735 colorbox-725" title="showexe.py : script Python pour chercher et trouver des fichiers exécutable !" src="http://blog.asher256.com/wp-content/showexe-script-python-trouver-executable.jpg" alt="showexe script python trouver executable Script Linux: Trouver Facilement le Nom dun Fichier Exécutable" width="300" height="117" /></p>
<p>Plusieurs d&#8217;entre vous le savent, il est possible de chercher à coup de ls dans les chemins de la variable d&#8217;environnement <strong>$PATH</strong>, mais comme toujours, il serait intéressant d&#8217;avoir l&#8217;<strong>outil adéquat</strong> pour faire ce que vous souhaitez <strong>rapidement</strong> et <strong>facilement</strong>.</p>
<p>C&#8217;est ce que le <strong>script showexe.py</strong>, que vous pourrez télécharger à la fin de cet article, vous permettra de faire !<span id="more-725"></span></p>
<h2>Vous connaissez le nom exact du fichier exécutable Linux ? Utilisez which !</h2>
<p>Si vous connaissez le nom exact du fichier exécutable, une simple utilisation de which sera suffisante :</p>
<pre lang="bash">which firefox</pre>
<p>La commande ci-dessus vous donnera le chemin précis de Firefox. Chez moi par exemple, c&#8217;est /usr/bin/firefox.</p>
<p>Là où cela devient moins facile, c&#8217;est quand vous doutez un peu du nom du fichier l&#8217;exécutable (par exemple, est-ce t-firefox, remote-firefox ou autre chose ?).</p>
<p>C&#8217;est pour cette raison que j&#8217;ai développé le script showexe.py, un script  Python qui vous permettra de trouver instantanément le <strong>nom</strong> et le <strong>chemin complet</strong> d&#8217;un fichier exécutable, grâce à des <strong>filtres simples</strong> ou à des <strong>expressions rationnelles</strong>.</p>
<p></p>
<h2>À télécharger et installer : showexe.py, le script pour trouver facilement les fichiers exécutables Linux dont vous doutez du nom</h2>
<p>L&#8217;installation du script showexe.py est assez facile, si vous avez au moins une fois touché à la ligne de commande. Il suffit de copier (en tant que root) le script showexe.py dans le répertoire /usr/local/bin/, sous le nom showexe. Ceci étant fait, il ne vous restera qu&#8217;à le rendre exécutable et changer son utilisateur et groupe par root avec la commande :</p>
<pre lang="bash">chmod 755 /usr/local/bin/showexe
chown root:root /usr/local/bin/showexe</pre>
<p>(Il est aussi possible de faire cela avec des gestionnaires de fichiers graphiques, comme Thunar, Nautilus, Dolphin ou Konqueror. Il faut juste le lancer en tant que root, avec su ou sudo)</p>
<p>L&#8217;utilisation de showexe est très simple. Par exemple, pour trouver tous les programmes ayant &laquo;&nbsp;gimp&nbsp;&raquo; dans leur nom :</p>
<pre lang="bash">showexe --match gimp</pre>
<p>Il est aussi possible d&#8217;utiliser les expressions rationnelles :</p>
<pre lang="bash">showexe --match 'fir.*x'</pre>
<p>Cela vous donnera (à titre d&#8217;exemple) :</p>
<pre lang="bash">/usr/bin/firefox
/usr/bin/firefox-3.0
/usr/bin/firefox.debian</pre>
<p>(&#8216;fir.*x&#8217; veut dire tout ce qui commence par fir et finit par x. <a  rel="nofollow" href="http://fr.wikipedia.org/wiki/Expression_rationnelle">Si vous vous intéressez aux expressions rationnelles, lisez cet article</a>)</p>
<p>Information supplémentaire : si vous utilisez showexe sans arguments, tous les fichiers exécutables de votre système de fichiers seront affichés. Cela pourrait vous être utile pour utiliser un tube avec grep et filtrer grâce à ce dernier.</p>
<p>Vous pouvez <strong><a  rel="nofollow" href="http://blog.asher256.com/mes-fichiers/programmes/showexe.py">télécharger directement showexe.py</a></strong> (ce que je vous recommande) ou le lire / copier / coller directement depuis cet article :</p>
<pre lang="nothing">#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009, Asher256
# Site : http://blog.asher256.com/
#
# License : <acronym title="GNU General Public License">GPL</acronym>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the <acronym title="GNU is Not UNIX">GNU</acronym> General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# <acronym title="GNU is Not UNIX">GNU</acronym> General Public License for more details.
#
# You should have received a copy of the <acronym title="GNU is Not UNIX">GNU</acronym> General Public License
# along with This program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
"""
Affiche tous les fichiers exécutables du système.

Les fichier exécutables sont supposés exister dans les chemins
définis dans la variable d'environnement PATH. Ils sont séparés
avec le caractère ":".

Ce programme permet aussi de filtrer les fichiers à afficher.
"""

# Informations
__author__ = "Asher256 (contact at asher256 com)"
__copyright__ = "Copyright (c) Asher256, 2009"
__license__ = "<acronym title="GNU General Public License">GPL</acronym>"
__version__ = "0.1"

# Bibliothèques
import os
import sys
import re
from getopt import gnu_getopt, GetoptError
from stat import ST_MODE, S_ISREG

try:
    import psyco
    psyco.full()
except ImportError:
    pass

def usage():
    "Afficher l'aide"
    print """Utilitaire pour afficher tous les fichiers exécutables du \
système.

Usage: %s [options]

Options:
        -h, --help                 Cette aide!
        -v, --vebose               Affiche plus d'informations (les
                                   erreurs par exemple)

        -m, --match    Appliquer un filtre sur la liste des
                                   fichiers. Ce filtre correspond à une
                                   expression rationnelle.

       --version                   Afficher la version
""" % sys.argv[0]

def handle_options():
    "Lecture de toutes les options passées dans les arguments"

    # Lecture des arguments
    try:
        args = sys.argv[1:]
        optlist = gnu_getopt(args,
                             'vh:m:',
                             ['verbose', 'help', 'version', 'match='])
    except GetoptError:
        print "Erreur dans les arguments."
        print "--help pour plus d'informations..."
        sys.exit(1)

    # Le dictionnaire qui contiendra les options activées
    options = {}
    options["verbose"] = False
    options["match"] = ""

    # Traitement des arguments
    for option, value in optlist[0]:
        if option == "-v" or option == "--verbose":
            options["verbose"] = True
        if option == "-m" or option == "--match":
            options["match"] = value
        elif option == "-h" or option == "--help":
            usage()
            sys.exit(0)
        elif option == "--version":
            print __version__
            sys.exit(0)

    return options

def show_executables(options):
    "Afficher tous les fichier exécutables qui existent dans le système"
    # On parcourt tous les chemins de la variable d'environnemnt PATH
    for directory in os.environ['PATH'].split(":"):
        # Il doit impérativement être un répertoire
        if not os.path.isdir(directory):
            continue

        # Le filtre
        filter_activated = options["match"] and True or False

        if filter_activated:
            file_filter = re.compile(options["match"])

        # Afficher les fichiers exécutables
        for filename in os.listdir(directory):
            # Application du filtre
            if filter_activated:
                if not file_filter.search(filename):
                    continue
            # Test si le fichier est bien exécutable
            path = os.path.join(directory, filename)
            try:
                if not S_ISREG(os.stat(path)[ST_MODE]):
                    continue
            except OSError:
                continue
            # Affichage du fichier
            print path

if __name__ == '__main__':
    try:
        show_executables(handle_options())
    except KeyboardInterrupt:
        sys.exit(1)

# vim:ai:et:sw=4:ts=4:sts=4:tw=78:fenc=utf-8</pre>]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Script pour GNU/Linux : lancer un logiciel X (graphique) avec un utilisateur n&#8217;ayant pas le droit</title>
		<link>http://blog.asher256.com/gnu-linux-script-xauth-merge-extract-python-xorg-x11-lancer-programme-logiciel-x-graphique-avec-un-utilisateur-sans-droit/</link>
		<comments>http://blog.asher256.com/gnu-linux-script-xauth-merge-extract-python-xorg-x11-lancer-programme-logiciel-x-graphique-avec-un-utilisateur-sans-droit/#comments</comments>
		<pubDate>Sun, 31 Aug 2008 14:51:43 +0000</pubDate>
		<dc:creator>Asher256</dc:creator>
				<category><![CDATA[Informatique]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Planet-Libre]]></category>
		<category><![CDATA[Planet-Ubuntu]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Script]]></category>

		<guid isPermaLink="false">http://blog.asher256.com/?p=153</guid>
		<description><![CDATA[Il vous est probablement déjà arrivé, sous GNU/Linux, d&#8217;avoir besoin de lancer un de vos programmes ayant une interface graphique, comme Firefox, ou un programme louche que vous venez de télécharger, avec un autre utilisateur, sous votre session X actuelle, sans pour autant en ouvrir une autre. Il y a plusieurs façons de faire cela. [...]]]></description>
			<content:encoded><![CDATA[<p>Il vous est probablement déjà arrivé, sous <acronym title="GNU is Not UNIX">GNU</acronym>/Linux, d&#8217;avoir besoin de lancer un de vos programmes ayant une interface graphique, comme Firefox, ou un programme louche que vous venez de télécharger, avec un autre utilisateur, sous votre session X actuelle, sans pour autant en ouvrir une autre.</p>
<p>Il y a plusieurs façons de faire cela. Par exemple se connecter avec ssh en localhost, avec l&#8217;option -X ou -Y, ou utiliser xhost. Le souci, c&#8217;est que le premier est un peu lent (par exemple, pour lancer un jeu vidéo). Quand au deuxième, il n&#8217;est pas terrible du côté de la sécurité (ah les souvenirs&#8230; Polluer les displays des autres <img src='http://blog.asher256.com/wp-includes/images/smilies/icon_razz.gif' alt="icon razz Script pour GNU/Linux : lancer un logiciel X (graphique) avec un utilisateur nayant pas le droit" class='wp-smiley colorbox-153' title="Script pour GNU/Linux : lancer un logiciel X (graphique) avec un utilisateur nayant pas le droit" />  ).</p>
<p>Une des solutions les plus intéressantes est d&#8217;exporter votre clé avec xauth, pour l&#8217;importer ensuite dans l&#8217;utilisateur qui vous intéresse !<span id="more-153"></span> Comme il faut entrer deux ou trois commandes pour faire cela manuellement, j&#8217;ai développé le programme <em>sendxauth.py</em>, permettant d&#8217;automatiser cela grâce à cette commande simple à mémoriser.</p>
<h2>Un petit exemple pour clarifier les choses</h2>
<p>Si mon explication n&#8217;a pas été claire, laisser moi vous donner un petit exemple.</p>
<p>Supposons que vous avez un programme louche sous la main, que vous devez tester à tout prix. Comme il risque de faire ce qu&#8217;il veut dans le répertoire de votre utilisateur principal, par exemple vous voler vos informations confidentielles (les fichiers de configuration de votre navigateur web, qui contiennent peut-être vos mots de passes, ou vos courriels personnels ou confidentiels archivés), il peut-être intéressant de lancer ce programme avec un utilisateur limité. Donc, au lieu de le lancer avec votre utilisateur principal, vous allez utiliser l&#8217;utilisateur hyper limité « cobaye », qui n&#8217;a le droit de rien faire dans votre système, à part toucher à ses fichiers.</p>
<p></p>
<p>Le souci c&#8217;est que, si vous vous loguez dans votre utilisateur hyper limité :</p>
<pre lang="bash">su -l cobaye</pre>
<p>Et que vous lancez un programme graphique comme xterm (toujours en tant que « cobaye ») :</p>
<pre lang="bash">xterm</pre>
<p>Vous aurez l&#8217;erreur :</p>
<pre lang="listing">xterm Xt error: Can't open display:
xterm:  DISPLAY is not set</pre>
<p>C&#8217;est un peu normal car l&#8217;utilisateur n&#8217;a le droit de rien faire dans votre display (sécurité).</p>
<p>Pour lui donner ce droit, vous devez utiliser sendxauth.py (le script de ce tutoriel, voir plus bas) qui va s&#8217;occuper de tout faire à note place :</p>
<pre lang="bash">sendxauth.py cobaye</pre>
<p>Une fois que vous vous reloguerez sur « cobaye » :</p>
<pre lang="bash">su -l cobaye</pre>
<p>Et que vous aurez déclaré les deux variables recommandées par sendxauth.py :</p>
<pre lang="bash">export DISPLAY=":0.0"
export XAUTHORITY="/home/cobaye/.Xauthority"</pre>
<p>xterm se lancera sans aucun souci, en tant que « cobaye » !</p>
<h2>Télécharger le script</h2>
<p>Vous pouvez <a  title="sendxauth.py : envoyer votre clé xauth à un autre utilisateur" href="http://blog.asher256.com/mes-fichiers/programmes/sendxauth.py">télécharger le script sendxauth.py</a> ou le copier coller depuis :</p>
<pre lang="python">#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2008 Asher256
#
# Contact : contact at asher256 dot com
# Website : http://blog.asher256.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the <acronym title="GNU is Not UNIX">GNU</acronym> General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# <acronym title="GNU is Not UNIX">GNU</acronym> General Public License for more details.
#
# You should have received a copy of the <acronym title="GNU is Not UNIX">GNU</acronym> General Public License
# along with This program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
"""Send xauth key to different users."""

import sys
import os
import re
import pwd
from getopt import gnu_getopt, GetoptError

VERSION = '0.1'

SOURCE_USER = ''
DESTINATION_USER = ''
DISPLAY = ':0.0'
VERBOSE = False
DEV_NULL = ' &gt;/dev/null 2&gt;&amp;1'

def vprint(string):
    """Print 'string' if --verbose is defined.

    """
    if VERBOSE != False:
        print string

def check_environment():
    """Check if all required environment variables are available.

    """
    display = os.getenv('DISPLAY')
    if display == None:
        print 'DISPLAY environment variable is not declared.'
        sys.exit(1)
    else:
        globals()["DISPLAY"] = display 

def user_exists(user):
    """Return True if the user exists.

    """
    try:
        pwd.getpwnam(user)
    except KeyError:
        return False
    else:
        return True

def handle_arguments():
    """Handle options in the arguments (argv).

    """
    try:
        args = sys.argv[1:]
        optlist = gnu_getopt(args, 'vh', ['help', 'verbose'])
    except GetoptError:
        print 'Error when parsing arguments.'
        print "--help for more informations."
        sys.exit(1)

    if len(sys.argv) &lt; 2:
        print 'What\'s the destination user ?'
        print "--help for more informations."
        sys.exit(1)

    for user in optlist[1]:
        if not user_exists(user):
            print "The user '%s' doesn't exists." % user
            sys.exit(1)
        else:
            globals()["DESTINATION_USER"] = user

        break

    for option, value in optlist[0]:
        if option in ['-v', '--verbose']:
            globals()['VERBOSE'] = True
            globals()['DEV_NULL'] = ''
        elif option in ['-h', '--help']:
            print __doc__[0:-2]
            print
            print 'Usage: %s [OPTIONS] destination_user ' \
                  % os.path.basename(sys.argv[0])
            print
            print "OPTIONS :"
            print "          -h, --help            Show this help"
            print "          -v, --verbose         Verbose mode"
            print
            sys.exit(0)

def commands_required(*cmd_list):
    """This function tests if all programs in
    the arguments are available in the environment
    variable 'PATH'.

    """
    path = os.getenv('PATH')
    if path != None:
        path_list = path.split(os.pathsep)
    else:
        print "The environment variable PATH is not defined."
        sys.exit(1)

    for command in cmd_list:
        error = True
        for path in path_list:
            command_path = os.path.join(path, command)
            if os.access(command_path, os.X_OK):
                error = False
                break

        if error:
            print 'The command \'%s\' is not found.' % command
            sys.exit(1)

def su_command_generator(command, user=''):
    """Convert a command to : su -c 'command' user and return that.

    """
    command = re.sub(r"(['\\])", r"\\\1", command)
    command = 'su -c \'' + command + '\''
    if user != '':
        command += ' ' + user
    return command

def send_xauth(destination_user, source_user=''):
    """Send the authentication to the destination user

    If source_user is '', the source user is the actual user (automatically
    detected).

    """
    if source_user != '':
        sys.stdout.write(source_user + '\'s ')
    print 'xauth key will be sent to', destination_user + '...'
    print

    auth_tmpfile = '/tmp/sendxauth' + str(os.getpid())

    try:
        # extract
        command = 'xauth extract ' + auth_tmpfile + ' ' + DISPLAY
        if source_user != '':
            sys.stdout.write('You must enter ' + source_user + ' password : ')
            command = su_command_generator(command)

        vprint(command)
        result = os.system(command + DEV_NULL)
        if source_user != '':
            print
        if result != 0:
            print 'Errors when extracting xauth key.'
            sys.exit(1)

        # chmod auth key
        os.chmod(auth_tmpfile, 0777)

        # merge
        sys.stderr.write('You must enter ' + destination_user + ' password : ')
        destination_home = pwd.getpwnam(destination_user)[5]
        authfile = os.path.join(destination_home, '.Xauthority')

        # masquer les ' et \ dans authfile
        command = su_command_generator('xauth merge ' + auth_tmpfile,
                     destination_user)
        command = 'XAUTHORITY=\'' + authfile + '\' '  + command
        vprint(command)
        result = os.system(command + DEV_NULL)
        if DEV_NULL != '':
            print

        if result != 0:
            print 'Error when merging xauth key by ' + destination_user + '.'
            sys.exit(1)
        else:
            print "xauthority is sent to %s !" % destination_user
            print
            print "You maybe must declare these shell variables before " + \
                  "running a graphical program :"
            print "export DISPLAY=\"%s\"" % DISPLAY
            print "export XAUTHORITY=\"%s/.Xauthority\"" % \
                  pwd.getpwnam(destination_user)[5]
    finally:
        try:
            os.remove(auth_tmpfile)
        except OSError:
            print 'Warning: Cannot remove ' + auth_tmpfile + '...'
        else:
            vprint('Notice: ' + auth_tmpfile + ' deleted <img src='http://blog.asher256.com/wp-includes/images/smilies/icon_wink.gif' alt="icon wink Script pour GNU/Linux : lancer un logiciel X (graphique) avec un utilisateur nayant pas le droit" class='wp-smiley colorbox-153' title="Script pour GNU/Linux : lancer un logiciel X (graphique) avec un utilisateur nayant pas le droit" /> ')

if __name__ == '__main__':
    try:
        commands_required('xauth', 'su')
        check_environment()
        handle_arguments()
        send_xauth(DESTINATION_USER, SOURCE_USER)
    except KeyboardInterrupt:
        print "Interrupted."

# vim:ai:et:sw=4:ts=4:sts=4:tw=78:fenc=utf-8</pre>]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>

