使用python实现netcat
时间: 2024-01-01 16:04:53 浏览: 123
以下是Python实现Netcat的样例代码:
```python
import argparse
import socket
import threading
import subprocess
def send_recv(sock):
while True:
data = sock.recv(1024)
if not data:
break
sock.sendall(data)
print(data.decode())
def listen(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', port))
sock.listen(1)
conn, addr = sock.accept()
print(f'Connected by {addr}')
send_recv(conn)
conn.close()
def connect(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
send_recv(sock)
sock.close()
def execute(cmd):
result = subprocess.check_output(cmd, shell=True)
return result
def main():
parser = argparse.ArgumentParser(description='Netcat')
parser.add_argument('-l', '--listen', action='store_true', help='listen mode')
parser.add_argument('-c', '--connect', metavar='HOST', help='connect mode')
parser.add_argument('-p', '--port', type=int, default=8888, help='port')
parser.add_argument('-e', '--execute', metavar='CMD', help='execute command')
args = parser.parse_args()
if args.listen:
listen(args.port)
elif args.connect:
connect(args.connect, args.port)
elif args.execute:
result = execute(args.execute)
print(result.decode())
if __name__ == '__main__':
main()
```
使用方法:
- 监听模式:`python netcat.py -l -p 8888`
- 连接模式:`python netcat.py -c 127.0.0.1 -p 8888`
- 执行命令:`python netcat.py -e "ls -la"`
阅读全文