Python shell obtains the host name based on the ip address.
In this article, we mainly share the code for getting the ip address from the shell in python by ip address or by hostname. The details are as follows.
I sometimes need to obtain the ip address based on the hostname.
For example, obtain the ip address 10.173.14.117 Based on machine.company.com.
Method 1: Use the gethostbyname function in the socket module
The Code is as follows: Use the socket module
>>> import socket>>> socket.gethostbyname("www.baidu.com")'61.135.169.125'>>> socket.gethostbyname("rs.xidian.edu.cn")'202.117.119.1'
Method 2 use the hostname command in shell
Doubt:
Sometimes the socket is unstable and sometimes the ip address cannot be obtained for specific reasons.
The method I want is not very elegant, tedious, but robust.
The main idea is to write the hostname Information to the file on another machine, and then copy the file to the machine to read the hostname information in the file.
Use plink to run the hostname> % s. hostname command on the remote ip machine to output the hostname Information to the file.
Then, the local pscp is used to copy the text file/root/% s. hostname with hostname on the remote machine to the local machine.
Use the python text reading function to read information and retrieve the hostname string
Final work: Use the rm command to delete both remote machines and local text files
The Code is as follows:
def getHostName(ip): command = 'java -jar %s %s "hostname > %s.hostname"' %(remoteCmdLoca,ip,ip) result = subprocess.call(command, shell=True) command = '%s -q -r -pw passwd %s root@%s:/root' % (pscpLoca, pscpLoca, ip) result = subprocess.call(command, shell=True) command = '%s -q -r -pw passwd root@%s:/root/%s.hostname %s' %(pscpLoca,ip,ip,fileDir) result = subprocess.call(command, shell=True) fileName = fileDir + ip + '.hostname' readFile = open(fileName,'r') hostnameInfo = str(readFile.readline().strip('\n')) readFile.close() subprocess.call('rm '+ fileName, shell=True) print "=========%s hostname is %s========" %(ip,hostnameInfo) return hostnameInfo
The following is a simple example of how to obtain the host name in python in windows. I am a win10 system. I can try it later:
Environment: Windows 10 64-bit + python2.7
The Code is as follows:
import sockethostName = socket.gethostname()
The running result is as follows:
>> import socket>>> hostName = socket.gethostname()>>> print hostNameLAPTOP-H7MGGAAT
Summary
The above is all the content of the code example for getting the host name from the ip address of python shell in this article. I hope it will be helpful to you. Interested friends can continue to refer to this site:
Python auto crop image code sharing
Graph traversal of Python Algorithms
If you have any shortcomings, please leave a message. Thank you for your support!