how to execute the shell script in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • spgreddy
    New Member
    • Nov 2014
    • 4

    how to execute the shell script in python

    Hi,

    I need to execute the below script in python to find the ip address of a host

    /sbin/ifconfig'+'|'+' grep 'inet addr:''+'|'+' grep -v '127.0.0.1''+'| '+'cut -d: -f2'+'|'+'awk '{ print $1}'

    Please let me know how can I execute that in python script.

    Regards,
    Siva
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    socket.gethostb yname(hostname) will return the IPv4 address of a host name.

    Comment

    • spgreddy
      New Member
      • Nov 2014
      • 4

      #3
      Hi bvdet,

      The
      Code:
      socket.gethostbyname(hostname)
      command returns only loopback address 127.0.0.1 but it won't display actual IP address like '10.111.212.111 . Thats the reason i want to execute the below command in python.

      Please let me know how can i execute the below command in python

      Code:
      sbin/ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | 'cut -d: -f2 | awk '{ print $1}'
      Regards,
      Siva

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        How about this:
        Code:
        >>> socket.gethostbyname(socket.gethostname())
        '10.0.0.3'
        >>>
        I'm on Win 7.

        Comment

        • spgreddy
          New Member
          • Nov 2014
          • 4

          #5
          Hi

          I got the answer for this.
          Code:
          import commands
          
          commands.getoutput("/sbin/ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' |cut -d: -f2 | awk '{ print $1}'")
          will return the actual ip address like '10.120.11.123'

          Regards,
          Siva

          Comment

          • dwblas
            Recognized Expert Contributor
            • May 2008
            • 626

            #6
            You can use the subprocess.chec k_output module to get the output from ifconfig and then parse that to find the inet rec. Note that on my system the rec starts with inet, not inet addr.

            Comment

            Working...