[英]python equivalent of netcat
我有一個 TCP 服務器,我需要用 Python 為其編寫一個客戶端。
服務器是使用arduino_uip庫的 arduino; 服務器代碼(幾乎)與該庫的TCP 服務器示例相同。 使用 nc 作為客戶端可以正常工作。
但是當我使用 python 套接字(如在這個答案中)與服務器通信時,服務器在套接字關閉或關閉時掛起。
那可能是服務器的問題; 但是,由於 nc 作為客戶工作正常,我的問題是:
這個答案與 nc 有什么不同,nc 可以解釋服務器在連接關閉/關閉時掛起)?
總結什么有效,什么無效:
這是客戶端代碼:
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()
編輯 :
看來(Vorsprung 的回答讓我想到了!)這實際上是一個時間問題。 如果我在關閉之前在上面的代碼中添加 sleep(0.5) 一切都很好(就像在 netcat 中,在我按下 Ctrl+C 之前有一個手動延遲)。 我想我現在必須檢查那個arduino庫......
查看了 netcat 源代碼( svn checkout svn://svn.code.sf.net/p/netcat/code/trunk netcat-code ),它只在關閉之前調用 shutdown(),而不僅僅是在設置之后調用插座
這就是我所看到的區別
python相當於netcat
使用 nclib:pip install nclib
文檔: https : //nclib.readthedocs.io/en/latest/
Python 3 netcat 偵聽器,輸入和輸出分別分配給變量 command 和 data。
import nclib
def listener(port):
""" local netcat listener for reverse bash shell from a remote host. """
server = nclib.TCPServer(('0.0.0.0', int(port)))
print("listening ...")
for client in server:
print('Connected to %s:%d' % client.peer)
command = ""
while command != "exit":
try:
# if command was entered by the user
if len(command) > 0:
# read the line to hide command from output
if command in client.readln().decode('utf-8').strip(" "):
pass # disregard the last command
# get output until dollar sign (bash --posix forces bash-X.X$)
data = client.read_until('$')
print(data.decode('utf-8'), end="") # print string of received bytes
# get user input command and write command to socket
command = input(" ")
client.writeln(command)
# handle exceptions and exiting
except KeyboardInterrupt:
print("\nKeyboardInterrupt")
exit(1)
except Exception as e:
print("\nException Occurred\n")
print(e)
exit(1)
print("Disconnected :-)")
exit(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.