Running Windows commands with Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • miago
    New Member
    • Feb 2007
    • 6

    #1

    Running Windows commands with Python

    Searching this forum I found an example of running Unix commands from Python;I wonder if there is a way to get the output of windows commands on a string using Python.
    Originally posted by miago
    I believe command line functionality is built in into Python only for *nix environment.Is there's a windows solution?
    Thanks in advance;
    Miago.
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by miago
    Searching this forum I found an example of running Unix commands from Python;I wonder if there is a way to get the output of windows commands on a string using Python.Thanks in advance;
    Miago.
    It sort of depends on which Window app you are trying to interface to. Most Microsoft products and some third party products are COM (Common Object Model) aware. With the PythonWin package, you can send commands to these apps as if you were using a VB script. If your python program has a full GU interface you could Select the text that you want, then Copy using the VB commands then get the clipboard contents in your program. Or you might be able to SaveAs text and read the resulting file. I've seen an example that copied text from MS Word and pasted it to a web page. The possibilities are endless, but I'm not very familiar with PythonWin. There are some on this forum who are, though. I use wxPython so all my Python programs have almost complete access to Windows' features like the clipboard. PythonWin is another way to do this, but you pretty much have to know the Windows API first.
    Hope this is useful to you,
    Barton

    Comment

    • Motoma
      Recognized Expert Specialist
      • Jan 2007
      • 3236

      #3
      Originally posted by miago
      Searching this forum I found an example of running Unix commands from Python;I wonder if there is a way to get the output of windows commands on a string using Python.Thanks in advance;
      Miago.
      You may be able to do this by reassigning sys.stdout.

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by miago
        Searching this forum I found an example of running Unix commands from Python;I wonder if there is a way to get the output of windows commands on a string using Python.Thanks in advance;
        Miago.
        Good point, motoma. I was thinking of Windows apps, but there may be a way to redirect the output of a Windows command that is designed to echo text to the command-line. Anybody have any experience with this?

        Comment

        • horace1
          Recognized Expert Top Contributor
          • Nov 2006
          • 1510

          #5
          Originally posted by miago
          Searching this forum I found an example of running Unix commands from Python;I wonder if there is a way to get the output of windows commands on a string using Python.Thanks in advance;
          Miago.
          try
          Code:
          import subprocess
          line=subprocess.Popen("test", stdout=subprocess.PIPE).communicate()[0]
          the output from program test.exe will be in line

          Comment

          • dshimer
            Recognized Expert New Member
            • Dec 2006
            • 136

            #6
            I am always interested in the number of ways you can accomplish things in Python, I use the following, does it do basically the same thing, or do you see problems or disadvantages to it?
            Code:
            import os
            CommandOutput=os.popen('dir/w').read()
            or if I am expecting to get back many lines and want it placed in a list I use
            Code:
            import os,string
            CommandOutputList=string.split(os.popen('dir/w').read())

            Comment

            • horace1
              Recognized Expert Top Contributor
              • Nov 2006
              • 1510

              #7
              Originally posted by dshimer
              I am always interested in the number of ways you can accomplish things in Python, I use the following, does it do basically the same thing, or do you see problems or disadvantages to it?
              Code:
              import os
              CommandOutput=os.popen('dir/w').read()
              or if I am expecting to get back many lines and want it placed in a list I use
              Code:
              import os,string
              CommandOutputList=string.split(os.popen('dir/w').read())
              I do not know sufficent python to indicate which is the best approach! do we have a python expert on hand to comment?

              Comment

              • miago
                New Member
                • Feb 2007
                • 6

                #8
                Dear dudes, I did as you advised,but to no success.I type this:
                Code:
                import os
                DNS=raw_input(" DNS")
                CommandOutput=o s.popen('tracer t %s').read()%(DN S)
                print CommandOutput

                And this is what I get:
                "Impossible to resolve to destination system"

                And I don't really understand how to implement this:
                import subprocess
                DNS=raw_input(" Enter DNS")
                line=subprocess .Popen("tracert %s", stdout=subproce ss.PIPE).commun icate()[0] %(DNS)
                I should place an integer somewhere,for I receive this message:

                line=subprocess .Popen("tracert %s", stdout=subproce ss.PIPE).commun icate()[0] %(DNS)
                Traceback (most recent call last):
                File "<input>", line 1, in ?
                File "C:\Python24\li b\subprocess.py ", line 533, in __init__
                (p2cread, p2cwrite,
                File "C:\Python24\li b\subprocess.py ", line 593, in _get_handles
                p2cread = self._make_inhe ritable(p2cread )
                File "C:\Python24\li b\subprocess.py ", line 634, in _make_inheritab le
                DUPLICATE_SAME_ ACCESS)
                TypeError: an integer is required
                >>>

                I thank you all for your kindness and attention;I really want to make progress with this;

                As a last question,I want to ask:getservbyna me simply returns the usual service for a port or does it scan the machine it's running on?If the latter is thecase,then is it possible to scan remote ports using this?I found the manual somewhat ambiguous....Th anks in advance.

                Comment

                • Motoma
                  Recognized Expert Specialist
                  • Jan 2007
                  • 3236

                  #9
                  Originally posted by miago
                  Dear dudes, I did as you advised,but to no success.I type this:
                  Code:
                  import os
                  DNS=raw_input(" DNS")
                  CommandOutput=o s.popen('tracer t %s').read()%(DN S)
                  print CommandOutput

                  And this is what I get:
                  "Impossible to resolve to destination system"

                  And I don't really understand how to implement this:
                  import subprocess
                  DNS=raw_input(" Enter DNS")
                  line=subprocess .Popen("tracert %s", stdout=subproce ss.PIPE).commun icate()[0] %(DNS)
                  I should place an integer somewhere,for I receive this message:

                  line=subprocess .Popen("tracert %s", stdout=subproce ss.PIPE).commun icate()[0] %(DNS)
                  Traceback (most recent call last):
                  File "<input>", line 1, in ?
                  File "C:\Python24\li b\subprocess.py ", line 533, in __init__
                  (p2cread, p2cwrite,
                  File "C:\Python24\li b\subprocess.py ", line 593, in _get_handles
                  p2cread = self._make_inhe ritable(p2cread )
                  File "C:\Python24\li b\subprocess.py ", line 634, in _make_inheritab le
                  DUPLICATE_SAME_ ACCESS)
                  TypeError: an integer is required
                  >>>

                  I thank you all for your kindness and attention;I really want to make progress with this;

                  As a last question,I want to ask:getservbyna me simply returns the usual service for a port or does it scan the machine it's running on?If the latter is thecase,then is it possible to scan remote ports using this?I found the manual somewhat ambiguous....Th anks in advance.

                  Try this:

                  Code:
                  import os
                  DNS=raw_input("DNS")
                  CommandOutput=os.popen('tracert %s' % (DNS)).read()
                  print CommandOutput
                  However, I believe you will need to provide a host for tracert to work.

                  Comment

                  • miago
                    New Member
                    • Feb 2007
                    • 6

                    #10
                    Thank you very much,Motoma;I'v e put the dns outside the scope for string formatting.It works perfectly now.Thank you so much!!As for the other question....Is there any enlightened ones who could clarify the use of getservbyname() for me??I would appreciate very much.Thank you.

                    Comment

                    • miago
                      New Member
                      • Feb 2007
                      • 6

                      #11
                      So it actually verifies the availability of the service by port on a given hostname;in case I give no args,will it default to localhost??The manual does not specify this,if I can remember correctly.Thank you again,Motoma,my journey into the programming world was made smooth by your kindness.

                      Comment

                      • Motoma
                        Recognized Expert Specialist
                        • Jan 2007
                        • 3236

                        #12
                        Originally posted by miago
                        So it actually verifies the availability of the service by port on a given hostname;in case I give no args,will it default to localhost??The manual does not specify this,if I can remember correctly.Thank you again,Motoma,my journey into the programming world was made smooth by your kindness.
                        My appologies, I was mistaken.
                        getservbyname() returns the port number for a given service and protocol.
                        An example:

                        Code:
                        >>> socket.getservbyname("http","tcp")
                        80
                        This shows that the tcp:http protocol should be located on port 80.
                        You can also specify without the second argument.

                        Hope this helps, and welcome to The Scripts.

                        Comment

                        • miago
                          New Member
                          • Feb 2007
                          • 6

                          #13
                          This is what the manual says:

                          "getservbyn ame( servicename[, protocolname])

                          Translate an Internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match. "
                          I see no place for the host/port args....Please be patient!:)


                          I found an interesting page:


                          Doing some research....Be back soon!

                          Comment

                          • Motoma
                            Recognized Expert Specialist
                            • Jan 2007
                            • 3236

                            #14
                            Originally posted by miago
                            This is what the manual says:

                            "getservbyn ame( servicename[, protocolname])

                            Translate an Internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match. "
                            I see no place for the host/port args....Please be patient!:)


                            I found an interesting page:
                            http://gapz.tuxfamily. org/repos/Python/Python_network_ programming.pdf

                            Doing some research....Be back soon!
                            Yes, my apologies, my previous post was incorrect about it's usage.

                            Comment

                            • dshimer
                              Recognized Expert New Member
                              • Dec 2006
                              • 136

                              #15
                              Originally posted by miago
                              As a last question,I want to ask:getservbyna me simply returns the usual service for a port or does it scan the machine it's running on?If the latter is thecase,then is it possible to scan remote ports using this?I found the manual somewhat ambiguous....Th anks in advance.
                              It seems to me to just scan the machine it is running on. Though getaddrinfo seems to return some interesting info if you know what you are looking for. for example for a local network storage device if I get the host ip by name (in this case nas) then send it to getaddrinfo looking for http
                              Code:
                              socket.getaddrinfo(socket.gethostbyname('nas'),'http')
                              returns
                              [(2, 1, 0, '', ('192.168.1.250', 80))]
                              Thouth I'm not really sure what you are looking for

                              Comment

                              Working...