Python socket套接字实现C/S模式远程命令执行功能案例


Posted in Python onJuly 06, 2018

本文实例讲述了Python socket套接字实现C/S模式远程命令执行功能。分享给大家供大家参考,具体如下:

一. 前言

要求:

使用python的socket套接字编写服务器/客户机模式的远程命令执行脚本。

serverCmd.py 远程机器上用来执行客户端发送命令的脚本
clientCmd.py 本地机器上,向远程服务器发送命令的脚本
servers.txt  本地机器上,存放所有的远程服务器IP地址文件(仅支持第一个IP)

发送:cmd [command]形式消息,让远程主机执行命令(本地主机无回显)

发送:close session消息,双方关闭会话。

二. 源码

下载地址: 点击此处本站下载

注:

1. 代码注释较少,建议有一定套接字编程基础。
2. 或者直接简单部分修改IP使用。
3. clientCmd.py和servers.txt(修改IP地址后)放在同一目录。
4.程序为简单Demo,仅为学习记录。

serverCmd.py

#!/usr/bin/env python
# coding:utf-8
# Build by LandGrey
#
import time
import socket
import threading
import traceback
import subprocess
def parsecmd(strings):
  midsplit = str(strings).split(" ")
  if len(midsplit) >= 2 and midsplit[0] == "cmd":
    try:
      command = subprocess.Popen(strings[4:], shell=True)
      command.communicate()
      print "\n"
    except Exception, e:
      print e.message
      traceback.print_exc()
def recvdata(port):
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind(('', port))
  s.listen(1)
  print "[+] Server is running on port:%s at %s" % (str(port), time.strftime("%Y%m%d %H:%M:%S", time.localtime()))
  while True:
    mainsocket, mainhost = s.accept()
    print "[+] Connect success -> %s at %s" % (str(mainhost), time.strftime("%Y%m%d %H:%M:%S", time.localtime()))
    if mainhost:
      while True:
        data = mainsocket.recv(1024)
        if data:
          print "[+] Receive:%s" % data
          mainsocket.sendall("[Server]success")
          parsecmd(data)
        if data == "close session":
          mainsocket.close()
          print "[+] Quit success"
          break
      break
if __name__ == "__main__":
  # some public variable
  connPort = 47091
  onethreads = threading.Thread(target=recvdata, args=(connPort,))
  onethreads.start()

clientCmd.py

#!/usr/bin/env python
# coding:utf-8
# Build by LandGrey
#
import time
import socket
def readtarget():
  global server_list
  with open(r"servers.txt") as f:
    for line in f.readlines():
      if line[0:1] != "#" and len(line.split(".")) == 4:
        server_list.append(line)
def connserver(host, port):
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect((host, port))
  while True:
    print "\n[*] Please input command:"
    data = raw_input()
    if not data:
      break
    s.sendall(data)
    recvdata = s.recv(1024)
    print "[+] Send %s:%s -> %s" % (host, str(connPort), data)
    time.sleep(0)
    if recvdata:
      print "[+] Receive :%s" % recvdata
    if data == "close session":
      s.close()
      break
if __name__ == "__main__":
  server_list = []
  connPort = 47091
  readtarget()
  if server_list != []:
    for host in server_list:
      connserver(host, connPort)

servers.txt

# server ip list
192.168.0.139

三. 运行效果

python serverCmd.py

[+] Server is running on port:47091 at 20161013 17:50:19
[+] Connect success -> ('192.168.0.241', 4255) at 20161013 17:50:32
[+] Receive:hello
[+] Receive:你好
[+] Receive:cmd ip
'ip' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

[+] Receive:cmd ipconfig

Windows IP 配置

以太网适配器 本地连接:

   连接特定的 DNS 后缀 . . . . . . . :
   本地链接 IPv6 地址. . . . . . . . : ****::****:****:****:*******
   IPv4 地址 . . . . . . . . . . . . : 192.168.0.139
   子网掩码  . . . . . . . . . . . . : 255.255.255.0
   默认网关. . . . . . . . . . . . . : 192.168.0.1

隧道适配器 isatap.{****-6122-4F83-8828-****}:

   媒体状态  . . . . . . . . . . . . : 媒体已断开
   连接特定的 DNS 后缀 . . . . . . . :

[+] Receive:cmd ping www.baidu.com

正在 Ping www.a.shifen.com [180.97.33.108] 具有 32 字节的数据:
来自 180.97.33.108 的回复: 字节=32 时间=66ms TTL=36
来自 180.97.33.108 的回复: 字节=32 时间=66ms TTL=36
来自 180.97.33.108 的回复: 字节=32 时间=64ms TTL=36
来自 180.97.33.108 的回复: 字节=32 时间=65ms TTL=36

180.97.33.108 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 64ms,最长 = 66ms,平均 = 65ms

[+] Receive:要结束了
[+] Receive:close session
[+] Quit success

python clientCmd.py

[*] Please input command:
hello
[+] Send 192.168.0.139:47091 -> hello
[+] Receive :[Server]success

[*] Please input command:
你好
[+] Send 192.168.0.139:47091 -> 你好
[+] Receive :[Server]success

[*] Please input command:
cmd ip
[+] Send 192.168.0.139:47091 -> cmd ip
[+] Receive :[Server]success

[*] Please input command:
cmd ipconfig
[+] Send 192.168.0.139:47091 -> cmd ipconfig
[+] Receive :[Server]success

[*] Please input command:
cmd ping www.baidu.com
[+] Send 192.168.0.139:47091 -> cmd ping www.baidu.com
[+] Receive :[Server]success

[*] Please input command:
要结束了
[+] Send 192.168.0.139:47091 -> 要结束了
[+] Receive :[Server]success

[*] Please input command:
close session
[+] Send 192.168.0.139:47091 -> close session
[+] Receive :[Server]success

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python实现的生成自我描述脚本分享(很有意思的程序)
Jul 18 Python
对Python新手编程过程中如何规避一些常见问题的建议
Apr 01 Python
深入了解Python数据类型之列表
Jun 24 Python
使用Python脚本实现批量网站存活检测遇到问题及解决方法
Oct 11 Python
Python的argparse库使用详解
Oct 09 Python
python ---lambda匿名函数介绍
Mar 13 Python
python实现AES加密解密
Mar 28 Python
树莓派用python中的OpenCV输出USB摄像头画面
Jun 22 Python
Python爬虫谷歌Chrome F12抓包过程原理解析
Jun 04 Python
Python中random模块常用方法的使用教程
Oct 04 Python
Python urllib库如何添加headers过程解析
Oct 05 Python
浅谈Python从全局与局部变量到装饰器的相关知识
Jun 21 Python
python脚本监控Tomcat服务器的方法
Jul 06 #Python
解决csv.writer写入文件有多余的空行问题
Jul 06 #Python
Python简单爬虫导出CSV文件的实例讲解
Jul 06 #Python
Python实现的从右到左字符串替换方法示例
Jul 06 #Python
Python用csv写入文件_消除空余行的方法
Jul 06 #Python
Python实现string字符串连接的方法总结【8种方式】
Jul 06 #Python
python 读取目录下csv文件并绘制曲线v111的方法
Jul 06 #Python
You might like
PHP简单实现解析xml为数组的方法
2018/05/02 PHP
脚本安需导入(装载)的三种模式的对比
2007/06/24 Javascript
jquery随机展示头像代码
2011/12/21 Javascript
javascript编码的几个方法详细介绍
2013/01/06 Javascript
JavaScript事件处理器中的event参数使用介绍
2013/05/24 Javascript
ie8本地图片上传预览示例代码
2014/01/12 Javascript
javascript实现的元素拖动函数宿主为浏览器
2014/07/21 Javascript
Javascript中prototype属性实现给内置对象添加新的方法
2015/05/14 Javascript
jQuery拖拽排序插件制作拖拽排序效果(附源码下载)
2016/02/23 Javascript
一款简单的jQuery图片标注效果附源码下载
2016/03/22 Javascript
jQuery CSS3自定义美化Checkbox实现代码
2016/05/12 Javascript
AngularJS使用拦截器实现的loading功能完整实例
2017/05/17 Javascript
vue 组件高级用法实例详解
2018/04/11 Javascript
nodejs读取并去重excel文件
2018/04/22 NodeJs
基于vue cli 通过命令行传参实现多环境配置
2018/07/12 Javascript
javscript 数组扁平化的实现
2020/02/03 Javascript
使用tensorflow实现AlexNet
2017/11/20 Python
python爬虫面试宝典(常见问题)
2018/03/02 Python
Python + selenium + requests实现12306全自动抢票及验证码破解加自动点击功能
2018/11/23 Python
python 实现得到当前时间偏移day天后的日期方法
2018/12/31 Python
python实现五子棋小游戏
2020/03/25 Python
python numpy矩阵信息说明,shape,size,dtype
2020/05/22 Python
英国知名美妆护肤在线商城:Zest Beauty
2018/04/24 全球购物
来自世界各地的饮料:Flavourly
2019/05/06 全球购物
英国最大的独立摄影零售商:Park Cameras
2019/11/27 全球购物
CK加拿大官网:Calvin Klein加拿大
2020/03/14 全球购物
C# Debug和Testing相关面试题
2015/10/25 面试题
退伍老兵事迹材料
2014/01/31 职场文书
职工运动会感言
2014/02/07 职场文书
双语教学实施方案
2014/03/23 职场文书
铁路安全事故反思
2014/04/26 职场文书
住院医师规范化培训实施方案
2014/06/12 职场文书
房地产资料员岗位职责
2014/07/02 职场文书
2014年幼儿园国庆主题活动方案
2014/09/16 职场文书
2015迎新晚会活动总结
2015/07/16 职场文书
解决jupyter notebook图片显示模糊和保存清晰图片的操作
2021/04/24 Python