所以,我正在尝试使用socket.gethostname()
为我返回服务器的名称。然后我想取该服务器的名称并将其更改为其他内容并将其存储为变量。
例如,如果a有一个名为“MyTestServer”的服务器,我想获取该名称,然后将其存储为字符串'test'。我认为下面的代码可以在PYthon中运行,但它不是......有什么建议吗?
for name in socket.gethostname():
if name is 'MyTestServer':
strjil = 'test'
答案 0 :(得分:1)
答案 1 :(得分:1)
>>> import socket
>>> name = socket.gethostname()
>>> if name == "MyTestServer":
... strjil = "test"
...
(我不确定strjil
与name
的关系如何,所以我按原样离开了。)
答案 2 :(得分:1)
如果您只是谈论自己机器的名称(运行代码的机器名称):
import socket
# Get the local hostname as a string (a chain of characters)
myname = socket.gethostname()
# Compare this name to some value (another string) and do something special
# (This is an example)
if myname == "MyTestServer":
print("You are running on the right host")
# If the name of the host is not the one expected, we can imagine to abort the
# program (just an example)
else:
print("You may not run this script on that computer")
exit(1) # Quit program
# You can try changing your own host name
try:
socket.sethostname("NewName")
# This may fail because of permissions
except OSError as e:
print("Could not change my own name:", e)
exit(1) # Quit program
如果要获取远程计算机的主机名,则需要先在它们之间创建连接。你将无法强迫他们使用python改变他们的名字。
# Now, do something with other systems
# Create a listening socket on port 8888 and accept connection on it
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 8888))
sock.listen(1)
conn, addr = sock.accept()
# Get some information about the client who connected to us
clientinfo = conn.getpeername()
# It is actually a tuple containing hostname and port
distantname, port = clientinfo
# Here you can also do something special with it
if distantname != "AcceptedClient":
print("Intruder!!")
sock.shutdown(socket.SHUT_RDWR)
sock.close()
exit(1)
# However, you cannot change that name, unless you ask the client politely to do
# that on his side
# Maybe for example:
sock.send(b"CHANGENAME NewClientName\n")
# Then the client would have code that reacts to that command and do the
# necessary
# ...