使用socket.gethostname()在python for循环中定义一个字符串

时间:2014-01-15 15:50:59

标签: python sockets

所以,我正在尝试使用socket.gethostname()为我返回服务器的名称。然后我想取该服务器的名称并将其更改为其他内容并将其存储为变量。

例如,如果a有一个名为“MyTestServer”的服务器,我想获取该名称,然后将其存储为字符串'test'。我认为下面的代码可以在PYthon中运行,但它不是......有什么建议吗?

 for name in socket.gethostname():
        if name is 'MyTestServer':
            strjil = 'test'

3 个答案:

答案 0 :(得分:1)

is运算符用于比较对象的标识。您需要使用==来比较值:

if name == 'MyTestServer':

这是关于Python中比较对象的reference

答案 1 :(得分:1)

>>> import socket
>>> name = socket.gethostname()
>>> if name == "MyTestServer":
...   strjil = "test"
... 

(我不确定strjilname的关系如何,所以我按原样离开了。)

答案 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
# ...