侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   247

本文实例讲述了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 timeimport socketimport threadingimport tracebackimport subprocessdef 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      breakif __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 timeimport socketdef 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()      breakif __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迭代dict的key和value的方法
    下一条:
    python脚本监控Tomcat服务器的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客