By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,041 Members | 1,734 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,041 IT Pros & Developers. It's quick & easy.

how to execute the shell script in python

P: 4
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
Nov 18 '14 #1
Share this Question
Share on Google+
5 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
socket.gethostbyname(hostname) will return the IPv4 address of a host name.
Nov 18 '14 #2

P: 4
Hi bvdet,

The
Expand|Select|Wrap|Line Numbers
  1. 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

Expand|Select|Wrap|Line Numbers
  1. sbin/ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | 'cut -d: -f2 | awk '{ print $1}'
Regards,
Siva
Nov 18 '14 #3

bvdet
Expert Mod 2.5K+
P: 2,851
How about this:
Expand|Select|Wrap|Line Numbers
  1. >>> socket.gethostbyname(socket.gethostname())
  2. '10.0.0.3'
  3. >>> 
I'm on Win 7.
Nov 18 '14 #4

P: 4
Hi

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

Regards,
Siva
Nov 19 '14 #5

Expert 100+
P: 621
You can use the subprocess.check_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.
Nov 19 '14 #6

Post your reply

Sign in to post your reply or Sign up for a free account.