os.popen vs os.system

rbt rbt at athop1.ath.vt.edu
Tue May 17 14:34:40 EDT 2005


Peter Hansen wrote:
> You can't be doing exactly that, since there are no sockets involved... 
> do you mean the above call is executed -- on the receiving end -- after 
> some signal is received via a socket in another part of the code? That's 
> not going to have any effect on things...

Here's the server portion:

from email.MIMEText import MIMEText
import email.Utils
import os
import smtplib
import socket
import sys
import time

def get_server_ip():
     server = socket.gethostbyname(socket.gethostname())
     return server

def set_server_port():
     ## Using "port = 0" will cause a random port to be chosen
     port = 0
     return port

def listen(ip_param, port_param):

     def send_params(ip_param, port_param):
         ## This function will send the network parameters.
         ## Change the to and from email addys.
         f = "XXX<xxx at somewhere.com>"
         t = "someone at somewhere.com"
         msg = MIMEText("""Server IP: %s\nServer Port: %s""" 
%(ip_param,port_param))

         msg["Subject"] = "%s Listening" %socket.gethostname()
         msg["Message-id"] = email.Utils.make_msgid()
         msg["From"] = f
         msg["To"] = t

         h = "smtp.vt.edu"
         s = smtplib.SMTP(h)
         s.sendmail(f, t, msg.as_string())
         s.quit()

     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     try:
         s.bind((ip_param, port_param))
     except socket.error:
         sys.exit("IP & Port Already in use.")
     ip, port = s.getsockname()
     print "Server", ip, "is listening for connections on port", port
     send_params(ip, port)
     while 1:
         print "\nWaiting for new connection...\n"
         s.listen(1)
         conn, addr = s.accept()
         print "Client", addr[0], "connected and was directed to port", 
addr[1]
         data = conn.recv(1024)
         print "Client sent this message:", data
         if data == 'shutdown -r -f':
             print data
##            restart = os.popen('shutdown -r -f')
##            print restart.read()
##            restart.close()
         elif data == 'shutdown -a':
             print data
##            abort = os.popen('shutdown -a')
##            abort.read()
##            abort.close()
         else:
             print "No valid command received."
         conn.close()

# Start the Program

ip = get_server_ip()
port = set_server_port()

listen(ip, port)




More information about the Python-list mailing list