个人工具

“UbuntuHelp:BroadcastAlertWithSound”的版本间的差异

来自Ubuntu中文

跳转至: 导航, 搜索
第3行: 第3行:
 
This page describes how to send pop-up messages to NX and X-windows sessions.  With the NX sessions, these messages can be accompanied by sound.  This was developed using Ubuntu 7.04 (Feisty).
 
This page describes how to send pop-up messages to NX and X-windows sessions.  With the NX sessions, these messages can be accompanied by sound.  This was developed using Ubuntu 7.04 (Feisty).
 
=== Introduction ===
 
=== Introduction ===
The Python script below was developed to send pop-up messages with sound to NX and X sessions running on a Ubuntu server.  This was developed on a home network consisting of a Ubuntu 7.04 server running [[UbuntuHelp:FreeNX|FreeNX]], and Windows PCs and Ubuntu/Xubuntu PCs running the nomachine NX client or X-Windows.  The NX clients are configured to support sound, but the X-windows clients receive only a silent pop-up message.
+
The Python script below was developed to send pop-up messages with sound to NX and X sessions running on a Ubuntu server.  This was developed on a home network consisting of a Ubuntu 7.04 server running FreeNX, and Windows PCs and Ubuntu/Xubuntu PCs running the nomachine NX client or X-Windows.  The NX clients are configured to support sound, but the X-windows clients receive only a silent pop-up message.
 
=== Dependencies ===
 
=== Dependencies ===
 
The script uses gxmessage to send the pop-up messages, and esdplay to transmit a .wav sound file.  Gxmessage is a requirement to run the script.  Esound needs to be installed if sound functionality is required.
 
The script uses gxmessage to send the pop-up messages, and esdplay to transmit a .wav sound file.  Gxmessage is a requirement to run the script.  Esound needs to be installed if sound functionality is required.
第12行: 第12行:
 
=== Setting up NX Sessions for Sound ===
 
=== Setting up NX Sessions for Sound ===
 
This section is not required to get the script running without sound.  If you want to get the script running quickly, you can skip this section, and come back to it later.
 
This section is not required to get the script running without sound.  If you want to get the script running quickly, you can skip this section, and come back to it later.
Follow the [[UbuntuHelp:FreeNX|FreeNX]] instructions to install [[UbuntuHelp:FreeNX|FreeNX]] on a Ubuntu server.
+
Follow the [[FreeNX]] instructions to install FreeNX on a Ubuntu server.
 
Ensure that esound is installed (see above), and that the esd service is running like so ..
 
Ensure that esound is installed (see above), and that the esd service is running like so ..
 
<pre><nowiki>
 
<pre><nowiki>
第32行: 第32行:
 
This is the text that needs to be copied into bcast.py ..
 
This is the text that needs to be copied into bcast.py ..
 
<pre><nowiki>
 
<pre><nowiki>
#!/usr/bin/python
+
#!/usr/bin/python
 
+
 
# Author: David Collins, 2007
 
# Author: David Collins, 2007
 
# Note: Changing values in os.environ does not affect calling process's environment
 
# Note: Changing values in os.environ does not affect calling process's environment
 
 
"""
 
"""
 
Broadcast a pop-up message to X and NX sessions.  A .wav can be specified to
 
Broadcast a pop-up message to X and NX sessions.  A .wav can be specified to
 
send sound with the message, but this will only be received by NX sessions.
 
send sound with the message, but this will only be received by NX sessions.
 
 
Usage: sudo ./bcast.py --message "message" [--title "title"] [--timeout secs]
 
Usage: sudo ./bcast.py --message "message" [--title "title"] [--timeout secs]
                                        [--sound "wavefile.wav"]
+
[--sound "wavefile.wav"]
 
"""
 
"""
 
+
import os, subprocess, sys, getopt
import os, subprocess, sys, getopt, string
+
 
+
 
# -------------------------------------------------------------
 
# -------------------------------------------------------------
 
def usage(msg=None):
 
def usage(msg=None):
  sys.stdout = sys.stderr
+
sys.stdout = sys.stderr
  if msg != "":
+
if msg != "":
    print msg
+
print msg
  print __doc__
+
print <u>doc</u>
  sys.exit(2)
+
sys.exit(2)
 
# -------------------------------------------------------------
 
# -------------------------------------------------------------
 
def processargs():
 
def processargs():
  global title, message, wavefile, timeout
+
global title, message, wavefile, timeout
 
+
# Default values ..
  # Default values ..
+
title = "Alert"
  title = "Alert"
+
message = ""
  message = ""
+
wavefile = ""
  wavefile = ""
+
timeout = 0
  timeout = 0
+
optionlist = [[UbuntuHelp:message=","title=","timeout=","sound=]]
 
+
try:
  optionlist = ["message=","title=","timeout=","sound="]
+
opts, args = getopt.getopt(sys.argv[1:], "", optionlist)
  try:
+
if len(opts) < 1:
    opts, args = getopt.getopt(sys.argv[1:], "", optionlist)
+
raise getopt.error, ""
    if len(opts) < 1:
+
except getopt.error, msg:
      raise getopt.error, ""
+
usage(msg)
  except getopt.error, msg:
+
try:
    usage(msg)
+
for opt, val in opts:
 
+
if val.startswith("--"):  # 2 options with no value between
  try:
+
raise Exception("Option '%s' has no associated value." % opt)
    for opt, val in opts:
+
# print opt, "=", val
      if val[0:2] == "--":  # 2 options with no value between
+
if opt == "--message":
        raise Exception, "Option '" + opt + "' has no associated value."
+
message = val
      # print opt, "=", val
+
elif opt == "--title":
      if opt == "--message":
+
title = val
        message = val
+
elif opt == "--sound":
      elif opt == "--title":
+
wavefile = val
        title = val
+
elif opt == "--timeout":
      elif opt == "--sound":
+
try:
        wavefile = val
+
timeout = int(val)
      elif opt == "--timeout":
+
except:
        try:
+
raise Exception("Timeout value '%s' is not an integer." % val)
          timeout = string.atoi(val)
+
except Exception, msg:
        except:
+
usage(msg)
          raise Exception, "Timeout value '" + val + "' is not an integer."
+
for arg in args:
  except Exception, msg:
+
print "***" + arg
    usage(msg)
+
 
+
  for arg in args:
+
    print "***" + arg
+
 
# -------------------------------------------------------------
 
# -------------------------------------------------------------
 
def checkdependancies():
 
def checkdependancies():
  # Make sure that gxmessage is available ..
+
# Make sure that gxmessage is available ..
  # PIPE was not defined - so used -1
+
# PIPE was not defined - so used -1
  p = subprocess.Popen(['which gxmessage'], stdout=-1, shell=True)
+
p = subprocess.Popen(['which gxmessage'], stdout=-1, shell=True)
  result = p.wait()
+
result = p.wait()
  if result != 0:
+
if result != 0:
    print "Gxmessage needs to be installed."
+
print "Gxmessage needs to be installed."
    print "On ubuntu, run 'sudo apt-get install gxmessage'."
+
print "On ubuntu, run 'sudo apt-get install gxmessage'."
    exit(-2)
+
exit(-2)
 
+
# Make sure that esdplay is available ..
  # Make sure that esdplay is available ..
+
p = subprocess.Popen(['which esdplay'], stdout=-1, shell=True)
  p = subprocess.Popen(['which esdplay'], stdout=-1, shell=True)
+
result = p.wait()
  result = p.wait()
+
if result != 0:
  if result != 0:
+
print "esdplay is not installed - therefore sound will not function."
    print "esdplay is not installed - therefore sound will not function."
+
print "On ubuntu, run 'sudo apt-get install esound' to enable sound."
    print "On ubuntu, run 'sudo apt-get install esound' to enable sound."
+
 
# -------------------------------------------------------------
 
# -------------------------------------------------------------
 
def sendalerts():
 
def sendalerts():
  # To hold list of displays - to avoid duplication.
+
# To hold list of displays - to avoid duplication.
  displaylist = []
+
displaylist = []
 
+
# Get PID list in /proc ..
  # Get PID list in /proc ..
+
pidlist = os.listdir("/proc")
  pidlist = os.listdir("/proc")
+
for pid in pidlist:
  for pid in pidlist:
+
# All number directories are PIDs ..
 
+
if pid.isdigit():
    # All number directories are PIDs ..
+
try:
    if pid.isdigit():
+
envfile = "/proc/" + str(pid) + "/environ"
      try:
+
env = open(envfile)
        envfile = "/proc/" + str(pid) + "/environ"
+
environ = env.readline()
        env = open(envfile)
+
except:
        environ = env.readline()
+
pass  #readenv=False
      except:
+
else:
        pass  #readenv=False
+
# print envfile
      else:
+
envlist = environ.split("\0")
        # print envfile
+
# print len(envlist)
        envlist = environ.split("\0")
+
espeaker = ""
        # print len(envlist)
+
display = ""
 
+
user = ""
        espeaker = ""
+
shlvl = ""
        display = ""
+
# Get $USER, $DISPLAY, $HOME, $ESPEAKER ..
        user = ""
+
for en in envlist:
        shlvl = ""
+
if en.startswith("USER="):
 
+
user = en[5:]
        # Get $USER, $DISPLAY, $HOME, $ESPEAKER ..
+
# Skip, if this is a system process ..
        for en in envlist:
+
if user == "root" or user.isdigit():
          if en[0:5] == "USER=":
+
break
            user = en[5:]
+
if en.startswith("DISPLAY="):
            # Skip, if this is a system process ..
+
display = en[8:]
            if (user == "root") or (user.isdigit()):
+
os.environ['DISPLAY'] = display
              break
+
elif en.startswith("HOME="):
          if en[0:8] == "DISPLAY=":
+
home = en[5:]
            display = en[8:]
+
os.environ['HOME'] = home
            os.environ['DISPLAY'] = display
+
elif en.startswith("ESPEAKER="):
          elif en[0:5] == "HOME=":
+
espeaker = en[9:]
            home = en[5:]
+
os.environ['ESPEAKER'] = espeaker
            os.environ['HOME'] = home
+
subprocess.Popen(['export ESPEAKER'], shell=True)
          elif en[0:9] == "ESPEAKER=":
+
elif en.startswith("SHLVL="):
            espeaker = en[9:]
+
shlvl = en[6:]
            os.environ['ESPEAKER'] = espeaker
+
try:
            subprocess.Popen(['export ESPEAKER'], shell=True)
+
# Some filtering ..
          elif en[0:6] == "SHLVL=":
+
# eg. exclude $DISPLAY=nx/nx,options=/home/sinead/.nx/C-Buddy-1001 ..
            shlvl = en[6:]
+
if "," in display:
 
+
continue
        try:
+
# eg. exclude $DISPLAY=:1.0
          # Some filtering ..
+
if display[0] == ":":
          # eg. exclude $DISPLAY=nx/nx,options=/home/sinead/.nx/C-Buddy-1001 ..
+
continue
          if (display.find(",") != -1):
+
# Add .0 - eg. unix:1000->unix:1000.0 (else get duplication)
            continue
+
if "." not in display:
          # eg. exclude $DISPLAY=:1.0
+
display+= ".0"
          if (display[0] == ":"):
+
except:
            continue
+
continue
          # Add .0 - eg. unix:1000->unix:1000.0 (else get duplication)
+
# Send Popup Message to User's Screen using gxmessage ..
          if (display.find(".") == -1):
+
# Use shlvl to identify real users (for example, excludes gdm)
            display=display + ".0"
+
# Shell=True is important - else doesn't work ..
        except:
+
if user != "" and display != "" and shlvl != "":
          continue
+
try:
 
+
# Only send to the display if it hasn't already been done.
        # Send Popup Message to User's Screen using gxmessage ..
+
result=displaylist.index(display)
        # Use shlvl to identify real users (for example, excludes gdm)
+
except:
        # Shell=True is important - else doesn't work ..
+
if espeaker != "" and wavefile != "":
        if (user != "") and (display != "") and (shlvl != ""):
+
print "%s - Display='%s' Speaker='%s'" % (user, display, espeaker)
          try:
+
else:
            # Only send to the display if it hasn't already been done.
+
print "%s - Display='%s'" % (user, display)
            result=displaylist.index(display)
+
subprocess.Popen(['sudo -u %s gxmessage -center ' \
          except:
+
'-timeout %s -display %s -title "%s" "%s"' % \
            if (espeaker != "") and (wavefile != ""):
+
(user, timeout, display, title, message)], shell=True)
              print "%s - Display='%s' Speaker='%s'" % (user, display, espeaker)
+
# If user's session supports ESD sound - eg. an NX session and
            else:
+
# a wave file is specified, play a sound/music, also ..
              print "%s - Display='%s'" % (user, display)
+
if espeaker != "" and wavefile != "":
 
+
subprocess.Popen(['sudo -u %s esdplay %s' % (user, wavefile)],
            subprocess.Popen(['sudo -u ' + user + ' gxmessage -center ' \
+
shell=True)
              + '-timeout ' + str(timeout) + ' -display ' + display \
+
# Register this display as alerted.
              + ' -title "' + title + '" "' + message + '"'], shell=True)
+
displaylist.append(display)
 
+
            # If user's session supports ESD sound - eg. an NX session and
+
            # a wave file is specified, play a sound/music, also ..
+
            if (espeaker != "") and (wavefile != ""):
+
              subprocess.Popen(['sudo -u ' + user + ' esdplay ' + wavefile],
+
                                                        shell=True)
+
 
+
            # Register this display as alerted.
+
            displaylist.append(display)
+
 
# -------------------------------------------------------------
 
# -------------------------------------------------------------
 
# Do it ! ...
 
# Do it ! ...

2010年5月19日 (三) 16:56的版本

This page describes how to send pop-up messages to NX and X-windows sessions. With the NX sessions, these messages can be accompanied by sound. This was developed using Ubuntu 7.04 (Feisty).

Introduction

The Python script below was developed to send pop-up messages with sound to NX and X sessions running on a Ubuntu server. This was developed on a home network consisting of a Ubuntu 7.04 server running FreeNX, and Windows PCs and Ubuntu/Xubuntu PCs running the nomachine NX client or X-Windows. The NX clients are configured to support sound, but the X-windows clients receive only a silent pop-up message.

Dependencies

The script uses gxmessage to send the pop-up messages, and esdplay to transmit a .wav sound file. Gxmessage is a requirement to run the script. Esound needs to be installed if sound functionality is required.

sudo aptitude install gmessage
sudo aptitude install esound

Setting up NX Sessions for Sound

This section is not required to get the script running without sound. If you want to get the script running quickly, you can skip this section, and come back to it later. Follow the FreeNX instructions to install FreeNX on a Ubuntu server. Ensure that esound is installed (see above), and that the esd service is running like so ..

ps -e | grep 'esd'
17249 ?        00:00:00 esd

Download the 'NX Client DEB for Linux' or 'NX client for Windows' from http://www.nomachine.com/download.php and install on your Ubuntu and Windows PCs. In the configuration of the NX client, click on the 'Services' tab, and tick 'Enable Multimedia Support' - this enables sound for the NX client. Each user needs to log onto your Ubuntu server using their NX client, and start System/Preferences/Sound from the panel. They need to choose 'ESD - Enlightened Sound Daemon' for the various sound options. They can test the sound while making these selections.

Creating and Running the Script

Copy the script code below into a file called bcast.py. Ensure that this script is executable by using the chmod command.

chmod 755 bcast.py

The script needs to be run using the sudo prefix if you are not logged in as root.

sudo ./bcast --message "Message" --title "Title" --timeout 0 --sound "wavefile.wav"

The script can be called from within cron jobs that are running using the root account. This is the text that needs to be copied into bcast.py ..

#!/usr/bin/python
# Author: David Collins, 2007
# Note: Changing values in os.environ does not affect calling process's environment
"""
Broadcast a pop-up message to X and NX sessions.  A .wav can be specified to
send sound with the message, but this will only be received by NX sessions.
Usage: sudo ./bcast.py --message "message" [--title "title"] [--timeout secs]
[--sound "wavefile.wav"]
"""
import os, subprocess, sys, getopt
# -------------------------------------------------------------
def usage(msg=None):
sys.stdout = sys.stderr
if msg != "":
print msg
print <u>doc</u>
sys.exit(2)
# -------------------------------------------------------------
def processargs():
global title, message, wavefile, timeout
# Default values ..
title = "Alert"
message = ""
wavefile = ""
timeout = 0
optionlist = [[UbuntuHelp:message=","title=","timeout=","sound=]]
try:
opts, args = getopt.getopt(sys.argv[1:], "", optionlist)
if len(opts) < 1:
raise getopt.error, ""
except getopt.error, msg:
usage(msg)
try:
for opt, val in opts:
if val.startswith("--"):  # 2 options with no value between
raise Exception("Option '%s' has no associated value." % opt)
# print opt, "=", val
if opt == "--message":
message = val
elif opt == "--title":
title = val
elif opt == "--sound":
wavefile = val
elif opt == "--timeout":
try:
timeout = int(val)
except:
raise Exception("Timeout value '%s' is not an integer." % val)
except Exception, msg:
usage(msg)
for arg in args:
print "***" + arg
# -------------------------------------------------------------
def checkdependancies():
# Make sure that gxmessage is available ..
# PIPE was not defined - so used -1
p = subprocess.Popen(['which gxmessage'], stdout=-1, shell=True)
result = p.wait()
if result != 0:
print "Gxmessage needs to be installed."
print "On ubuntu, run 'sudo apt-get install gxmessage'."
exit(-2)
# Make sure that esdplay is available ..
p = subprocess.Popen(['which esdplay'], stdout=-1, shell=True)
result = p.wait()
if result != 0:
print "esdplay is not installed - therefore sound will not function."
print "On ubuntu, run 'sudo apt-get install esound' to enable sound."
# -------------------------------------------------------------
def sendalerts():
# To hold list of displays - to avoid duplication.
displaylist = []
# Get PID list in /proc ..
pidlist = os.listdir("/proc")
for pid in pidlist:
# All number directories are PIDs ..
if pid.isdigit():
try:
envfile = "/proc/" + str(pid) + "/environ"
env = open(envfile)
environ = env.readline()
except:
pass  #readenv=False
else:
# print envfile
envlist = environ.split("\0")
# print len(envlist)
espeaker = ""
display = ""
user = ""
shlvl = ""
# Get $USER, $DISPLAY, $HOME, $ESPEAKER ..
for en in envlist:
if en.startswith("USER="):
user = en[5:]
# Skip, if this is a system process ..
if user == "root" or user.isdigit():
break
if en.startswith("DISPLAY="):
display = en[8:]
os.environ['DISPLAY'] = display
elif en.startswith("HOME="):
home = en[5:]
os.environ['HOME'] = home
elif en.startswith("ESPEAKER="):
espeaker = en[9:]
os.environ['ESPEAKER'] = espeaker
subprocess.Popen(['export ESPEAKER'], shell=True)
elif en.startswith("SHLVL="):
shlvl = en[6:]
try:
# Some filtering ..
# eg. exclude $DISPLAY=nx/nx,options=/home/sinead/.nx/C-Buddy-1001 ..
if "," in display:
continue
# eg. exclude $DISPLAY=:1.0
if display[0] == ":":
continue
# Add .0 - eg. unix:1000->unix:1000.0 (else get duplication)
if "." not in display:
display+= ".0"
except:
continue
# Send Popup Message to User's Screen using gxmessage ..
# Use shlvl to identify real users (for example, excludes gdm)
# Shell=True is important - else doesn't work ..
if user != "" and display != "" and shlvl != "":
try:
# Only send to the display if it hasn't already been done.
result=displaylist.index(display)
except:
if espeaker != "" and wavefile != "":
print "%s - Display='%s' Speaker='%s'" % (user, display, espeaker)
else:
print "%s - Display='%s'" % (user, display)
subprocess.Popen(['sudo -u %s gxmessage -center ' \
'-timeout %s -display %s -title "%s" "%s"' % \
(user, timeout, display, title, message)], shell=True)
# If user's session supports ESD sound - eg. an NX session and
# a wave file is specified, play a sound/music, also ..
if espeaker != "" and wavefile != "":
subprocess.Popen(['sudo -u %s esdplay %s' % (user, wavefile)],
shell=True)
# Register this display as alerted.
displaylist.append(display)
# -------------------------------------------------------------
# Do it ! ...
processargs()
checkdependancies()
sendalerts()