实现开放端口,返回命令行结果

修改自:https://github.com/AllGloryToTheHypnotoad/Black-Hat-Python/blob/master/BHP-Code/Chapter2/bhnet.py

#!/usr/bin/python3import socket
import getopt
import threading
import subprocess
import sys
import traceback# define some global variables
listen = False
target = ""
port = 9999def usage():print("Python Net Tool")print()print("Usage: pnt.py -t target_host -p port")print("-l --listen - listen on [host]:[port] for incoming connections")print()print()print("Examples: ")print("pnt.py -t 192.168.0.1 -p 5555 -l -c")print("pnt.py -p 5555 -l")sys.exit(0)def main():global listenglobal portglobal executeglobal commandglobal upload_destinationglobal targetif not len(sys.argv[1:]):usage()# read the commandline optionstry:opts, args = getopt.getopt(sys.argv[1:],"hlt:p:",["help","listen","target","port"])# colon ':' means option requires argumentexcept getopt.GetoptError as err:print(str(err))usage()for o,a in opts:if o in ("-h","--help"):usage()elif o in ("-l","--listen"):listen = Trueelif o in ("-t", "--target"):target = aelif o in ("-p", "--port"):port = int(a)else:assert False,"Unhandled Option"if listen:server_loop()else:client_loop()  def client_loop():client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)try:# connect to our target hostclient.connect((target,port))while True:# now wait for data backrecv_len = 1response = ""while recv_len:data = client.recv(4096)recv_len = len(data)response+= data.decode()if recv_len < 4096:breakprint(response, end=' ')# wait for more inputbuffer = input("")buffer += "\n"# send it offclient.send(buffer.encode())except Exception as e:traceback.print_exc()print("[*] Exception! Exiting.")# tear down the connectionclient.close()def server_loop():global target# if no target is defined, we listen on all interfacesif not len(target):target = "0.0.0.0"server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server.bind((target,port))server.listen(5)while True:client_socket, addr = server.accept()# spin off a thread to handle our new clientclient_thread = threading.Thread(target=client_handler, args=(client_socket,))client_thread.start()def client_handler(client_socket):client_socket.send(">>> ".encode())while True:# now we receive until we see a linefeed (enter key)cmd_buffer = ""while "\n" not in cmd_buffer:cmd_buffer += client_socket.recv(1024).decode()# send back the command outputresponse = run_command(cmd_buffer)# send back the responseclient_socket.send(response+"\n>>> ".encode())def run_command(command):# return bytescommand = command.rstrip()# run the command and get the output backtry:output = subprocess.check_output(command,stderr=subprocess.STDOUT, shell=True)except:output = "Failed to execute command.\r\n".encode()# send the output back to the clientreturn outputmain()

python 简单 socket 编程相关推荐

  1. python的socket编程_Python Socket编程详细介绍

    在使用Python做socket编程时,由于需要使用阻塞(默认)的方式来读取数据流,此时对于数据的结束每次都需要自己处理,太麻烦.并且网上也没找到太好的封装,所以就自己写了个简单的封装. 封装思路 1 ...

  2. Python:socket编程教程

    ocket是基于C/S架构的,也就是说进行socket网络编程,通常需要编写两个py文件,一个服务端,一个客户端. 首先,导入Python中的socket模块: import socket Pytho ...

  3. Python中Socket编程

    目录 Python中Socket编程 1 一.Socket概述 1 二.python中socket模块使用 1 三.socket之聊天室 3 四.socket之端口探测 7 五.scapy之tcp端口 ...

  4. Linux下简单socket编程

    Linux下简单socket编程 socket的英文翻译是接口.插座的意思,很形象,就相当于将两个台电脑用一根线连起来,线的两头分别是插头,插在两台电脑上,借此实现通信. 两台电脑通信,实际上是这两台 ...

  5. Python基础-socket编程

    一.网络编程 自从互联网诞生以来,现在基本上所有的程序都是网络程序,很少有单机版的程序了. 计算机网络就是把各个计算机连接到一起,让网络中的计算机可以互相通信.网络编程就是如何在程序中实现两台计算机的 ...

  6. python socket编程_最基础的Python的socket编程入门教程

    本文介绍使用Python进行Socket网络编程,假设读者已经具备了基本的网络编程知识和Python的基本语法知识,本文中的代码如果没有说明则都是运行在Python 3.4下. Python的sock ...

  7. 使用 Python 进行 socket 编程

    (5)类定义语句  所有的类都需要在这里定义.当模块被导入时 class 语句会被执行, 类也就会被定义.类 的文档变量是 class.__doc__.  (7) 主程序  无论这个模块是被别的模块导 ...

  8. python 简单网络编程

    目录 1. 基础知识 1.1 什么是协议 1.2 有哪些协议 1.3 分层模型 1.4 什么是套接字Socket编程 1.5 套接字通信过程 2. Python实现 2.1 socket 2.2 so ...

  9. python 12 socket 编程

    1.socket编程需要两个部分 服务器与客户端我们的python中调用 socket包就不需要自己写协议了(socket编程中windows 与Linux中的效果是完全不相同了,次代码最好是放在Li ...

  10. python之socket编程

    From : http://www.cnblogs.com/aylin/p/5572104.html 1.socket socket起源于Unix,而Unix/Linux基本哲学之一就是"一 ...

最新文章

  1. 初探Django2.1:Win10+Python3.6.6环境下安装Django
  2. IKAnalyzer使用停用词词典进行分词
  3. 数据仓库中的维度表和事实表概述
  4. lisp点转为vla_一种将Region转为Polyline的方法
  5. asp.net 二级域名(路由方式实现)
  6. 200道物理学难题——038蚱蜢跃树
  7. opencv调试利器ImageWatch的安装使用
  8. 为什么企业宁愿花 15K 重新招人,也不愿意花 10K 留住老测试员?
  9. jdbc mysql innodb 死锁 deadlock_Mysql InnoDB 数据更新/删除导致锁表
  10. 【avx2】VitrualBox 安装centos7 支持avx2
  11. pm2 status errored
  12. 在 Nebula K8s 集群中使用 nebula-spark-connector 和 nebula-algorithm
  13. matlab 跳步,给定两个大整数u和v,它们分别有m和n位数字,且m≤n.用通常的乘法求uv的值需要O(mn)时间.可以将u和v.. - 上学吧找答案(手机版)...
  14. HTML 限制文本框只能输入数字 onkeyup+onafterpaste
  15. 联想ghost重装系统_联想笔记本系统重装图文教程
  16. 软件工程专业就业方向
  17. Clang调试诊断信息Expressive Diagnostics
  18. 6.xp 开机画面【欢迎使用】四个字更改方法:
  19. 1.GraspNet-API之Grasp Lable Format
  20. android 模拟器监听短信,android模拟器用命令和DDMS模拟来电和短信(示例代码)

热门文章

  1. 广告JS代码效果大全
  2. Dreamweaver网页设计与制作100例:用DIV+CSS技术设计的书法主题网站(web前端网页制作课作业)...
  3. 对于代理服务器的理解
  4. linux硬盘温度,linux查看硬盘温度和使用情况
  5. Unity安卓开发环境搭建
  6. c语言图书管理系统报告书,c语言图书管理系统实验报告_c语言程序设计报告 图书管理平台_c语言 图书管理平台...
  7. 苹果助手一键安装_再见!国内经典的iOS越狱助手,正式宣布下线
  8. android签名命令行,Android系统签名位置及命令
  9. 在android系统中制作系统签名jks
  10. CentOS7|Redhat7挂载NTFS格式磁盘