简体   繁体   English

Python:Netcat函数不起作用

[英]Python: Netcat function doen't work

When I use this command on Linux, it works: 当我在Linux上使用此命令时,它可以工作:

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

But now, I try to implement this command in a Python script. 但是现在,我尝试在Python脚本中实现此命令。

Method 1: Use os.system("") 方法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")

Method 2: Use socket 方法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")

I don't get an error, but I don't receive data. 我没有收到错误,但是我没有收到数据。

You should try concatenating the string like this 您应该尝试像这样串联字符串

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

or this 或这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM