Python:Netcat function doen不起作用



当我在Linux上使用此命令时,它可以工作:

echo "test.bash.stats 44 1459116000" | nc myhostname.com 2003

但是现在,我尝试在Python脚本中实现这个命令。

方法1:使用os.system("")

# this works
os.system("echo 'test.bash.stats 14 1459116000' | nc myhostname.com 2003")
#It does not work because there are a problem with quote
data['time_timestamp'] = 1459116000
os.system("echo 'test.bash.stats 14 "data['time_timestamp']"' | nc myhostname.com 2003")

方法2:使用套接字

import socket
def netcat(hostname, port, content):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.sendall(content)
    s.shutdown(socket.SHUT_WR)
    while 1:
        data = s.recv(1024)
        if data == "":
            break
        print "Received:", repr(data)
    print "Connection closed."
    s.close()
netcat("myhostname.com", 2003, "test.bash.stats 14 1459116000")

我没有收到错误,但我没有收到数据。

您应该尝试像以下一样连接字符串

os.system("echo 'test.bash.stats 14 " + str(data['time_timestamp']) + " '| nc myhostname.com 2003")

或者这个

os.system("echo 'test.bash.stats 14 %d '| nc myhostname.com 2003" % data['time_timestamp'])

最新更新