利用python模拟netcat

import socket
import sys
import subprocess
import getopt

def server_connected(port):
info = sys.platform
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.bind(("0.0.0.0", port))
server.listen(5)
print(f"Listening to {port}")
conn, addr = server.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(4096)
if not data:
break
try:
command = data.decode("utf-8")
if info.startswith("linux"):
command_output = subprocess.run(command, shell=True, executable="/bin/bash", capture_output=True)
output = command_output.stdout.decode("utf-8") + command_output.stderr.decode("utf-8")
elif info.startswith("win"):
command_output = subprocess.run(command, shell=True, capture_output=True)
output = command_output.stdout.decode("gbk") + command_output.stderr.decode("gbk")
except Exception as e:
output = str(e)
conn.sendall(output.encode("utf-8") if info.startswith("linux") else output.encode("gbk"))
conn.close()
server.close()

def client_connected(host, port):
info = sys.platform
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((host, port))
print(f"Connected to {host}:{port}")
while True:
data = input(">>> ")
if data.lower() == "exit":
break
client.sendall(data.encode("gbk") if info.startswith("win") else data.encode("utf-8"))
response = client.recv(4096)
if not response:
break
print(response.decode("gbk") if info.startswith("win") else response.decode("utf-8"))
client.close()

def run_args():
host = ""
port = 0
listen = False
try:
opts, args = getopt.getopt(sys.argv[1:], "lh:p:", ["listen", "host", "port"])
except getopt.GetoptError as e:
print(f"Error: {e}")
sys.exit(1)

for o, a in opts:
if o in ("-l", "--listen"):
listen = True
if o in ("-h", "--host"):
host = a
if o in ("-p", "--port"):
port = int(a)

if listen and port > 0:
server_connected(port)
elif len(host) > 0 and port > 0:
client_connected(host, port)

if __name__ == "__main__":
run_args()

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值